Reputation: 11244
I am passing a function to Enum.reduce
as follows to get 24
Enum.reduce([1,2,3,4], &(&1 * &2)) #=> 24
If I have a nested list in which I would like to multiply each nested element and sum them together. For example in [[1,2],[3,4]]
I would like to perform [[1*2] + [3*4]]
to get 14
, is there a way to do it (using anonymous functions)
This is what I tried (knowing its incorrect) and I got nested captures via & are not allowed
. I am trying to understand the required mental model when using Elixir
Enum.reduce([[1,2],[3,4]], &(&(&1 * &2) + &(&1 * &2)))
Upvotes: 6
Views: 3258
Reputation: 18070
You are totally right, if you will try to nest anonymous functions with captures you will get (CompileError): nested captures via & are not allowed
.
Also, captures are made for simplicity. Do not over-complicate it.
That's how you can do it:
[[1,2],[3,4]]
|> Enum.map(&Enum.reduce(&1, fn(x, acc) -> x * acc end))
|> Enum.sum
What we do here is basically two things:
Enum.map(&Enum.reduce(&1, fn(x, acc) -> x * acc end))
For each sublist ([1, 2]
, [3, 4]
) we run a captured function &Enum.reduce
, where &1
is the sublist. Then we count the multiplication: fn(x, acc) -> x * acc end
.sum
the result list.Upvotes: 12