code / tomo-koans

Lines447 Tomo432 INI9 Markdown6
(32 lines)
1 # Enums
3 # Enums define a type with multiple possible variants:
4 enum Shape(Circle(radius: Num), Rectangle(width: Num, height: Num), Point)
6 # Use `when` to pattern match an enum:
7 func area(shape: Shape -> Num)
8 when shape is Circle(radius)
9 return Num.PI * radius^2
10 is Rectangle(width, height)
11 return width * height
12 is Point
13 return 0
15 func main()
17 # You can create instances of an enum:
18 point := Shape.Point
20 # Single member enums display without the field names:
21 circle := Shape.Circle(radius=10)
22 assert circle == Shape.Circle(10)
24 # Multi-member enums explicitly list their field names:
25 rect := Shape.Rectangle(width=4, height=5)
26 assert rect == Shape.Rectangle(width=4, height=5)
28 assert point.area() == ???
30 assert rect.area() == ???
32 assert "My shape is $circle" == ???