Elixir: Anonymous Function

Including the ‘&’ capture operator

nick3499
1 min readJun 28, 2017

In the interactive Elixir shell below, an anonymous function is demonstrated:

iex(1)> fv = fn(distance) -> :math.sqrt(2 * 9.8 * distance) end
#Function<6.50752066/1 in :erl_eval.expr/5>
iex(2)> fv.(20)
19.79898987322333

In addition to the conventional anonymous function, the & capture operator can be used—as an alternative:

iex(1)> fv = &(:math.sqrt(2 * 9.8 * &1))    
#Function<6.50752066/1 in :erl_eval.expr/5>
iex(2)> fv.(20)
19.79898987322333

Both anonymous functions return identical values.

--

--

nick3499
nick3499

Written by nick3499

coder of JavaScript and Python

No responses yet