# Map value is not being added

I am trying to modify a map so that it loops unto itself. The map starts with the values {0 → 1, 1 → 0, 2 → 0, etc} and then loops over to become {0 → 0, 1 → 0, 2 → 0, etc, 6 → 1, 7 → 0)}. This does not happen, instead the value is completely lost and the map is full of zeros, but if I set 1 to 1 instead of 0 to 1 and loop the map twice, the key 7 has a value of 1. Sorry for the bad explanation, its as if the k == 0 does not do anything to the keys.

``````IO.inspect list  # {0 => 1, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0}

list = for {k, v} <- list, into: %{} do
if (k == 0) do
{k + 7, v + elem(Map.fetch(list, 7), 1)}
else
{k - 1, v}
end
end

IO.inspect list  # {0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0, 8 => 0}
# supposed to be   {0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 1, 7 => 0, 8 => 0}
``````

This is the problem - the `k == 0` case produces a result of `{7, 1}`, but the other branch also produces `{7, 0}` when `k` is 8. Maps can only have one value for a particular key, and `into` will take the last one it sees.

If you remove that element from the input and repeatedly apply the `for` loop (copy/paste FTW), you get output like:

``````%{0 => 1, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 0}
%{0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 0, 7 => 1}
%{0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 0, 6 => 1, 7 => 1}
%{0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 => 1, 6 => 1, 7 => 1}
%{0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 1, 5 => 1, 6 => 1, 7 => 1}
%{0 => 0, 1 => 0, 2 => 0, 3 => 1, 4 => 1, 5 => 1, 6 => 1, 7 => 1}
%{0 => 0, 1 => 0, 2 => 1, 3 => 1, 4 => 1, 5 => 1, 6 => 1, 7 => 1}
%{0 => 0, 1 => 1, 2 => 1, 3 => 1, 4 => 1, 5 => 1, 6 => 1, 7 => 1}
%{0 => 1, 1 => 1, 2 => 1, 3 => 1, 4 => 1, 5 => 1, 6 => 1, 7 => 1}
%{0 => 1, 1 => 1, 2 => 1, 3 => 1, 4 => 1, 5 => 1, 6 => 1, 7 => 2}
``````
1 Like

Yup, my mind blanked out and for some reason I thought it was updating it in real time, not creating a new map and setting the previous one equal to the new one.