Choose the smallest clear control form: 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 `if`, `cond`, and `case` for different shapes of decisions.
Classify a score, inspect one parse result, and make one Boolean choice.
Run this first
Run it once, change one input, and compare the new result.
# Use each form for the question it fits
score = 76
label = cond do score >= 90 -> :great; score >= 60 -> :pass; true -> :retry end
parsed = case Integer.parse("42") do {n, ""} -> {:ok, n}; _ -> {:error, :bad_text} end
allowed = if score >= 60, do: :yes, else: :no
{label, parsed, allowed}The result is {:pass, {:ok, 42}, :yes}.
Steps for the full example
- Read
if ... do ... else: Choose between two Boolean paths. - Read
cond do: Try conditions in order. - Read
case value do: Match one value against clauses.
Original lesson notes
Run the example first. Predict one result, then change one input and run it again.
Use if for one Boolean question with at most two outcomes.
Use cond for several Boolean conditions checked from top to bottom.
Symbols and terms
if ... do ... else- Choose between two Boolean paths.
cond do- Try conditions in order.
case value do- Match one value against clauses.
- if
- Use
iffor one Boolean question with at most two outcomes. - cond
- Use
condfor several Boolean conditions checked from top to bottom. - case
- Use
casewhen patterns should inspect one value.
Original full exercise
Use cond to label 5 as :positive, 0 as :zero, and smaller values as :negative.
number = 5
cond do
number > 0 -> ____
number == 0 -> ____
true -> ____
endWith 5, return :positive.
Show hint
Fill the branches with three atoms.
Show original answer
number = 5
cond do
number > 0 -> :positive
number == 0 -> :zero
true -> :negative
endWhen is case clearer than cond?
Use case when several patterns inspect the shape of one value.
Original lesson takeaways
- Use
iffor one Boolean split. - Use
condfor ordered conditions. - Use
casefor pattern-driven choices.