【问题标题】:Elixir update external var from inside anonymous functionElixir 从匿名函数内部更新外部变量
【发布时间】: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


【解决方案1】:

我从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

【讨论】:

    猜你喜欢
    • 2013-08-16
    • 2012-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 2023-03-28
    • 2018-03-07
    • 2016-08-31
    • 2019-02-04
    相关资源
    最近更新 更多