Is this explanation of &1 + &2 + &1 correct?

28 views
Skip to first unread message

Dave Thomas

unread,
May 12, 2013, 4:47:21 PM5/12/13
to elixir-l...@googlegroups.com
You have to be careful when using the `&1` notation—when Elixir sees
it, in converts the immediately enclosing expression into a
function. So, the following works:

iex> func = &1 + &2
#Function<erl_eval.12.82930912>
iex> func.(9, 4)
13

However, this doesn't.

iex> func = &1 + &2 + &1
#Function<erl_eval.12.82930912>
iex> func.(9, 4)
** (BadArityError) bad arity error: #Function<erl_eval.6.82930912> 
   called with [3,4]

That's because `&1 + &2 + &1` is parsed internally as `(&1 + &2) +
&1`. The parenthesized part is self-contained, so Elixir converts it
to 

(fn a, b -> a+b end) + &1

Now it continues to parse the line, sees the second `&1` and generates
a second anonymous function, enclosing the whole expression:

fn x -> (fn a, b -> a+b end) + x end

When we call this with two parameters, it raises a bad arity error,
because the outer function only expects one.

José Valim

unread,
May 12, 2013, 4:55:01 PM5/12/13
to elixir-l...@googlegroups.com
Yes, this is perfect.
--
You received this message because you are subscribed to the Google Groups "elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-co...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 


--


José Valim
Skype: jv.ptec
Founder and Lead Developer

Reply all
Reply to author
Forward
0 new messages