Erlang basics · Lesson 15 (open contents)
Choose with patterns, guards, and errors
Use `case`, `if`, and `try` for three different decisions.
Run this first
Run it once, change one input, and compare the new result.
%% 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}}.
Read from the first line down
- 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.
Symbols are not secret signs
case Value ofMatch one value against branches.
if Guard ->Choose by guard conditions.
catch error:Reason ->Handle a named error reason.
Match each name to its meaning
case
case matches one value against ordered patterns.
if expression
Erlang if chooses the first guard expression that is true.
try expression
try separates normal results from expected error classes and reasons.
Why these forms are useful
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.
Close the answer and try
Use case to turn {error, timeout} into retry.
case {error, timeout} of
{ok, Value} -> Value;
{error, ____} -> ____
end.Target result: Return retry.
Stuck? Read one hint
Match timeout and return the atom retry.
After you run it, see one answer
case {error, timeout} of
{ok, Value} -> Value;
{error, timeout} -> retry
end.Think about it: Is Erlang `if` a general else-if statement?
It is a sequence of guard clauses; use case when patterns describe the data more clearly.
Remember these three lines
- 1
Use case for shapes.
- 2
Use if for guard-only choices.
- 3
Catch only errors the boundary expects.