Elixir basics · Lesson 06 (open contents)
Choose with case
Match one value against branches, then add conditions with guards.
Choose a message for a score
Change score to 95 and 40, and run the code each time.
# score is the value we will check
score = 76
# case looks for the first matching branch from top to bottom
message =
case score do
value when value >= 90 -> "Great work"
value when value >= 60 -> "Passed"
_value -> "Try again"
end
# Look at the chosen result
message76produces"Passed".95produces"Great work".40produces"Try again".
Read from the first line down
case score dosays that the next branches will checkscore.- Branches are tried from top to bottom, so
>= 90must come before>= 60. _valuecatches any remaining value. Its leading underscore reminds us that we will not use it again.
Symbols are not secret signs
->When the condition on the left matches, run the expression on the right.
whenAdd one more condition after a pattern.
_A final fallback branch that catches values not handled above.
case ... do ... enddo opens the branches. end closes the whole case.
Match each name to its meaning
branch
A piece of code chosen for a particular kind of input.
case
Match one value against several patterns and run the first matching branch.
guard
An extra condition after when, such as when score >= 60.
Why these forms are useful
Programs often need to act differently in different situations. case gets one value, then tries to match it against several patterns.
Each branch says which input it accepts and what it returns. The first matching branch runs. The later branches are skipped.
A guard is a small condition after a pattern. Guards allow only a safe, clearly defined group of checks.
Close the answer and try
Choose an action for a weather atom: take an umbrella for :rain, wear a hat for :sunny, and look at the sky for anything else.
# Try other atoms too
weather = :rain
case weather do
____ -> "Take an umbrella"
____ -> "Wear a hat"
____ -> "Look at the sky"
endTarget result: :rain produces "Take an umbrella", and :sunny produces "Wear a hat".
Stuck? Read one hint
Use fixed atoms in the first two places. Use an underscore name to catch every other value.
After you run it, see one answer
# weather is the value to match
weather = :rain
case weather do
:rain -> "Take an umbrella"
:sunny -> "Wear a hat"
_other -> "Look at the sky"
endThink about it: Why must `value >= 90` come before `value >= 60`?
case picks the first matching branch. Since 95 is also above 60, the opposite order would send 95 into the “Passed” branch too soon.
Remember these three lines
- 1
caseis good at combining pattern matching with a choice. - 2
The order of branches can change the result.
- 3
A fallback branch explains what happens to other inputs.