In Elixir you have anonymous functions and named functions, we’ll be covering the former in this post.
What does an anonymous function look like?
fn a, b -> a + b end #or fn (a, b) -> a + b end
Putting it to use would look like the following:
iex> sum = fn a, b -> a + b end iex> sum.(5, 2) 7 iex> sum.(10, 12) 22
You’ll notice the function is invoked with
.() and not
(). This helps to distinguish between anonymous and named functions.
You can have nested anonymous functions:
greet = fn -> fn name -> name end end
iex> person = greet.() iex> person.("Dave") "dave"
As you can tell, the syntax can become difficult to read. Let’s make it a bit easier:
greet = fn -> fn name -> IO.puts name end end
iex> person = greet.() iex> person.("Dave") dave :ok
Elixir does provide us with a neat little shortcut for creating anonymous functions, the
iex> sum = &(&1 + &2) iex> sum.(4, 4) 8
&1, &1 etc. would be the parameters to use. We can also perform function capturing with the
& operator. All we need is the function name and it’s parity.
iex> print_message = &IO.puts/1 &IO.puts/1 iex> print_message.("Hello there!) hello there :ok
See you soon.