🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Anonymous Functions

An anonymous function is a reusable block of code without a name, stored in a variable. The word anonymous means it has no name of its own.

A stored function doubles a number

The fn block doubles its argument and is stored in double. The dot call runs it, and is_function confirms the variable holds a function.

double = fn x -> x * 2 end

IO.puts(double.(21))
IO.puts(is_function(double))

Two arguments go before the arrow

An anonymous function can take more than one argument. The arguments are listed before the arrow, separated by commas.

add = fn a, b -> a + b end

IO.puts(add.(3, 4))
IO.puts(add.(10, 5))

A named function can run a passed function twice

The apply_twice function receives a function as its first argument. It runs that function on the value, then runs it again on the result.

defmodule Runner do
  def apply_twice(fun, value), do: fun.(fun.(value))
end

triple = fn x -> x * 3 end

IO.puts(Runner.apply_twice(triple, 2))

Example

defmodule Formatter do
  def show(fun, value), do: "Result: #{fun.(value)}"
end

square = fn n -> n * n end

IO.puts(Formatter.show(square, 5))
IO.puts(is_function(square))
IO.puts(square.(9))

Key points

  • Anonymous: without a name of its own.
  • fn: starts an anonymous function, and end closes it.
  • Arrow: the -> symbol separates the arguments from the result.
  • Storage: you keep an anonymous function by binding it to a variable.
  • Dot call: you call it through the variable with a dot, as in double.(21).
  • is_function: this test returns true for a value that holds a function.

In this example, square holds an anonymous function that multiplies a number by itself. Formatter.show receives that function and calls it with 5, and the last line calls square directly with 9.

Note

in Elixir, a function is a value, so a variable can hold one and pass it on.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

double holds fn x -> x * 2 end. Which expression calls it with 10?