forked from argotorg/fe
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathif_let_while_let.fe
More file actions
88 lines (75 loc) · 2.37 KB
/
Copy pathif_let_while_let.fe
File metadata and controls
88 lines (75 loc) · 2.37 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
84
85
86
87
88
struct Point {
x: u256,
y: u256,
}
fn sum_if_let(_ point: Option<Point>) -> u256 {
if let Option::Some(Point { x, y }) = point {
x + y
} else {
0
}
}
fn sum_nested_if_let(_ value: Option<(Point, Option<u256>)>) -> u256 {
if let Option::Some((Point { x: 2, y }, Option::Some(value))) = value {
y + value
} else {
0
}
}
fn sum_compound_if_let(_ a: Option<Option<usize>>) -> usize {
if let Option::Some(b) = a && let Option::Some(c) = b {
c
} else {
0
}
}
fn sum_compound_if_let_annotated(_ a: Option<Option<usize>>) -> usize {
let x: usize = if let Option::Some(b) = a && let Option::Some(c) = b {
c
} else {
0
}
x
}
fn sum_while_let(_ values: [Option<usize>; 4]) -> usize {
let mut idx: usize = 0
let mut sum: usize = 0
while let Option::Some(value) = ref values[idx] {
sum += value
idx += 1
if idx == 4 {
break
}
}
sum
}
fn sum_descending_while_let(mut _ current: own Option<u256>) -> u256 {
let mut sum: u256 = 0
while let Option::Some(value) = current {
sum += value
if value == 0 {
current = Option::None
} else {
current = Option::Some(value - 1)
}
}
sum
}
#[test]
fn test_if_let_while_let() {
assert!(sum_if_let(Option::Some(Point { x: 2, y: 3 })) == 5)
assert!(sum_if_let(Option::None) == 0)
assert!(sum_nested_if_let(Option::Some((Point { x: 2, y: 3 }, Option::Some(7)))) == 10)
assert!(sum_nested_if_let(Option::Some((Point { x: 3, y: 3 }, Option::Some(7)))) == 0)
assert!(sum_nested_if_let(Option::Some((Point { x: 2, y: 3 }, Option::None))) == 0)
assert!(sum_nested_if_let(Option::None) == 0)
assert!(sum_compound_if_let(Option::Some(Option::Some(7))) == 7)
assert!(sum_compound_if_let(Option::Some(Option::None)) == 0)
assert!(sum_compound_if_let(Option::None) == 0)
assert!(sum_compound_if_let_annotated(Option::Some(Option::Some(11))) == 11)
assert!(sum_compound_if_let_annotated(Option::Some(Option::None)) == 0)
assert!(sum_compound_if_let_annotated(Option::None) == 0)
assert!(sum_while_let([Option::Some(2), Option::Some(5), Option::None, Option::Some(9)]) == 7)
assert!(sum_descending_while_let(Option::Some(3)) == 6)
assert!(sum_descending_while_let(Option::None) == 0)
}