forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpattern_match.nula
More file actions
83 lines (72 loc) · 2.19 KB
/
Copy pathpattern_match.nula
File metadata and controls
83 lines (72 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Pattern Matching — exhaustive walk through Nulang's match expressions.
// Covers literal matching, variable binding, wildcards, guards, nested
// patterns, records, and user-declared variant types.
//
// Run with: nulang examples/pattern_match.nula
// User-declared option and result types (there is no prelude — yet!)
type Option[T] = Some(T) | None
// A simple enum for demonstration
type Color = Red | Green | Blue
// -- Literal matching --
fn describe_int(n: Int) -> String {
match n {
case 0 => "zero"
case 1 => "one"
case n => "other: " + perform Int.to_string(n)
}
}
// -- Variant matching with payload binding --
fn unwrap_or(opt: Option[Int], default: Int) -> Int {
match opt with {
| Some(x) => x
| None => default
}
}
// -- Guard expressions --
fn classify(n: Int) -> String {
match n with {
| x if x < 0 => "negative"
| x if x == 0 => "zero"
| x if x < 10 => "small positive"
| _ => "large"
}
}
// -- Nested patterns --
fn describe(opt: Option[Option[Int]]) -> String {
match opt with {
| Some(Some(n)) => "nested value: " + perform Int.to_string(n)
| Some(None) => "outer Some, inner None"
| None => "outer None"
}
}
// -- Record field matching --
fn area(rect: { x: Int, y: Int, w: Int, h: Int }) -> Int {
match rect with {
| { w: width, h: height } => width * height
}
}
// -- Variant enum matching --
fn color_code(c: Color) -> Int {
match c with {
| Red => 1
| Green => 2
| Blue => 3
}
}
// -- Put it all together --
fn main() {
perform IO.print(describe_int(0))
perform IO.print(describe_int(5))
perform IO.print(perform Int.to_string(unwrap_or(Some(42), 0)))
perform IO.print(perform Int.to_string(unwrap_or(None, 99)))
perform IO.print(classify(-5))
perform IO.print(classify(7))
perform IO.print(classify(100))
perform IO.print(describe(Some(Some(7))))
perform IO.print(describe(Some(None)))
perform IO.print(describe(None))
let r = { x: 0, y: 0, w: 10, h: 5 }
perform IO.print(perform Int.to_string(area(r)))
perform IO.print(perform Int.to_string(color_code(Blue)))
0
}