typestar

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

  1. when Minutes =< 3 picks the flat-rate clause.
  2. Guard order matters: each clause assumes the earlier ones failed.
  3. is_integer/1 guards the catch-all against bad input.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Pattern matching, step 5 of 31 in Language basics.

← Previous Next →