🎓 A1Learner
🔍
0 of 54 lessons completed

Elixir Cond Expressions

A cond expression picks a result by testing conditions in order. It fits choices that rest on comparisons rather than on the shape of a value.

The first passing test gives the grade

A score of 82 fails the first test and passes the second. The fallback is never reached.

score = 82
grade =
  cond do
    score >= 90 -> "A"
    score >= 70 -> "B"
    true -> "C"
  end
IO.puts(grade)

A middle test can be the winner

The tests are plain comparisons. Here the equality test in the middle is the one that passes.

count = 0
label =
  cond do
    count > 0 -> "has items"
    count == 0 -> "empty"
    true -> "negative count"
  end
IO.puts(label)

The true fallback catches a low score

Neither comparison passes for 35. The final test is the word true, so its branch always wins what is left.

score = 35
result =
  cond do
    score >= 80 -> "high"
    score >= 50 -> "middle"
    true -> "low"
  end
IO.puts(result)

Example

hours = 9
period =
  cond do
    hours < 12 -> "morning"
    hours < 18 -> "afternoon"
    true -> "evening"
  end
rush =
  cond do
    hours >= 7 and hours <= 9 -> "rush hour"
    true -> "quiet"
  end
IO.puts(period)
IO.puts(rush)

Key points

  • Test: the condition on the left of an arrow that a branch needs to pass.
  • Order: tests run from top to bottom, and the first passing test wins.
  • Result value: a cond returns the result of the first branch whose test passes.
  • True fallback: a final branch with the test true always passes and catches the rest.
  • No match: a cond with no passing test raises an error, so the true fallback keeps it safe.

In this example, hours is 9, so the first cond stops at its first test and returns morning. The second cond combines two comparisons with and, and both pass, so it returns rush hour.

Note

cond tests conditions on any values, while case matches patterns against one value.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

With x = 4, what does cond do x > 10 -> "big"; true -> "small" end return?