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)))
Syntax. The building blocks of an anonymous function are fn , -> , and end . When calling the anonymous function, we write the assigned name, followed by . , and then any of the function's parameters.
In order to call a function in Elixir we want to use the module name, in this case 'Calculator', and then the function we want to invoke, we'll use squared here. And pass in any arguments the function expects. Great all the functions from our Calculator module returned the values we expected.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With