Anonymous functions are commonly used throughout Elixir on their own, as return values, and as arguments in higher order functions such as
Enum.map([1, 2, 3], fn n -> n + 1 end) # => [2, 3, 4]
Functions in Elixir are treated as first class citizens:
Anonymous functions are created with the
fn keyword and invoked with a dot (
function_variable = fn n -> n + 1 end function_variable.(1) # => 2
Anonymous functions may be created with the
& capture shorthand.
& declares the start of the capture expression.
&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)
& 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: &<=/2
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 end square.() # => 6 x # => ** (CompileError): undefined function x/0