Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's up with this anonymous function syntax?

Tags:

elixir

Just starting on my Elixir journey. Reading this in a book:

"The & operator converts the expression that follows into a function."

ok, I think I got that...

iex(70)> f = &(&1 * &2)
#Function<12.80484245 in :erl_eval.expr/5>
iex(72)> f.(2,3)
6

ok, ampersand is a shorthand for anonymous function and it's arguments. But then, why this next call doesn't work?!

iex(73)> &(&1 * &2).() 
#Function<12.80484245 in :erl_eval.expr/5>

...and I can keep doing this seemingly forever:

iex(76)> &(&1 * &2).().().()
#Function<12.80484245 in :erl_eval.expr/5>

what is going on here?

like image 447
alexakarpov Avatar asked Apr 29 '14 07:04

alexakarpov


1 Answers

If you wrap the anonymous function with parentheses, it will work:

iex(1)> (&(&1 * &2)).()
** (BadArityError) &:erlang.*/2 with arity 2 called with no arguments

The Error is expected, as we're calling a 2 arity fun with zero arguments. If we pass it two numbers, we should get see them get multiplied together:

iex(2)> (&(&1 * &2)).(2,3)
6
like image 105
sasajuric Avatar answered Oct 04 '22 09:10

sasajuric