Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top