Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir map_values in a map?

Tags:

elixir

Ain't there a standard lib function that would allow to execute a map_values function over a map:

Map.map_values(%{a: 30, b: 45}, fn v -> v*2 end) # = %{a: 60, b: 90}

The best way I found is:

Enum.map(%{a: 30, b: 45}, fn {k, v} -> {k, map_fn(v)}) |> Enum.into(%{})

which I find pretty heavy since I use this quite often...

like image 880
Augustin Riedinger Avatar asked Apr 22 '26 07:04

Augustin Riedinger


2 Answers

I don't think so, but you can do it more concisely with Map.new/2:

iex> Map.new(%{a: 30, b: 45}, fn {k, v} -> {k, v * 2} end)
%{a: 60, b: 90}
like image 163
Adam Millerchip Avatar answered Apr 25 '26 02:04

Adam Millerchip


An alternative to this is a for comprehension e.g

a = %{a: 30, b: 45}
    for {k, v} <- a, into: %{} do
      {k, v + 1}
    end

output :

%{a: 31, b: 46}

Through this way you are not creating an intermediate list, because Enum.map return a list and then you need to convert it to map. Here the important part is the into: %{} because if you omit it, it will return you a list by default.

like image 22
Tano Avatar answered Apr 25 '26 03:04

Tano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!