Erlang Language Data Types Funs


Example

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.
#Fun<erl_eval.6.52032458>
2> Fun(5).
25

Funs may also have several clauses.

3> AddOrMult = fun(add,X) -> X+X;
3>                (mul,X) -> X*X 
3> end.
#Fun<erl_eval.12.52032458>
4> AddOrMult(mul,5).
25
5> AddOrMult(add,5).
10

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.
#Fun<lists.max.1>
7> Max([1,3,5,9,2]). 
9