On this page:
if
cond
when
unless
when
unless
8.12

6.13 Conditionals🔗ℹ

expression

if test_expr

| then_body

  ...

| else_body

  ...

If test_expr produces a true value (which is value other than #false), returns the result of the then_body clause, otherwise returns the result of the else_body clause.

Static information is gathered from then_body and else_body under the same conditions as the right-hand side of def (see Rules for Static Information), and the information is intersected to determine the static information of the if form.

> if #true

  | "yes"

  | "no"

"yes"

> if 1+2 == 3

  | let yep = "yes"

    yep

  | "no"

"yes"

expression

cond

| clause_test_expr:

    clause_result_body

    ...

| ...

 

expression

cond

| clause_test_expr:

    clause_result_body

    ...

| ...

| ~else:

    clause_result_body

    ...

 

expression

cond

| clause_test_expr:

    clause_result_body

    ...

| ...

| ~else clause_result_expr

Tries the clause_test_exprs in sequence, and as soon as one produces a non-#false value, returns the result of the corresponding clause_result_body block. The keyword ~else can be used as a synonym for #true in the last clause.

If no clause_test_expr produces a true value and there is no ~else clause, a run-time exception is thrown.

Static information is gathered from clause_result_bodys or clause_result_expr under the same conditions as the right-hand side of def (see Rules for Static Information), and the information is intersected to determine the static information of the cond form.

expression

when test_expr

| body

  ...

If test_expr produces a true value (which is value other than #false), returns the result of the body clause, otherwise returns #void.

> when #true

  | println("yes")

yes

> when #false

  | println("no")

expression

unless test_expr

| body

  ...

If test_expr produces #false, returns the result of the body clause, otherwise returns #void.

> unless #true

  | println("yes")

> unless #false

  | println("no")

no

binding operator

bind when expr

 

binding operator

bind unless expr

As binding forms, when and unless impose side conditions on a match. These forms match and bind the same as the given bind, but only when expr produces a true value for when or #false for unless, and the binding does not match otherwise. The bindings created by a match to bind are available for use in expr.

Because the bindings of bind must be made available for expr, a when or unless binding is not compatible for use with let, unless the set of names from bind is empty.

fun classify(v):

  match v

  | n :: Integral when n mod 2 .= 0:

      "even"

  | n :: Integral when n mod 2 .= 1:

      "odd"

  | _ :: Real:

      "other number"

  | ~else:

      "other value"

> classify(1)

"odd"

> classify(2)

"even"

> classify([1, 2])

"other value"