Higher-Order Functions
In Elixir, functions are treated as first-class citizens. This means you can use functions as arguments to other functions, and even return them as results. A function that can take another function as an argument or return it as a result is called a higher-order function.
When passing a function to a higher-order function, we often use anonymous functions. Let’s dive in and understand what these are.
Anonymous Functions
An anonymous function, as the name suggests, is a function without a name. These are throwaway functions that you define right where you need them.
Anonymous functions are defined using the fn keyword, like so:
iex> hello = fn -> "Hello, world!" end (1)
#Function<43.113135111/0 in :erl_eval.expr/6>
iex> hello.() (2)
"Hello, world!"
| 1 | We’re defining an anonymous function that returns "Hello, world!" and
assigning it to the variable hello. The cryptic #Function<…> line is
how IEx shows a function value. The numbers are internal identifiers,
your output will differ, that is fine. |
| 2 | The . (dot) between the variable and the parentheses is how you
call an anonymous function. You always need that dot, while named
functions such as IO.puts are called without it. |
Anonymous functions can also take parameters:
iex> add = fn (a, b) -> a + b end (1)
#Function<41.113135111/2 in :erl_eval.expr/6>
iex> add.(1, 2) (2)
3
| 1 | We define an anonymous function that takes two parameters and returns their sum. |
| 2 | Call it with two numbers to get the sum back. |
Elixir also offers a shorthand for short anonymous functions called the
capture operator (&). We cover it
later in the book, so don’t worry about it for now.
|