Anonymous functions

Functions are delimited by the keywords fn and end:

iex> add = fn a, b -> a + b end
#Function<12.71889879/2 in :erl_eval.expr/5>
iex> is_function(add)
true
iex> is_function(add, 2)
true
iex> is_function(add, 1)
false
iex> add.(1, 2)
3

Functions are “first class citizens” in Elixir meaning they can be passed as arguments to other functions just as integers and strings can. In the example, we have passed the function in the variable add to the is_function/1 function which correctly returned true. We can also check the arity of the function by calling is_function/2.

Note a dot (.) between the variable and parenthesis is required to invoke an anonymous function.

Anonymous functions are closures, and as such they can access variables that are in scope when the function is defined:

iex> add_two = fn a -> add.(a, 2) end
#Function<6.71889879/1 in :erl_eval.expr/5>
iex> add_two.(2)
4

A variable assigned inside a function does not affect its surrounding environment:

iex> x = 42
42
iex> (fn -> x = 0 end).()
0
iex> x
42