Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 ยท Functions and Pattern Matching

Funs and Higher-Order Functions

Use anonymous functions (funs) in Erlang, capture variables in closures, pass funs to lists:map, filter and foldl, return funs and write named funs.

A fun is an anonymous function: a function value you can store in a variable, pass to another function, send in a message or return from a function. Functions that take or return funs are called higher-order functions. They let you separate "how to traverse" from "what to do", so you rarely write recursion by hand for common list jobs.

Creating a fun

ERLANG
1> Double = fun(X) -> X * 2 end.
#Fun<erl_eval.42.105768164>
2> Double(21).
42
3> Add = fun(A, B) -> A + B end.
#Fun<erl_eval.41.105768164>
4> Add(3, 4).
7

The syntax is fun(Args) -> Body end. You call a fun by writing the variable followed by parentheses. A fun may have several clauses like a normal function:

ERLANG
1> Describe = fun(0) -> zero;
1>               (N) when N < 0 -> negative;
1>               (_) -> positive
1>            end.
2> Describe(-4).
negative

Funs from existing functions

Instead of writing a wrapper, point at an existing function using fun Name/Arity for local functions and fun Module:Name/Arity for remote ones:

ERLANG
1> F = fun lists:reverse/1.
fun lists:reverse/1
2> F([1, 2, 3]).
[3,2,1]
3> G = fun erlang:length/1.
4> G("abc").
3

This is the preferred form when a function with the right name already exists.

Closures

A fun remembers the variables that were bound where it was created:

ERLANG
1> Factor = 3.
3
2> Times = fun(X) -> X * Factor end.
3> Times(5).
15
4> lists:map(Times, [1, 2, 3]).
[3,6,9]

Factor is captured when the fun is created. Because variables never change, the captured value is always safe. A function that returns a fun makes a customised function:

ERLANG
make_adder(N) ->
    fun(X) -> X + N end.
ERLANG
1> Add5 = make_adder(5).
2> Add5(10).
15

When a fun's own parameter has the same name as an outer variable, the parameter shadows it and the compiler warns. Use distinct names.

Higher-order functions in lists

The lists module is full of them. The three you will use constantly:

ERLANG
1> lists:map(fun(X) -> X * X end, [1, 2, 3, 4]).
[1,4,9,16]
2> lists:filter(fun(X) -> X rem 2 =:= 0 end, [1, 2, 3, 4, 5, 6]).
[2,4,6]
3> lists:foldl(fun(X, Acc) -> X + Acc end, 0, [1, 2, 3, 4]).
10
  • lists:map(Fun, List) applies Fun to every element and returns the new list.
  • lists:filter(Pred, List) keeps the elements for which Pred returns true.
  • lists:foldl(Fun, Acc0, List) threads an accumulator through the list from left to right. The fun receives (Element, Acc), in that order. lists:foldr/3 goes from the right.

More: lists:foreach/2 (run a fun for its side effects), lists:any/2, lists:all/2, lists:partition/2, lists:sort/2 (with a comparison fun), lists:flatmap/2, lists:takewhile/2, lists:dropwhile/2, lists:zipwith/3.

ERLANG
1> lists:sort(fun(A, B) -> A > B end, [3, 1, 4, 1, 5]).
[5,4,3,1,1]
2> lists:foreach(fun(X) -> io:format("item ~p~n", [X]) end, [a, b]).
item a
item b
ok
3> lists:partition(fun(X) -> X > 2 end, [1, 2, 3, 4]).
{[3,4],[1,2]}

foldl is the most general: map, filter and sum can all be built from it. For example, finding the maximum:

ERLANG
Max = lists:foldl(fun(X, M) -> max(X, M) end, hd(L), tl(L)).

Composition

Because funs are values, you can combine them:

ERLANG
compose(F, G) -> fun(X) -> F(G(X)) end.

Inc = fun(X) -> X + 1 end,
Twice = fun(X) -> X * 2 end,
IncThenDouble = compose(Twice, Inc),
IncThenDouble(5).     % 12

Named funs

A fun can call itself if you give it a name (OTP 17 and later). Capitalise the name:

ERLANG
1> Fact = fun F(0) -> 1;
1>            F(N) -> N * F(N - 1)
1>        end.
2> Fact(5).
120

The name F is visible only inside the fun.

Funs and processes

Funs are the usual way to start a process: spawn(fun() -> ... end). The fun is sent to the new process with its captured variables, a point we will use heavily in processes. One caution: a fun sent to another node must exist there with the same code version, so for distributed messages many programs send data rather than funs.

Stand-ins in JavaScript

JavaScript has the same ideas under other names. These are not Erlang, but they behave the same way.

JS Stand-in: map, filter, foldl (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: closures and compose (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you create an anonymous function that doubles a number?

    Erlang funs use fun(Args) -> Body end.
  2. 2. In lists:foldl(Fun, Acc0, List), which arguments does Fun receive?

    foldl calls Fun(Element, Acc).
  3. 3. What does fun lists:reverse/1 create?

    fun Module:Name/Arity makes a function value from an existing function.
  4. 4. What is a closure?

    A closure remembers the variable bindings of its creation site.

Summary

  • A fun is a function value: fun(X) -> ... end; call it as F(Arg).
  • fun name/arity and fun mod:name/arity reference existing functions.
  • Funs capture the variables around them (closures); functions can return funs.
  • lists:map, filter, foldl, foreach, partition and sort/2 take funs.
  • Named funs (fun F(X) -> ... F(...) end) can recurse.

Next: Lists