if and cond in Elixir
Both conditionals return values: if for two branches, cond for a ladder of tests.
# if is an expression: both branches hand back a value.
depth_ft = 23
note = if depth_ft > 30, do: "bring the long rope", else: "day trip"
IO.puts(note)
# cond picks the first branch whose condition is truthy.
visibility_ft = 8
rating =
cond do
visibility_ft >= 30 -> "gin clear"
visibility_ft >= 15 -> "workable"
true -> "silted out"
end
IO.puts("cave rating: #{rating}")
How it works
ifis an expression, sonotereceives whichever branch runs.cond dowalks the visibility tests top to bottom and stops at the first truthy one.true ->is the catch-all rung, playing the role of else.
Keywords and builtins used here
IOconddoendif
The run, in numbers
- Lines
- 16
- Characters to type
- 375
- Tokens
- 67
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 54 seconds.
Step 1 of 3 in Control flow, step 19 of 27 in Language basics.