8.18 Fun Expressions

  1. fun
  2. [Name](Pattern11,...,Pattern1N) [when GuardSeq1] ->
  3. Body1;
  4. ...;
  5. [Name](PatternK1,...,PatternKN) [when GuardSeqK] ->
  6. BodyK
  7. 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. 1> Fun1 = fun (X) -> X+1 end.
  2. #Fun<erl_eval.6.39074546>
  3. 2> Fun1(2).
  4. 3
  5. 3> Fun2 = fun (X) when X>=5 -> gt; (X) -> lt end.
  6. #Fun<erl_eval.6.39074546>
  7. 4> Fun2(7).
  8. gt
  9. 5> Fun3 = fun Fact(1) -> 1; Fact(X) when X > 1 -> X * Fact(X - 1) end.
  10. #Fun<erl_eval.6.39074546>
  11. 6> Fun3(4).
  12. 24

The following fun expressions are also allowed:

  1. fun Name/Arity
  2. 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:

  1. 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.