@@ -87,20 +87,42 @@ def find_item(items: list[str], target: str) -> str?:
8787 return Some(item)
8888 return None()
8989
90+ def describe(val: int?) -> str:
91+ match val:
92+ case Some(v):
93+ if v > 100:
94+ return f"big value: {v}"
95+ return f"value: {v}"
96+ case None():
97+ return "nothing"
98+
9099 def main():
91100 fruits = ["apple", "banana", "cherry"]
92101
102+ # Pattern matching on Optional
93103 result = find_item(fruits, "banana")
94- print(f"Found: {result.unwrap()}")
104+ match result:
105+ case Some(fruit):
106+ print(f"Found: {fruit}")
107+ case None():
108+ print("Not found")
95109
96110 result2 = find_item(fruits, "grape")
97- print(f"Fallback: {result2.unwrap_or('nothing')}")
98-
99- some_val: int? = Some(42)
100- print(f"Value: {some_val.unwrap()}")
101-
102- no_val: int? = None()
103- print(f"Default: {no_val.unwrap_or(0)}")
111+ match result2:
112+ case Some(fruit):
113+ print(f"Found: {fruit}")
114+ case None():
115+ print("Not found")
116+
117+ # Nested logic in match arms
118+ print(describe(Some(42)))
119+ print(describe(Some(200)))
120+ print(describe(None()))
121+
122+ # unwrap helpers still work too
123+ some_val: int? = Some(10)
124+ print(f"Unwrapped: {some_val.unwrap()}")
125+ print(f"Fallback: {None().unwrap_or(0)}")
104126 """ ;
105127
106128 private const string ResultTypes = """
@@ -111,24 +133,37 @@ def validate_age(age: int) -> int !str:
111133 return Err("Age seems unrealistic")
112134 return Ok(age)
113135
114- def main() :
115- # Ok path
116- r1 = validate_age(25)
117- print(f"Valid age: {r1.unwrap_or(-1)}")
118-
119- # Error paths
120- r2 = validate_age(-5)
121- print(f"Negative : {r2.unwrap_or(-1)}")
136+ def classify(val: int !str) -> str :
137+ match val:
138+ case Ok(v):
139+ if v >= 18:
140+ return f"adult, age {v}"
141+ return f"minor, age {v}"
142+ case Err(e):
143+ return f"invalid : {e}"
122144
123- r3 = validate_age(200)
124- print(f"Too high: {r3.unwrap_or(-1)}")
145+ def main():
146+ # Pattern matching on Result
147+ ages = [25, -5, 200, 10]
148+ for age in ages:
149+ result = validate_age(age)
150+ match result:
151+ case Ok(v):
152+ print(f"Valid age: {v}")
153+ case Err(e):
154+ print(f"Error: {e}")
155+
156+ # Nested logic in match arms
157+ print(classify(Ok(25)))
158+ print(classify(Ok(10)))
159+ print(classify(Err("bad input")))
125160
126161 # try expression wraps exceptions in Result
127- r4 : int !Exception = try int("42")
128- print(f"Parsed: {r4 .unwrap_or(0)}")
162+ r1 : int !Exception = try int("42")
163+ print(f"Parsed: {r1 .unwrap_or(0)}")
129164
130- r5 : int !Exception = try int("hello")
131- print(f"Failed: {r5 .unwrap_or(-1)}")
165+ r2 : int !Exception = try int("hello")
166+ print(f"Failed: {r2 .unwrap_or(-1)}")
132167 """ ;
133168
134169 private const string ListComprehensions = """
0 commit comments