Let clauses choose the function path: full examples and further reading
The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.
Write named functions with patterns and guards in a module.
Compile two price/1 clauses and run one child and one adult input.
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}.
Steps for the full example
- 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.
Original lesson notes
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.
Symbols and terms
price(Age) when Age < 12- Choose this clause for a child age.
;- Separate clauses of the same function.
.- End the final clause of the function.
- 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.
Original full exercise
Write label/1 clauses for zero and positive integers.
label(0) -> ____;
label(Number) when Number > 0 -> ____.Return zero and positive.
Show hint
Use atoms as the two results.
Show original answer
label(0) -> zero;
label(Number) when Number > 0 -> positive.Why does the first clause end with a semicolon?
Another clause of the same function follows; the final clause ends with a dot.
Original lesson takeaways
- Name and arity identify a function.
- Patterns and guards select clauses.
- Put specific clauses before broad fallbacks.