Choose with patterns, guards, and errors: full examples and further reading
The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.
Use `case`, `if`, and `try` for three different decisions.
Classify a score, inspect one parse result, and convert one expected error.
Run this first
Run it once, change one input, and compare the new result.
Original full example
%% Use each form for the decision it fits
Score = 76,
Label = if Score >= 90 -> great; Score >= 60 -> pass; true -> retry end,
Parsed = case string:to_integer("42") of {N, []} -> {ok, N}; _ -> {error, bad_text} end,
Safe = try binary_to_integer(<<"x">>) catch error:badarg -> {error, badarg} end,
{Label, Parsed, Safe}.The result is {pass,{ok,42},{error,badarg}}.
Steps for the full example
- Read
case Value of: Match one value against branches. - Read
if Guard ->: Choose by guard conditions. - Read
catch error:Reason ->: Handle a named error reason.
Original lesson notes
Run the example first. Predict one result, then change one input and run it again.
case matches one value against ordered patterns.
Erlang if chooses the first guard expression that is true.
Symbols and terms
case Value of- Match one value against branches.
if Guard ->- Choose by guard conditions.
catch error:Reason ->- Handle a named error reason.
- case
casematches one value against ordered patterns.- if expression
- Erlang
ifchooses the first guard expression that is true. - try expression
tryseparates normal results from expected error classes and reasons.
Original full exercise
Use case to turn {error, timeout} into retry.
Exercise starter
case {error, timeout} of
{ok, Value} -> Value;
{error, ____} -> ____
end.Return retry.
Show hint
Match timeout and return the atom retry.
Show original answer
Reference answer
case {error, timeout} of
{ok, Value} -> Value;
{error, timeout} -> retry
end.Is Erlang if a general else-if statement?
It is a sequence of guard clauses; use case when patterns describe the data more clearly.
Original lesson takeaways
- Use case for shapes.
- Use if for guard-only choices.
- Catch only errors the boundary expects.