← Back to lesson 16: Choose the smallest clear control form

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.

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

  1. Read if ... do ... else: Choose between two Boolean paths.
  2. Read cond do: Try conditions in order.
  3. 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 if for one Boolean question with at most two outcomes.
cond
Use cond for several Boolean conditions checked from top to bottom.
case
Use case when patterns should inspect one value.

Original full exercise

Use cond to label 5 as :positive, 0 as :zero, and smaller values as :negative.

Exercise starter
number = 5
cond do
  number > 0 -> ____
  number == 0 -> ____
  true -> ____
end

With 5, return :positive.

Show hint

Fill the branches with three atoms.

Show original answer
Reference answer
number = 5
cond do
  number > 0 -> :positive
  number == 0 -> :zero
  true -> :negative
end
When is case clearer than cond?

Use case when several patterns inspect the shape of one value.

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