One-liners and defp in Elixir
Two function shapes: the one-line do: body and the private helper only its module can call.
defmodule Tides do
# A one-line body rides on the def itself with do:
def high?(feet), do: feet >= 9.5
def report(feet) do
IO.puts("#{feet} ft -- #{advice(feet)}")
end
# defp makes a helper invisible outside the module
defp advice(feet) do
if high?(feet), do: "stay off the causeway", else: "safe to cross"
end
end
Tides.report(11.2)
Tides.report(4.0)
How it works
def high?(feet), do: feet >= 9.5puts a one-expression body on the def line itself.reportinterpolates the reading and hands the judgment call toadvice.defp adviceis private: inside the module an ordinary function, outside it does not exist.
Keywords and builtins used here
IOTidesdefdefmoduledefpdoendif
The run, in numbers
- Lines
- 16
- Characters to type
- 354
- Tokens
- 77
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 58 seconds.
Step 2 of 3 in Modules & functions, step 2 of 27 in Language basics.