Lesson 8 of 16
Anonymous Functions
fn...end
Anonymous functions are created with fn and called with a dot:
double = fn x -> x * 2 end
IO.puts(double.(5)) # 10
The dot . is required when calling anonymous functions in Elixir.
Capture Syntax &
The & shorthand lets you write compact anonymous functions:
add = &(&1 + &2)
IO.puts(add.(3, 4)) # 7
&1, &2 refer to the first and second arguments.
Your Turn
- Create
double = fn x -> x * 2 endand printdouble.(5)→ 10 - Create
add = &(&1 + &2)and printadd.(3, 4)→ 7 - Create
square = &(&1 * &1)and printsquare.(6)→ 36
JS Transpiler loading...
Loading...
Click "Run" to execute your code.