Reputation: 529
I have a list of tuples like this:[{key,val},{key2,val2}...]
I want to be able to convert it into a map:
#{key=>val, key2=>val2 ......}
Upvotes: 3
Views: 3585
Reputation: 48649
And if Hendri's solution is too simple for you, then you can do this:
-module(my).
-compile(export_all).
create_map(List_Of_Key_Val_Tuples) ->
create_map(List_Of_Key_Val_Tuples, #{}).
create_map([], Acc) ->
Acc;
create_map([{Key, Val} | Tail], Acc) ->
create_map(Tail, Acc#{Key => Val}).
In the shell:
11> c(my).
my.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,my}
12> my:create_map([{a, 10}, {"hello", hi}, {fun(X) -> X+2 end, add_two}]).
#{a => 10,#Fun<erl_eval.6.99386804> => add_two,"hello" => hi}
Upvotes: 2
Reputation: 371
You can use the from_list
function from the maps module:
maps:from_list(Yourlist).
Upvotes: 9