Learn/Elixir/4. Making decisions
Lesson 4 of 8
Sign in

Elixir, lesson 4

Making decisions

A program often has to pick one of several paths: is the password long enough, did the player win, is it a weekend? Elixir gives you three tools for this, and each one is an expression that returns a value.

Comparing values

OperatorMeaning
== / !=equal / not equal
<, <=, >, >=ordering
=== / !==

2 exercises to try what you just read.

Exercise 1

Letter grade

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

strictly equal, also checks integer vs float

1 == 1.0 is true, but 1 === 1.0 is false. For everyday comparisons == is what you want.

Combine conditions with and, or and not. They expect real booleans on the left, which catches mistakes early. Their cousins &&, || and ! accept any value: in Elixir only false and nil count as false, and everything else (including 0 and "") counts as true.

if and else

Use if for a simple yes/no choice. Because it is an expression, you can bind its result:

For longer branches, use the block form:

cond: the first true condition wins

When you have more than two choices, cond is cleaner than nested ifs. Elixir checks each condition from top to bottom and runs the first one that is true. End with true -> as a catch-all, because cond raises an error if nothing matches.

case: match on shape, with guards

case compares a value against patterns. A pattern can be a literal like 0, a structure like {:ok, value}, or a name that matches anything. Add a guard with when to require an extra condition.

The _ at the end matches anything, like an "else". Reach for case when the decision depends on the shape of a value, and cond when it depends on a list of conditions.

Further reading

  • Getting started: case, cond, and if
  • Patterns and guards

Read a test score and print its letter grade:

  • 90 to 100: A
  • 80 to 89: B
  • 70 to 79: C
  • 60 to 69: D
  • 0 to 59: F
  • below 0 or above 100: Invalid

Input: one line with a whole number. Output: the grade on one line. For 85, print B.

A year is a leap year if it is divisible by 4, except years divisible by 100, which are not, unless they are also divisible by 400. So 2024 and 2000 are leap years, but 1900 is not.

Input: one line with a year. Output: leap or common.

age = 20
member = true
IO.puts(age >= 18 and member)   # true
IO.puts(not member)             # false
temp = 31
advice = if temp > 25, do: "Wear a hat", else: "Bring a jacket"
IO.puts(advice)
if temp > 25 do
  IO.puts("It's hot!")
else
  IO.puts("It's fine.")
end
speed = 72
label =
  cond do
    speed > 120 -> "way too fast"
    speed > 50 -> "fast"
    true -> "relaxed"
  end
IO.puts(label)   # fast
case Integer.parse("17") do
  {n, ""} when n < 0 -> IO.puts("negative")
  {n, ""} -> IO.puts("the number #{n}")
  _ -> IO.puts("not a number")
end