On this page:
guard
guard.let
8.17.0.6

5.3 Guards🔗ℹ

definition

guard test_expr

| failure_body

  ...

body

...

Checks that test_expr produces a true value, evaluating the body sequence if so. If test_expr produces #false, then body is skipped and failure_body is evaluated, instead. This is equivalent to if test_expr | body ... | failure_body ..., and is primarily useful when body is much more complex than failure_body or contains a mixture of definitions and additional guard forms interleaved with each other.

Static information works the same way as it would in an equivalent if expression.

> block:

    guard #true | println("KABOOM!!!")

    println("everything working normally")

everything working normally

> block:

    guard #false | println("KABOOM!!!")

    println("everything working normally")

KABOOM!!!

Checks that target_expr produces values that match test_values_bind and makes the bindings of test_values_bind available in the subsequent body sequence. If target_expr does not match test_values_bind, then the body sequence is skipped and failure_body is evaluated, instead. This is the pattern matching variant of guard, see its documentation for general advice on using guards.

fun print_third(xs):

  guard.let [_, _, third, & _] = xs

  | println("list doesn't have three or more elements")

  println(third)

> print_third(["hi", "hello", "goodbye", "farewell"])

goodbye

> print_third(["hi", "hello"])

list doesn't have three or more elements

The block form with target_body is equivalent to using block: target_body ... as the target_expr.

fun print_third(xs):

  guard.let [_, _, third, & _]:

    xs

  | println("list doesn't have three or more elements")

  println(third)

> print_third(["hi", "hello", "goodbye", "farewell"])

goodbye

> print_third(["hi", "hello"])

list doesn't have three or more elements