用于将Map转换为Erlang中的列表的函数

uubf1zoe  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(173)

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}]
r6vfmomb

r6vfmomb1#

maps:to_list/1的作用就是:

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

pxy2qtax2#

你可以用maps:fold/3来表示循环贴图项。假设你只需要转换一个贴图,那么你可以使用如下的方法:

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}]

如果需要对嵌套Map执行相同的操作,则可以修改此示例,如下所示:

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}]

相关问题