Anonymous functions originate form the work of Alonzo Church in his invention of the lambda_calculus, in which all functions are anonymous. Anonymous functions are not bound to any identifier.
Erlang is a functional programming language. This means functions can be passed as arguments to functions and functions can return functions.
Functions that manipulate functions are called higher order functions and data type that represents a function in Erlang is called a fun.
fun are anonymous functions in erlang such as lambdas in python.
Example
Erlang
Square=fun(X)->X*X end.
Square(5).
25
Python:
>>> Square=lambda X:X*X
>>> Square(5)
25
Note in python definition of the lambdas, the arguments don’t have parentheses around them.
Funs can have several different clauses. Kilometer to mile and mile to kilometer function
DistanceConvert = fun({kilometer,Km})->{miles,Km * 0.62137};
({miles, M})->{kilometer,M/0.62137}
end.
#Fun<erl_eval.7.126501267>
DistanceConvert({miles,5}).
{kilometer,8.046735439432222}
DistanceConvert({kilometer,8.04673}).
{miles,4.999996620}
Functions That Have Funs As Their Arguments
L=[1,2,3,4,5].
[1,2,3,4,5]
lists:map(fun(X)->X*X end,L). % Here map gets fun functions as argument
[1,4,9,16,25]
Even = fun(X) -> (X rem 2) =:= 0 end.
#Fun<erl_eval.7.126501267>
lists:filter(Even,L).
[2,4]