3

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}]
sabiwara
  • 2,775
  • 6
  • 11

2 Answers2

5

maps:to_list/1 does exactly this:

1> maps:to_list(#{a=>1,b=>2,c=>3}).
[{a,1},{b,2},{c,3}]
sabiwara
  • 2,775
  • 6
  • 11
  • 1
    Is there a way where I can iterate through the map and then convert it to list? tolist is a BIF I guess. – MemeFast King Oct 11 '22 at 04:37
  • 1
    It depends what you are trying to do, [`maps:fold/3`](https://www.erlang.org/doc/man/maps.html#fold-3) (as pointed out by vkatsuba) is probably what you want, or maybe [`maps:iterator/1`](https://www.erlang.org/doc/man/maps.html#iterator-1) for some more advanced cases. – sabiwara Oct 11 '22 at 22:51
2

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}]
vkatsuba
  • 1,411
  • 1
  • 7
  • 19