Choose one path with case: full examples and further reading
The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.
Match one value against branches, then add conditions with guards.
Run the same Erlang case with scores 76, 95, and 40, then check the selected message.
Use case to see the order of branches
Change Score to 95 and 40, and run the code each time.
%% Clear old variables so Score is easy to change and try again
f().
%% Try each branch from top to bottom
Score = 76.
Message =
case Score of
Value when Value >= 90 -> very_good;
Value when Value >= 60 -> pass;
_Other -> try_again
end.
%% Look at the chosen atom
Message.76 produces the atom pass.
95 produces very_good.
40 produces try_again.
Steps for the full example
case Score ofsays that the following branches will matchScore.- The first two branches end with semicolons because more branches follow. The final branch has no semicolon.
- The dot in
end.ends the wholecaseexpression.
Original lesson notes
case gets one value, then searches from top to bottom for the first matching branch.
Semicolons ; separate branches. Do not put a semicolon after the final branch. End the whole case with end..
A guard after when adds one simple condition to a pattern.
Symbols and terms
;- This
casebranch is finished, and another branch follows. end.- End the whole
caseexpression. _Other- Match any value. The leading underscore says this variable will not be used again.
- case branch
- One rule for one shape of input. The first matching branch is chosen.
- guard
- An extra condition after
when, such aswhen Score >= 60. - fallback
- A final branch that handles the remaining inputs so an unexpected value is not left out.
Original full exercise
Choose an action for a weather atom: rain returns umbrella, sunny returns hat, and anything else returns look_up.
%% Clear Score, Message, and any old Weather value
f().
%% Try other atoms too
Weather = rain.
case Weather of
____ -> umbrella;
____ -> hat;
____ -> look_up
end.rain produces umbrella, and sunny produces hat.
Show hint
Use fixed atoms in the first two blanks. Use _Other to catch every other value.
Show original answer
%% f() is used only in the shell
f().
%% Weather is the atom to match
Weather = rain.
case Weather of
rain -> umbrella;
sunny -> hat;
_Other -> look_up
end.Should the final case branch end with a semicolon?
No. A semicolon means that another branch follows. The final branch goes straight to end..
Original lesson takeaways
casechooses the first matching branch from top to bottom.- The order of patterns can change the result.
- Semicolons separate branches.
end.closes the wholecase.