| 📦 Turbo Golo d710c1b k33g 23h ago | 1 | module demo.Shapes |
| 2 | |
| 3 | # A struct is a named record. Its fields are read with a colon: p: x(). |
| 4 | struct Point = { x, y } |
| 5 | |
| 6 | # A union is one type with several forms. Each variant may carry fields, and |
| 7 | # every variant gets an is<Variant>() predicate for free. |
| 8 | union Shape = { |
| 9 | Circle = { radius } |
| 10 | Rect = { width, height } |
| 11 | } |
| 12 | |
| 13 | # An augmentation adds functions to a type after the fact. `this` is the value |
| 14 | # the function is called on. |
| 15 | augment Point { |
| 16 | function describe = |this| -> "(" + this: x() + ", " + this: y() + ")" |
| 17 | } |
| 18 | |
| 19 | augment Shape { |
| 20 | function area = |this| { |
| 21 | return match { |
| 22 | when this: isCircle() then 3.14159 * this: radius() * this: radius() |
| 23 | when this: isRect() then this: width() * this: height() |
| 24 | otherwise 0 |
| 25 | } |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | function main = |args| { |
| 30 | let origin = Point(0, 0) |
| 31 | println("origin is " + origin: describe()) |
| 32 | |
| 33 | let shapes = list[Shape_Circle(1.0), Shape_Rect(2.0, 3.0)] |
| 34 | foreach shape in shapes { |
| 35 | println(shape + " has area " + shape: area()) |
| 36 | } |
| 37 | |
| 38 | # A closure is a function value: |parameters| -> expression. |
| 39 | let scaled = list[shape: area() * 2 foreach shape in shapes] |
| 40 | println("doubled: " + scaled) |
| 41 | } |