【发布时间】:2016-10-10 13:29:38
【问题描述】:
我有这个小方法:
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。
【问题讨论】:
-
Elixir 中的变量是不可变的;你只是在第 6 行创建一个临时的新地图。你需要使用类似
Enum.reduce的东西。有关类似问题的答案,请参阅 stackoverflow.com/questions/39698504/…。 -
太棒了...得到了它的工作:gist.github.com/ciokan/2c5bc02aced813a2b8bfe5d39a1b1ce6 按照您的说明有效代码对吗?
标签: elixir