Erlang Language Data Types Funs


Erlang is a functional programming language. One of the features in a function programming language is handling functions as data (functional objects).

  • Pass a function as an argument to another function.
  • Return function as a result of a function.
  • Hold functions in some data structure.

In Erlang those functions are called funs. Funs are anonymous functions.

1> Fun = fun(X) -> X*X end.
2> Fun(5).

Funs may also have several clauses.

3> AddOrMult = fun(add,X) -> X+X;
3>                (mul,X) -> X*X 
3> end.
4> AddOrMult(mul,5).
5> AddOrMult(add,5).

You may also use module functions as funs with the syntax: fun Module:Function/Arity.
For example, lets take the function max from lists module, which has arity 1.

6> Max = fun lists:max/1.
7> Max([1,3,5,9,2]).