v / examples
Raw file | 62 loc (51 sloc) | 821 bytes | Latest commit hash 017ace6ea
1// Example of sum types
2// Models a landing craft leaving orbit and landing on a world
3import rand
4import time
5
6struct Moon {
7}
8
9struct Mars {
10}
11
12fn (m Mars) dust_storm() bool {
13 return rand.int() >= 0
14}
15
16struct Venus {
17}
18
19type World = Mars | Moon | Venus
20
21struct Lander {
22}
23
24fn (l Lander) deorbit() {
25 println('leaving orbit')
26}
27
28fn (l Lander) open_parachutes(n int) {
29 println('opening ${n} parachutes')
30}
31
32fn wait() {
33 println('waiting...')
34 time.sleep(1 * time.second)
35}
36
37fn (l Lander) land(w World) {
38 if w is Mars {
39 for w.dust_storm() {
40 wait()
41 }
42 }
43 l.deorbit()
44 match w {
45 Moon {} // no atmosphere
46 Mars {
47 // light atmosphere
48 l.open_parachutes(3)
49 }
50 Venus {
51 // heavy atmosphere
52 l.open_parachutes(1)
53 }
54 }
55 println('landed')
56}
57
58fn main() {
59 l := Lander{}
60 l.land(Venus{})
61 l.land(Mars{})
62}