Lake

Enums

An enum is a tagged sum type: a value that is exactly one of several named variants, each optionally carrying a payload. Enums are the choice half of Lake's type system, complementing records.

§Declaring an enum

lake
Shape is enum {
  Circle(i64)            # a variant with a payload
  Rect(i64 i64)
  Unit                   # a variant with no payload
}

Each variant becomes a constructor under the enum's name:

lake
let a = Shape.Circle(5)
let b = Shape.Rect(3 4)
let c = Shape.Unit

§Matching with when

when over an enum dispatches on the variant and binds its payload. The compiler checks exhaustiveness — every variant must be handled (or a _ catch-all provided):

lake
area is {
  s Shape -> ret i64 {
    when s {
      Circle(r)  -> { ret 3 * r * r }
      Rect(w h)  -> { ret w * h }
      Unit       -> { ret 0 }
    }
  }
}

This is the same when you use for literal guards — here the patterns are variant names rather than values, and binding the payload replaces an if-cascade entirely.

§Generic enums

Variants can carry type parameters. The two most useful enums — Option and Result — are generic enums in the standard library:

lake
Option[T] is enum {
  Some(T)
  None
}

Result[T E] is enum {
  Ok(T)
  Err(E)
}

Option[T] models “a value or nothing”; Result[T E] models “success or failure”. See error handling for how they replace null and exceptions, and generics for the type-parameter machinery.

§Key ideas

  • An enum is a sum type: a value is exactly one named variant.
  • Variants are constructors (Shape.Circle(5)), optionally with payloads.
  • when matches variants, binds payloads, and is checked for exhaustiveness.
  • Enums may be generic (Option[T], Result[T E]), monomorphised per use.