typestar

case and guards in Elixir

One case expression sorts sensor readings into three outcomes by shape and size.

defmodule Gauge do
  # case tries each pattern in order; when bolts a guard onto a clause.
  def check(reading) do
    case reading do
      {:ok, temp} when temp >= 100 -> "boiling at #{temp} C"
      {:ok, temp} -> "steady at #{temp} C"
      {:error, why} -> "sensor down: #{why}"
    end
  end
end

IO.puts(Gauge.check({:ok, 104}))
IO.puts(Gauge.check({:ok, 21}))
IO.puts(Gauge.check({:error, "loose wire"}))

How it works

  1. case reading do tries each pattern in order and returns the branch that fits.
  2. {:ok, temp} when temp >= 100 matches the same shape as the next clause, but only past its guard.
  3. {:error, why} catches the failure tuple and reports the reason.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
380
Tokens
105
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 84 seconds.

Type this snippet

Step 3 of 3 in Pattern matching, step 6 of 27 in Language basics.

← Previous Next →