Elixir Anonymous Functions
Functions are values in Elixir. An anonymous function is created with fn ... -> ... end, can be stored in a variable, passed to other functions and returned from functions. You call it with a dot before the parentheses.
add = fn a, b -> a + b end
IO.inspect(add.(2, 3))
greet = fn -> "Hello!" end
IO.puts(greet.())
IO.inspect(is_function(add))
IO.inspect(is_function(add, 2))
IO.inspect(Function.info(add)[:arity])5
Hello!
true
true
2
The dot in add.(2, 3) makes it clear that add is a variable holding a function, not a named function add/2 defined in a module.
Arity
The arity of a function is the number of arguments it takes. In Elixir a function is identified by its name and arity, written name/arity: String.upcase/1, Enum.map/2. Calling a function with the wrong number of arguments raises a BadArityError.
Closures
An anonymous function remembers the variables that were visible when it was created. It captures their values, so later rebinding of the outer variable does not affect it:
rate = 0.2
with_tax = fn price -> price * (1 + rate) end
rate = 0.5 # rebinding the name does not change the closure
IO.inspect(with_tax.(100))
IO.inspect(rate)
make_counter_label = fn prefix ->
fn n -> "#{prefix}-#{n}" end
end
ticket = make_counter_label.("TCK")
IO.puts(ticket.(7))120.0
0.5
TCK-7
make_counter_label returns a function: a function that builds functions. This is a common way to configure behaviour.
Multiple clauses
An anonymous function can have several clauses with patterns and guards, just like case:
handle = fn
{:ok, value} -> "success: #{value}"
{:error, reason} when is_atom(reason) -> "error: #{reason}"
other -> "unexpected: #{inspect(other)}"
end
IO.puts(handle.({:ok, 10}))
IO.puts(handle.({:error, :not_found}))
IO.puts(handle.(:surprise))success: 10
error: not_found
unexpected: :surprise
All clauses must take the same number of arguments.
The capture operator &
& is a shortcut for creating functions. It has two forms:
&Module.function/arityturns a named function into a function value.&(... &1 ... &2 ...)builds an anonymous function where&1,&2are the arguments.
upcase = &String.upcase/1
IO.puts(upcase.("shout"))
double = &(&1 * 2)
IO.inspect(double.(21))
full_name = &"#{&1} #{&2}"
IO.puts(full_name.("Grace", "Hopper"))
IO.inspect(Enum.map([1, 2, 3], &(&1 * &1)))
IO.inspect(Enum.map(["a", "b"], &String.upcase/1))SHOUT
42
Grace Hopper
[1, 4, 9]
["A", "B"]
&(&1 * 2) is exactly the same as fn x -> x * 2 end. Use the capture form for very short functions and fn when the body is longer or needs pattern matching.
Passing functions to functions
Functions that take other functions are called higher-order functions. The Enum module is full of them:
prices = [12, 45, 7, 30]
IO.inspect(Enum.filter(prices, fn p -> p >= 20 end))
IO.inspect(Enum.reduce(prices, 0, fn p, acc -> p + acc end))
IO.inspect(Enum.sort_by(["pear", "fig", "banana"], &String.length/1))
apply_twice = fn f, x -> f.(f.(x)) end
IO.inspect(apply_twice.(&(&1 + 10), 1))[45, 30]
94
["fig", "pear", "banana"]
21
Common mistakes
- Calling without the dot:
add(1, 2)looks for a named functionadd/2and fails to compile. Writeadd.(1, 2). - Expecting a closure to see later changes: it captured the value at creation time.
- Using
&1outside a&(...)capture: it is only valid inside one.
Test yourself
How do you call an anonymous function stored in square?
- square(4)
- square.(4)
- square->(4)
- call(square, 4)
Which is equivalent to fn x -> x + 1 end?
&(x + 1)&(&1 + 1)&+1&1 + 1
r = 2; f = fn x -> x * r end; r = 10; f.(3) returns…
- 6
- 30
- An error
- nil