← Back to lesson 13: Let clauses choose the function path

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.

Original full example
%% 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

  1. Read price(Age) when Age < 12: Choose this clause for a child age.
  2. Read ;: Separate clauses of the same function.
  3. 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.

Exercise starter
label(0) -> ____;
label(Number) when Number > 0 -> ____.

Return zero and positive.

Show hint

Use atoms as the two results.

Show original answer
Reference 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
Design trade-offs and language comparisons
Original course references