Guards in Erlang
when refines a clause after its pattern matches.
%% Guards refine a clause: when filters after the pattern matches.
charge(Minutes) when Minutes =< 3 ->
10;
charge(Minutes) when Minutes =< 10 ->
10 + (Minutes - 3) * 4;
charge(Minutes) when is_integer(Minutes) ->
38 + (Minutes - 10) * 2.
main(_) ->
[io:format("~p min costs ~p pence~n", [M, charge(M)])
|| M <- [2, 7, 15]],
io:format("Long call: ~p~n", [charge(30)]).
How it works
when Minutes =< 3picks the flat-rate clause.- Guard order matters: each clause assumes the earlier ones failed.
is_integer/1guards the catch-all against bad input.
Keywords and builtins used here
chargeformatis_integermainwhen
The run, in numbers
- Lines
- 12
- Characters to type
- 369
- Tokens
- 114
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 105 seconds.
Step 2 of 4 in Pattern matching, step 5 of 31 in Language basics.