Funs: anonymous functions

A named function belongs to a module, and the functions lesson shows how it is declared and exported. A fun is the same code without a name: a value that can be bound, passed to another function and returned from one. Anonymous functions are how Erlang hands behaviour to lists:map/2, to a process and to a test.

fun ... end

fun opens the literal and end closes it; the arguments sit in parentheses and the body follows the arrow. The module below returns a fun from a named function, passes one to another function and captures a local function by name:

funs.erl

-module(funs). -export([main/0, double/0, adder/1, twice/2, inc/1]). double() -> fun(X) -> X * 2 end. adder(N) -> fun(X) -> X + N end. twice(F, X) -> F(F(X)). inc(X) -> X + 1. main() -> Double = double(), io:format("~p~n", [Double(21)]), AddTen = adder(10), io:format("~p~n", [AddTen(5)]), io:format("~p~n", [twice(fun inc/1, 40)]).

erlc funs.erl

erl -noshell -eval 'funs:main(), halt().'

42 15 42

fun inc/1 is a capture, not a call: it builds a fun that calls the local inc/1 when it is applied. A fun literal and a capture are the same kind of value, so twice/2 does not know which one it received. The arity is part of the value: a fun that takes two arguments cannot be called with one.

Several clauses

A fun may have several clauses, separated by semicolons, each with its own pattern and guard. The runtime picks the first clause that matches, exactly as it does for a named function. This fun labels a number and is then mapped over a list:

many_clauses.erl

-module(many_clauses). -export([main/0]). main() -> Describe = fun(0) -> zero; (N) when N > 0 -> positive; (_N) -> negative end, io:format("~p~n", [lists:map(Describe, [-2, 0, 5])]).

erlc many_clauses.erl

erl -noshell -eval 'many_clauses:main(), halt().'

[negative,zero,positive]

The order matters: a clause with _N first would swallow every argument and the other clauses would never run. A fun with no matching clause raises function_clause, the same error a named function raises.

The named fun of OTP 27

Until OTP 27 a recursive anonymous function had to receive itself as an argument, because a literal had no name to call. OTP 27 adds the named fun: the name after fun is visible inside every clause of the literal, so it can call itself. This factorial needs no helper and no extra argument:

named_fun.erl

-module(named_fun). -export([main/0]). main() -> Fact = fun Fact(0) -> 1; Fact(N) -> N * Fact(N - 1) end, io:format("~p~n", [Fact(5)]).

erlc named_fun.erl

erl -noshell -eval 'named_fun:main(), halt().'

120

The name is local to the fun and is not exported or visible outside it. A module built for an older OTP rejects the form with a syntax error, which is why a library that supports both versions writes the helper function instead. The recursion lesson shows the helper form with a named function.

Apply and capture

A bound fun is called with parentheses, like a named function. erlang:apply/2 does the same when the arguments already sit in a list, which happens when a program builds the call at run time. A capture with the module name works for any exported function, including one of the standard library:

erl

1> F = funs:double(), F(21). 42 2> is_function(F). true 3> Member = fun lists:member/2. fun lists:member/2 4> Member(2, [1, 2, 3]). true 5> erlang:apply(F, [21]). 42

is_function/1 only says that the value is a fun; is_function(F, 1) also demands arity one. The higher-order lesson builds on these values with lists:map/2 and lists:foldl/3.

Closures keep a value

A fun captures the bindings it can see when it is created, and keeps them after the function that made it returns. That is a closure. It is also the place where a reader from a mutable language makes a wrong guess: the fun does not see a later change to the captured variable, because no such change exists. This counter is the mistake:

counter.erl

-module(counter). -export([main/0]). make_counter() -> N = 0, fun() -> N + 1 end. main() -> Counter = make_counter(), io:format("~p~n", [Counter()]), io:format("~p~n", [Counter()]).

erlc counter.erl

erl -noshell -eval 'counter:main(), halt().'

1 1

Both calls print 1, and a reader who expected 1 then 2 has met the rule of single assignment: N is bound once, and the fun adds one to that same value every time. A counter that really counts carries the number as an argument (next(N)) or lives in a process whose state changes between messages; the processes lesson shows the second form, and the GenServer lesson turns it into a server.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the fun keyword build?

    Answer

    An anonymous function

    fun ... end is a function literal: a value with arguments and a body, and no name of its own.

  2. How do you call the fun bound to F with the argument 21?

    Answer

    F(21)

    A bound fun is applied with parentheses, exactly like a named function.

  3. What does is_function(F, 2) check?

    Answer

    That F is a fun of arity 2

    The second argument is the arity: the number of arguments the fun takes.

  4. What does fun lists:member/2 do?

    Answer

    Builds a fun that calls lists:member/2

    The module, function and arity capture a named function as a fun; nothing runs until the fun is called.

  5. What does this module print? -module(q1). -export([main/0]). main() -> Double = fun(X) -> X * 2 end, AddTen = fun(X) -> X + 10 end, io:format("~p~n", [AddTen(Double(5))]).

    Answer

    20

    Double(5) is 10, and AddTen(10) is 20.

  6. What does this module print? -module(q2). -export([main/0]). main() -> Describe = fun(0) -> zero; (N) when N > 0 -> positive; (_N) -> negative end, io:format("~p~n", [lists:map(Describe, [-1, 0, 2])]).

    Answer

    [negative,zero,positive]

    The clauses are tried in order: -1 falls to the last one, 0 to the first, and 2 to the guard clause.

  7. What does this module print? -module(q3). -export([main/0]). main() -> Fact = fun Fact(0) -> 1; Fact(N) -> N * Fact(N - 1) end, io:format("~p~n", [Fact(4)]).

    Answer

    24

    OTP 27 lets the literal name itself, so the recursive clauses compute 4 * 3 * 2 * 1.

  8. What does this module print? -module(q4). -export([main/0]). make_counter() -> N = 0, fun() -> N + 1 end. main() -> Counter = make_counter(), io:format("~p~n", [{Counter(), Counter()}]).

    Answer

    {1,1}

    Both calls read the same captured N, so each returns 1; the fun does not keep a changing state.

  9. What is erlang:apply(F, [2, 3]) equivalent to?

    Answer

    F(2, 3)

    apply takes the fun and the argument list, and calls the fun with those arguments.

  10. Why does the counter fun print 1 on every call?

    Answer

    The captured value is bound once and never changes

    Erlang has single assignment, so the captured N stays zero and each call computes 0 + 1.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev