condtional multi-unwrap and guard clauses

This commit is contained in:
2026-06-22 20:37:37 +02:00
parent 27f42dd253
commit 663f4dc658
9 changed files with 567 additions and 96 deletions
+56 -3
View File
@@ -1,6 +1,9 @@
# Milestone 5: conditional unwrapping `if opt |v| { ... }`.
# Tests a present optional binds and unwraps, a none takes the else branch, and
# that optional pointers (?*T) unwrap the same way.
# Milestone 5: conditional optional unwrapping, guards, and multi-unwrap.
observe :: func(counter @mut i32, value ?i32) ?i32 {
counter^ = counter^ + 1
return value
}
main :: func() i32 {
total i32 = 0
@@ -34,5 +37,55 @@ main :: func() i32 {
total = total + 1000
}
# guarded multi-unwrap exposes every capture to the guard and then-block
age ?i32 = 2
if a and age |value, years : value + years == 42| {
total = total
} else {
total = total + 100
}
# parenthesized chains and three-value unwraps are equivalent
bonus ?i32 = 0
if (a and age and bonus) |value, years, extra : value + years + extra == 42| {
total = total
} else {
total = total + 100
}
# false guards use the else branch, or simply fall through without one
if a |value : value == 0| {
total = total + 100
} else {
total = total
}
if a |value : value == 0| {
total = total + 100
}
# a failed unwrap prevents later expressions from being evaluated
calls i32 = 0
if b and observe(&calls, age) |missing, observed| {
total = total + missing + observed
}
if calls != 0 {
total = total + 100
}
# short-circuiting also applies after an earlier successful unwrap
if a and b and observe(&calls, age) |value, missing, observed| {
total = total + value + missing + observed
}
if calls != 0 {
total = total + 100
}
# optional pointers participate in multi-unwrap and guards
if a and p |value, q : value == 40 and q^ == 0| {
total = total
} else {
total = total + 100
}
return total # expect exit code 42
}