Function to convert map to a list in erlang

347 views Asked by At

Suppose I have a map like this

A = #{a=>1,b=>2,c=>3}.

I want to create a function which converts A to a list of tuples of key-value pairs.

list = [{a,1},{b,2},{c,3}]
2

There are 2 answers

2
sabiwara On

maps:to_list/1 does exactly this:

1> maps:to_list(#{a=>1,b=>2,c=>3}).
[{a,1},{b,2},{c,3}]
0
vkatsuba On

You can use maps:fold/3 for loop map items. Let's say you need just convert a map, then you can use something like:

1> A = #{a=>1,b=>2,c=>3}.
2> maps:fold(
  fun(K, V, Acc) ->
      [{K, V} | Acc]
  end,
[], A).
[{c,3},{b,2},{a,1}]

For case if need to do the same for nested maps, this example can be modify like:

1> A = #{a => 1, b => 2, c => 3, d => #{a => 1, b => #{a => 1}}},
2> Nested = 
      fun F(K, V = #{}, Acc) -> [{K, maps:fold(F, [], V)} | Acc];
          F(K, V, Acc)       -> [{K, V} | Acc]
      end,
3> maps:fold(Nested, [], A).
[{d,[{b,[{a,1}]},{a,1}]},{c,3},{b,2},{a,1}]