Function clauses in Elixir
A launch countdown written as clauses: patterns and a guard pick the line, recursion drives the loop.
defmodule Countdown do
# One function, several clauses; the first head that matches wins.
def call(0), do: "liftoff!"
def call(3), do: "ignition sequence start"
def call(n) when rem(n, 2) == 0, do: "#{n}, holding steady"
def call(n), do: "#{n}"
# Recursion instead of a loop: each call peels one number off.
def run(0), do: IO.puts(call(0))
def run(n) do
IO.puts(call(n))
run(n - 1)
end
end
Countdown.run(5)
How it works
- Four
callclauses match top to bottom:0and3by value, even numbers by theremguard. run(0)is the base case that prints liftoff and stops.run(n)prints its line and callsrun(n - 1)— recursion standing in for a loop.
Keywords and builtins used here
CountdownIOdefdefmoduledoend
The run, in numbers
- Lines
- 17
- Characters to type
- 410
- Tokens
- 109
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 87 seconds.
Step 2 of 3 in Pattern matching, step 5 of 27 in Language basics.