Elixir basics · Lesson 15 (open contents)
Choose the smallest clear control form
Use `if`, `cond`, and `case` for different shapes of decisions.
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}.
Read from the first line down
- 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.
Symbols are not secret signs
if ... do ... elseChoose between two Boolean paths.
cond doTry conditions in order.
case value doMatch one value against clauses.
Match each name to its meaning
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.
Why these forms are useful
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.
Close the answer and try
Use cond to label 5 as :positive, 0 as :zero, and smaller values as :negative.
number = 5
cond do
number > 0 -> ____
number == 0 -> ____
true -> ____
endTarget result: With 5, return :positive.
Stuck? Read one hint
Fill the branches with three atoms.
After you run it, see one answer
number = 5
cond do
number > 0 -> :positive
number == 0 -> :zero
true -> :negative
endThink about it: When is `case` clearer than `cond`?
Use case when several patterns inspect the shape of one value.
Remember these three lines
- 1
Use
iffor one Boolean split. - 2
Use
condfor ordered conditions. - 3
Use
casefor pattern-driven choices.