Case Expressions

Posted by Beetle B. on Tue 02 August 2016

Example (newtype is defined in a previous post).

fun f (x : newtype) =
  case x of
    Pizza => 3
  | Str s => 8
  | TwoInts(i1, i2) => i1 + i2

To call f:


In a case expression, the expressions of all branches must have the same type.

General syntax:

case e0 of
      p1 => e1
    | p2 => e2
    | p3 => e3

The pi are called patterns. They are not expressions. We do not evaluate them.

All the types of ei must be the same.

The compiler checks:

  • No missing cases (warning)
  • No redundant cases (error)

You can use case anywhere you use an expression. It is often the whole function body but need not be.


Evaluate e0 to v0. Then the first pattern that matches v0 is used. The environment is augmented with ei. Note that if the pattern is a constructor C(x1,...,xn), then each xi is bound to vi in the environment of ei.

Example usage with Options

fun inc_or_zero int option =
  case intoption of
      NONE => 0
    | SOME i => i+1

This is preferred to isSome and valOf.