Skip to content

Patterns and conditions

24. Test a match with is, bind with if Pattern = x, branch with case

Section titled “24. Test a match with is, bind with if Pattern = x, branch with case”

When only whether a value matches matters, write value is Pattern (spec §8 Pattern test; tour: Pattern Matching), not a case with a True arm and a _ -> False arm:

fn is_isosceles(sides: (Float, Float, Float)) -> Bool
    kind(sides) is Some(.Equilateral or .Isosceles)
end

A predicate that only tests a pattern needs no function of its own: pass a capture, Iter.filter(&(&1 is .Item(_))), or Iter.reject(&(&1 is None)). An equality test against one value stays == (state == .Open); is reads better once the pattern has a payload, a wildcard or an or (state is (.Open or .Paused)).

is binds nothing. When the branch that matched uses the payload, write if Pattern = expr for a small, local match where only that branch needs the names:

label = if Some(name) = maybe_name then
    name
else
    "unknown"
end

Write a case when every outcome continues with work of its own, when there is more than one shape to tell apart, or when exhaustiveness matters.

Add as name to a pattern (spec §10 Naming the Whole Match) when the arm needs the whole value the pattern matched, such as to pass it on. When the arm needs only fields, bind the fields and leave the whole unnamed:

case result
    Ok(Transaction{kind: .Deposit} as t) -> record(t)
    Ok(Transaction{amount:})             -> amount
    Err(msg)                             -> msg
end

Arms that return the same thing are one arm with alternatives (spec §10 Alternatives; tour: Pattern Matching):

case cp
    ' ' or '(' or ')' or '-' -> True
    _                        -> False
end

not one arm per value repeating -> True. Put the or where the arms differ: Some(.Equilateral or .Isosceles) -> True rather than Some(.Equilateral) or Some(.Isosceles) -> True. Keep separate arms when their bodies only happen to agree today and are expected to diverge.

26. Take a vector apart with a pattern when its shape decides

Section titled “26. Take a vector apart with a pattern when its shape decides”

When the code branches on a vector’s length or reads its first or last elements, match it with a vector pattern (spec §10 Vector Destructuring; tour: Pattern Matching) instead of Vector.length and Vector.get(...)!. The pattern says which shapes the code handles, and the compiler checks that it handles them all:

fn describe(v: Vector<Int>) -> String
    case v
        []                -> "empty"
        [only]            -> "just ${only}"
        [first, .., last] -> "${first} to ${last}"
    end
end

Keep Vector.get for an index that comes from arithmetic, such as a grid’s row and column. Over a set, a bracket pattern tests membership, so reach for one when an arm needs several elements present at once (["admin", "owner", ..]) or binds the rest; to test one element, in is shorter (§31).

27. Write a case of conditions with no subject

Section titled “27. Write a case of conditions with no subject”

A case whose arms all test conditions matches nothing, so it has no subject (spec §8 case; tour: Pattern Matching):

case
    count < 10  -> Err(.TooFewDigits)
    count == 10 -> Ok(digits)
    _           -> Err(.TooManyDigits)
end

not case digits with arms such as _ when count < 10 -> ..., where every arm matches the subject with _ and only the guards decide. Keep the subject when an arm’s pattern reads it, and write a condition there as that arm’s when guard.

An if chain that picks a value from three or more branches is the same choice, so it is this case too:

size = case
    bytes < 1_024     -> "${bytes} B"
    bytes < 1_048_576 -> "${bytes / 1_024} KB"
    _                 -> "${bytes / 1_048_576} MB"
end

not

size = if bytes < 1_024 then
    "${bytes} B"
else if bytes < 1_048_576 then
    "${bytes / 1_024} KB"
else
    "${bytes / 1_048_576} MB"
end

A plain if/else of two branches stays an if, and so does a chain whose branches run statements for their effects rather than produce a value.

An Html literal’s slot takes a Maybe and shows its value or nothing, in element content and inside a quoted attribute value alike. To show a part only when a condition holds, give the slot an if whose else is None (spec §8 if/else):

count = if unread > 0 then Some(Html" <b>${unread}</b>") else None

Html"<p class='inbox ${if unread > 0 then Some("unread") else None}'>Inbox${count}</p>"

not ${if unread > 0 then ... else Html.empty()} or else "". To leave a whole attribute out, give it an unquoted value: class=${if active then Some("active") else None}. Where the value is used as itself, write the else with that value: if c then x else y, not if c then Some(x) else None followed by Maybe.with_default(y).

28. Negate with !=, refute and Iter.reject before not

Section titled “28. Negate with !=, refute and Iter.reject before not”

not takes everything down to == (spec §8 Logical operators), so not a == b reads as a != b and is best written that way. An assertion that something is false is refute x (spec §17 Assertions), not assert not x. A predicate passed to Iter.filter only to be negated is Iter.reject:

fresh = candidates |> Iter.reject(&(&1 in seen))

not Iter.filter(fn c -> not c in seen). Elsewhere a negated call reads well as a not pipe stage when the value is already flowing through a pipeline (name |> String.trim() |> not Iter.is_empty()), and as a plain not f(x) otherwise. When Iter.reject does not fit a capture, write &(not f(&1)).