list1 = [2,3,4]
map22 = MapSet.new()
map22 = MapSet.put(map22,25)
for i <- list1 do
map22 = MapSet.put(map22,i)
end
IO.puts("The updated map is #{inspect(map22)}")
When i run the above program i see that the updates within the for loop doesn’t work at all. Why is this so?
Each block, like for, if, case, cond, with, fn define a new scope. You can read values from outer scopes, but you can’t rebind them, as inner scopes have no influence over outer scopes.
An alternative way of writing your code would be
list1 = [2,3,4]
map22 = MapSet.new()
map22 = MapSet.put(map22,25)
map22 =
for i <- list1, reduce: map22 do
map22 -> MapSet.put(map22,i)
end
IO.puts("The updated map is #{inspect(map22)}")
or using Enum.reduce:
list1 = [2,3,4]
map22 = MapSet.new()
map22 = MapSet.put(map22,25)
map22 = Enum.reduce(list1, map22, fn i, map22 -> MapSet.put(map22, i) end)
# or with capture syntax
# map22 = Enum.reduce(list1, map22, &MapSet.put(&2, &1))
IO.puts("The updated map is #{inspect(map22)}")