typestar

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

  1. if is an expression, so note receives whichever branch runs.
  2. cond do walks the visibility tests top to bottom and stops at the first truthy one.
  3. true -> is the catch-all rung, playing the role of else.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Control flow, step 19 of 27 in Language basics.

← Previous Next →