-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathiter2.mbt
90 lines (82 loc) · 2.11 KB
/
iter2.mbt
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
89
90
// Copyright 2025 International Digital Economy Academy
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///|
// Similar to Iter but used for two values
// It is useful for iterating over map entries
// without boxing
// It is useful for syntax sugar
// ```
// for k, v in map { ... }
// ```
type Iter2[A, B] ((A, B) -> IterResult) -> IterResult
///|
//TODO: Add intrinsic for Iter::run
pub fn Iter2::run[A, B](
self : Iter2[A, B],
f : (A, B) -> IterResult
) -> IterResult {
(self._)(f)
}
///|
pub impl[A : Show, B : Show] Show for Iter2[A, B] with output(self, logger) {
logger.write_string("[")
let mut first = true
for k, v in self {
if not(first) {
// AI: support !first ?
logger.write_string(", ")
} else {
first = false
}
logger.write_string("(")
logger.write_object(k)
logger.write_string(", ")
logger.write_object(v)
logger.write_string(")")
}
logger.write_string("]")
}
///|
pub fn Iter2::new[A, B](
f : ((A, B) -> IterResult) -> IterResult
) -> Iter2[A, B] {
Iter2(f)
}
///|
pub fn Iter2::each[A, B](self : Iter2[A, B], f : (A, B) -> Unit) -> Unit {
self.run(fn(a, b) {
f(a, b)
IterContinue
})
|> ignore
}
///|
pub fn Iter2::iter[A, B](self : Iter2[A, B]) -> Iter[(A, B)] {
Iter::new(fn(yield_) { self.run(fn(a, b) { yield_((a, b)) }) })
}
///|
pub fn Iter2::iter2[A, B](self : Iter2[A, B]) -> Iter2[A, B] {
// This is a no-op to make sure
// `for k,v in map.iter2() { ... }`
// still work
self
}
///|
pub fn Iter2::to_array[A, B](self : Iter2[A, B]) -> Array[(A, B)] {
let arr = []
for k, v in self {
arr.push((k, v))
}
arr
}