A. Gisbert
A. Gisbert

Reputation: 163

Elixir-Is it possible to capture a key-value pair?

Having this function:

Enum.map(%{1 => 2, 3 => 4}, fn {k, v} -> k * v end)

Is it possible to capture the anonymous function? I tried to do something like this:

Enum.map(%{1 => 2, 3 => 4}, &*/2)

Or like this:

Enum.map(%{1 => 2, 3 => 4}, &(&1 * &2))

Both ways fail because the captured function has arity/2 and map is only passing 1 argument, the pair.

Is it possible to do that? It is not something that I really want to do, but I am curious.

Upvotes: 2

Views: 542

Answers (2)

Dogbert
Dogbert

Reputation: 222328

Yes, you can create a capture of one argument and then call Kernel.elem/2 twice:

iex(1)> Enum.map(%{1 => 2, 3 => 4}, &(elem(&1, 0) * elem(&1, 1)))
[2, 12]

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

One might decompose the argument with Kernel.SpecialForms.with/1:

Enum.map(%{1 => 2, 3 => 4}, &(with {k, v} <- &1, do: k * v))                
#⇒ [2, 12]

Upvotes: 3

Related Questions