Anonymous Functions

Anonymous Functions in Elixir

5 exercises
0/4 exercises completed

About Anonymous Functions

Anonymous functions are commonly used throughout Elixir on their own, as return values, and as arguments in higher order functions such as[1, 2, 3], fn n -> n + 1 end)
# => [2, 3, 4]

Functions in Elixir are treated as first class citizens:

  • Named and anonymous functions can be assigned to variables.
  • Named and anonymous functions can be passed around like data as arguments and return values.
  • Anonymous functions can be created dynamically.

Anonymous functions are created with the fn keyword and invoked with a dot (.):

function_variable = fn n -> n + 1 end

# => 2

Anonymous functions may be created with the & capture shorthand.

  • The initial & declares the start of the capture expression.

  • &1, &2, and so on refer to the positional arguments of the anonymous function.

    # Instead of:
    fn x, y -> abs(x) + abs(y) end
    # We can write:
    & abs(&1) + abs(&2)
  • The & capture operator can also be used to capture existing named function:

    # Instead of:
    fn a, b -> a <= b end
    # We can capture the function using its name and arity:

Anonymous functions in Elixir are closures. They can access variables that are in scope when the function is defined. Variables assigned inside of an anonymous function are not accessible outside of it:

y = 2

square = fn ->
  x = 3
  x * y

# => 6

# => ** (CompileError): undefined function x/0
Edit via GitHub The link opens in a new window or tab

Learn Anonymous Functions

Practicing is locked

Unlocks 2 more exercises to practice Anonymous Functions