match statements

This commit is contained in:
2026-06-28 23:44:01 +02:00
parent 981ccb047a
commit 462632554c
12 changed files with 1057 additions and 6 deletions
+75
View File
@@ -0,0 +1,75 @@
Animal :: enum {
dog
cat
bird
}
# tagged union over an existing enum (variants are a subset of the enum's members)
Data :: union(Animal) {
dog i32
bird i32
}
# tagged union with a synthesized tag enum
Shape :: union(enum) {
square i32 # side
circle i32 # radius
}
# Statement match with payload capture; every variant returns, so the function needs
# no trailing return (the desugared if/else chain covers all paths).
describe :: func(d Data) i32 {
match d {
.dog |age|: return age + 1
.bird |wingspan|: return wingspan + 2
}
}
# Value match: single-expression arms yield implicitly, a block arm yields explicitly.
area :: func(s Shape) i32 {
result :: match s {
.square |side|: side * side
.circle |r|: {
# 3 ~ pi, integer arithmetic
yield 3 * r * r
}
}
return result
}
main :: func() i32 {
dog Data = Data{ dog = 9 }
bird Data = Data{ bird = 38 }
total i32 = describe(dog) + describe(bird) # 10 + 40 = 50
# enum statement match, exhaustive without an `else`
a Animal = .bird
rank i32 = 0
match a {
.dog: rank = 1
.cat: rank = 2
.bird: rank = 3
}
# enum value match
legs :: match a {
.dog: 4
.cat: 4
.bird: 2
}
# integer match with a mandatory `else`
bucket i32 = 0
match rank {
1: bucket = 100
3: bucket = 5
else: bucket = 99
}
sq Shape = Shape{ square = 4 }
ci Shape = Shape{ circle = 2 }
shapes i32 = area(sq) + area(ci) # 16 + 12 = 28
# 50 + 3 + 2 + 5 + 28 = 88
return total + rank + legs + bucket + shapes - 88
}