typestar

Funs in Erlang

fun ... end makes a function value; clauses branch inside.

%% fun ... end makes a function value; clauses branch inside it.
main(_) ->
    Surcharge = fun(night) -> 0;
                   (day) -> 5
                end,
    io:format("Night extra: ~p~n", [Surcharge(night)]),
    io:format("Day extra: ~p~n", [Surcharge(day)]),

    %% Funs close over their surroundings.
    Rate = 4,
    Bill = fun(Minutes) -> Minutes * Rate end,
    io:format("12 minutes: ~p pence~n", [Bill(12)]),

    %% Named library funs pass with fun Name/Arity.
    io:format("~p~n", [lists:map(fun erlang:abs/1, [-3, 4, -7])]).

How it works

  1. A fun can have pattern-matched clauses like any function.
  2. Funs close over surrounding bindings like Rate.
  3. fun erlang:abs/1 passes a named function by arity.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
474
Tokens
133
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 133 seconds.

Type this snippet

Step 2 of 4 in The lists module, step 12 of 31 in Language basics.

← Previous Next →