Enums

Enums are algebraic sum types. Each variant can optionally carry a payload, making them useful for modeling states, results, and tagged unions.

Enums are algebraic types. Variants can carry payloads.

enum Shape {
  Circle(float)
  Rect(float, float)
  Point
}

Pattern matching destructures enum variants.

fn area(s: Shape) -> float {
  match s {
    Circle(r) -> 3.14159 * r * r
    Rect(w, h) -> w * h
    Point -> 0.0
  }
}

fn main() {
  c = Circle(5.0)
  r = Rect(3.0, 4.0)

  println(area(c))
  println(area(r))
  println(area(Point))
}
$ pyr run enums.pyr
78.53975
12
0