8.18 Fun Expressions
- fun
- [Name](Pattern11,...,Pattern1N) [when GuardSeq1] ->
- Body1;
- ...;
- [Name](PatternK1,...,PatternKN) [when GuardSeqK] ->
- BodyK
- end
A fun expression begins with the keyword fun and ends with the keyword end. Between them is to be a function declaration, similar to a regular function declaration, except that the function name is optional and is to be a variable, if any.
Variables in a fun head shadow the function name and both shadow variables in the function clause surrounding the fun expression. Variables bound in a fun body are local to the fun body.
The return value of the expression is the resulting fun.
Examples:
- 1> Fun1 = fun (X) -> X+1 end.
- #Fun<erl_eval.6.39074546>
- 2> Fun1(2).
- 3
- 3> Fun2 = fun (X) when X>=5 -> gt; (X) -> lt end.
- #Fun<erl_eval.6.39074546>
- 4> Fun2(7).
- gt
- 5> Fun3 = fun Fact(1) -> 1; Fact(X) when X > 1 -> X * Fact(X - 1) end.
- #Fun<erl_eval.6.39074546>
- 6> Fun3(4).
- 24
The following fun expressions are also allowed:
- fun Name/Arity
- fun Module:Name/Arity
In Name/Arity, Name is an atom and Arity is an integer. Name/Arity must specify an existing local function. The expression is syntactic sugar for:
- fun (Arg1,...,ArgN) -> Name(Arg1,...,ArgN) end
In Module:Name/Arity, Module, and Name are atoms and Arity is an integer. Starting from Erlang/OTP R15, Module, Name, and Arity can also be variables. A fun defined in this way refers to the function Name with arity Arity in the latest version of module Module. A fun defined in this way is not dependent on the code for the module in which it is defined.
More examples are provided in Programming Examples.