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}]
r6vfmomb1#
maps:to_list/1的作用就是:
maps:to_list/1
1> maps:to_list(#{a=>1,b=>2,c=>3}). [{a,1},{b,2},{c,3}]
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}]
2条答案
按热度按时间r6vfmomb1#
maps:to_list/1
的作用就是:pxy2qtax2#
你可以用maps:fold/3来表示循环贴图项。假设你只需要转换一个贴图,那么你可以使用如下的方法:
如果需要对嵌套Map执行相同的操作,则可以修改此示例,如下所示: