Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I nest anonymous functions in Elixir?

Tags:

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)))
like image 978
Bala Avatar asked Jul 06 '16 06:07

Bala


People also ask

How do you call anonymous using Elixir?

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.

How do you call a function in Elixir?

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.


1 Answers

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.
like image 182
sobolevn Avatar answered Oct 14 '22 19:10

sobolevn