Reputation: 163
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
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
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