Romeo Mihalcea
Romeo Mihalcea

Reputation: 10252

Elixir update external var from inside anonymous function

I have this little method:

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

I'm enumerating over some records and adding to a map the filtered results. If I inspect my variable inside the enumerator I can see the results but, when I return, the map is empty. I'm guessing it's some sort of scoping issues here with the anonymous function but I'm unsure how to populate that dst_map with the results I need.

Upvotes: 0

Views: 212

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107728

I took the code from your Gist and made it a little shorter:

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

It looked like you were trying to put a key into dst_map if it didn't already exist already. You can use Map.put_new/3 for that.

Upvotes: 0

Related Questions