Bala
Bala

Reputation: 11244

Can I nest anonymous functions in Elixir?

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

Answers (1)

sobolevn
sobolevn

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:

  1. 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.
  2. We sum the result list.

Upvotes: 12

Related Questions