Erlang basics · Lesson 13 (open contents)
Let clauses choose the function path
Write named functions with patterns and guards in a module.
Run this first
Run it once, change one input, and compare the new result.
%% Save in fare.erl and compile it
-module(fare).
-export([price/1]).
price(Age) when Age < 12 -> 5;
price(_Age) -> 10.- After compiling,
{fare:price(10), fare:price(20)}.returns{5,10}.
Read from the first line down
- Read
price(Age) when Age < 12: Choose this clause for a child age. - Read
;: Separate clauses of the same function. - Read
.: End the final clause of the function.
Symbols are not secret signs
price(Age) when Age < 12Choose this clause for a child age.
;Separate clauses of the same function.
.End the final clause of the function.
Match each name to its meaning
function clause
Clauses with the same name and arity can accept different patterns or guards.
guard
A guard refines a clause with permitted checks after when.
clause order
Erlang tries matching clauses from top to bottom.
Why these forms are useful
Run the example first. Predict one result, then change one input and run it again.
Clauses with the same name and arity can accept different patterns or guards.
A guard refines a clause with permitted checks after when.
Close the answer and try
Write label/1 clauses for zero and positive integers.
label(0) -> ____;
label(Number) when Number > 0 -> ____.Target result: Return zero and positive.
Stuck? Read one hint
Use atoms as the two results.
After you run it, see one answer
label(0) -> zero;
label(Number) when Number > 0 -> positive.Think about it: Why does the first clause end with a semicolon?
Another clause of the same function follows; the final clause ends with a dot.
Remember these three lines
- 1
Name and arity identify a function.
- 2
Patterns and guards select clauses.
- 3
Put specific clauses before broad fallbacks.