枚举地图时如何编写传递给Enum.map的函数?

时间:2019-02-22 12:15:49

标签: elixir

iex(121)> val_map = %{"pri" => %{"tit" => "name1"}}
iex(122)> fp = fn (new_map) -> Map.get(new_map, "pri") end

以下引发错误

iex(123)> Enum.each(val_map, fp)
** (BadMapError) expected a map, got: {"pri", %{"tit" => "name1"}}
    (elixir) lib/map.ex:437: Map.get({"pri", %{"tit" => "name1"}}, "pri", nil)
    (elixir) lib/enum.ex:771: anonymous fn/3 in Enum.each/2
    (stdlib) maps.erl:257: :maps.fold_1/3
    (elixir) lib/enum.ex:1941: Enum.each/2

2 个答案:

答案 0 :(得分:1)

很难从代码中看出目标是什么,也许您只是在试验Enum,但也许Map.values/1在这里是更好的选择?

iex(1)> val_map = %{"pri" => %{"tit" => "name1"}, "sec" => %{"tat" => "name2"}}
%{"pri" => %{"tit" => "name1"}, "sec" => %{"tat" => "name2"}}
iex(2)> Map.values(val_map)
[%{"tit" => "name1"}, %{"tat" => "name2"}]

响应评论中的澄清,您可以这样做:

iex(1)> val_map = %{"pri" => %{"tit" => "name1"}, "sec" => %{"tit" => "name2"}}
%{"pri" => %{"tit" => "name1"}, "sec" => %{"tit" => "name2"}}
iex(2)> Enum.map(val_map, fn {k, %{"tit" => v}} -> %{k => v} end)
[%{"pri" => "name1"}, %{"sec" => "name2"}]

答案 1 :(得分:0)

当您遍历地图时,它将变成一个关键字列表(即您使用一个元组):

Enum.each  %{a: 1, b: 2, c: 3},  fn {key, value} ->
  IO.puts "#{key} : #{value}"
end 

在您的情况下,您需要在元组的key部分进行匹配:

val_map = %{"pri" => %{"tit" => "name1"}}
fp = fn ({"pri", value}) -> value; {other_key, value} -> value end

在第二部分中,您可以使用该值做其他事情:变换,不返回等。

在这种情况下,它将从您的初始地图返回一个地图(值)数组:

Enum.each(val_map, fp)
# [%{"tit" => "name1"}]