Erlang basics · Lesson 07 (open contents)
Choose one path with case
Match one value against branches, then add conditions with guards.
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.76produces the atompass.95producesvery_good.40producestry_again.
Read from the first line down
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.
Symbols are not secret signs
;This case branch is finished, and another branch follows.
end.End the whole case expression.
_OtherMatch any value. The leading underscore says this variable will not be used again.
Match each name to its meaning
case branch
One rule for one shape of input. The first matching branch is chosen.
guard
An extra condition after when, such as when Score >= 60.
fallback
A final branch that handles the remaining inputs so an unexpected value is not left out.
Why these forms are useful
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.
Close the answer and try
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.Target result: rain produces umbrella, and sunny produces hat.
Stuck? Read one hint
Use fixed atoms in the first two blanks. Use _Other to catch every other value.
After you run it, see one 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.Think about it: Should the final `case` branch end with a semicolon?
No. A semicolon means that another branch follows. The final branch goes straight to end..
Remember these three lines
- 1
casechooses the first matching branch from top to bottom. - 2
The order of patterns can change the result.
- 3
Semicolons separate branches.
end.closes the wholecase.