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
case reading dotries each pattern in order and returns the branch that fits.{:ok, temp} when temp >= 100matches the same shape as the next clause, but only past its guard.{:error, why}catches the failure tuple and reports the reason.
Keywords and builtins used here
GaugeIOcasedefdefmoduledoend
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.
Step 3 of 3 in Pattern matching, step 6 of 27 in Language basics.