functional-programmingelixir

How to change all the values in an Elixir map


I see that there's an update in the Dict module, but what about an update_all method that changes all values?

I tried doing this with Enum.map but the type changed:

iex(6)> Enum.map(%{:a => 2}, fn {k, v} -> {k, v + 1} end)
[a: 3]

Solution

  • You could pipe to Enum.into(%{}) or use a for comprehension, i.e.:

    iex> for {k, v} <- %{a: 1, b: 2}, into: %{}, do: {k, v + 1}
    %{a: 2, b: 3}