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
- A fun can have pattern-matched clauses like any function.
- Funs close over surrounding bindings like
Rate. fun erlang:abs/1passes a named function by arity.
Keywords and builtins used here
absendformatfunmainmap
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.
Step 2 of 4 in The lists module, step 12 of 31 in Language basics.