← Back to lesson 07: Choose with case

Choose 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 case with scores 76, 95, and 40, then check which message each score selects.

Choose a message for a score

Change score to 95 and 40, and run the code each time.

Original full example
# 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
message

76 produces "Passed".

95 produces "Great work".

40 produces "Try again".

Steps for the full example

  1. case score do says that the next branches will check score.
  2. Branches are tried from top to bottom, so >= 90 must come before >= 60.
  3. _value catches any remaining value. Its leading underscore reminds us that we will not use it again.

Original lesson notes

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.

Symbols and terms
->
When the condition on the left matches, run the expression on the right.
when
Add one more condition after a pattern.
_
A final fallback branch that catches values not handled above.
case ... do ... end
do opens the branches. end closes the whole case.
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.

Original full exercise

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.

Exercise starter
# Try other atoms too
weather = :rain

case weather do
  ____ -> "Take an umbrella"
  ____ -> "Wear a hat"
  ____ -> "Look at the sky"
end

:rain produces "Take an umbrella", and :sunny produces "Wear a hat".

Show hint

Use fixed atoms in the first two places. Use an underscore name to catch every other value.

Show original answer
Reference 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"
end
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.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references