我有这个小方法:
def get_dst_map(src_matches) do
# Returns a map of each dst_ip in src_matches with the number of failed attempts per dst_ip
dst_map = %{}
Enum.each src_matches, fn x ->
if !Map.has_key?(dst_map, x["dst_ip"]) do
dst_map = Map.put(dst_map, x["dst_ip"], Enum.count(src_matches, &(&1["dst_ip"] == x["dst_ip"])))
# This one prints result
IO.inspect dst_map
end
end
# This one prints empty
IO.inspect dst_map
dst_map
end
我正在枚举一些记录并将已过滤的结果添加到地图中。如果我在枚举器中检查我的变量,我可以看到结果,但是当我返回时,地图是空的。我猜这是匿名函数的某种范围问题,但我不确定如何使用我需要的结果填充dst_map
。
答案 0 :(得分:0)
我从your Gist获取了代码,并将其缩短了一点:
def get_dst_map(src_matches) do
# Returns a map of each dst_ip in src_matches with the number of failed attempts per dst_ip
Enum.reduce src_matches, %{}, fn src, dst_map ->
Map.put_new(dst_map, src["dst_ip"], Enum.count(src_matches, &(&1["dst_ip"] == src["dst_ip"])))
end
end
如果它已经存在,您似乎试图将密钥放入dst_map
。您可以使用Map.put_new/3
。