maps:put(Key,Value,Map) not working in erlang

Viewed 408

maps:put(key,value,Map) not working

Map = #{"a" => 1},
maps:put("a", 42, Map),
maps:put("b", 1337, Map),
io:fwrite("~p~n",[Map]).

output #

{"a" => 1}

Why I am not able to get output #{"a" => 42,"b" => 1337}?

1 Answers

The maps:put/3 function returns a new map. You can see that it doesn't alter Map if you look at the variable again after the first maps:put/3 call:

1> Map = #{"a" => 1}.
#{"a" => 1}.
2> maps:put("a", 42, Map).
#{"a" => 42}
3> Map.
#{"a" => 1}

As you can see, Map retains its initial value.

To fix the problem, you need to capture the maps:put/3 return value into a new variable:

4> Map1 = maps:put("a", 42, Map).
#{"a" => 42}
5> Map2 = maps:put("b", 1337, Map1).
#{"a" => 42,"b" => 1337}

Now the variable Map2 has the value you're looking for.

Related