Skip to content

Commit 166a9c9

Browse files
committed
PriorityQueue::to_array in a efficient way
1 parent 4920bcd commit 166a9c9

2 files changed

Lines changed: 19 additions & 17 deletions

File tree

priority_queue/moon.pkg.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
"import": [
33
"moonbitlang/core/builtin",
44
"moonbitlang/core/iter",
5+
"moonbitlang/core/array",
56
"moonbitlang/core/assertion",
67
"moonbitlang/core/coverage"
78
]

priority_queue/priority_queue.mbt

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -90,16 +90,20 @@ test "copy" {
9090
}
9191
9292
pub fn to_array[T : Compare](self : PriorityQueue[T]) -> Array[T] {
93-
let queue = self.copy()
94-
let arr = Array::new()
95-
loop queue.peek() {
96-
Some(p) => {
97-
arr.push(p)
98-
queue.pop_exn()
99-
continue queue.peek()
93+
let arr : Array[T] = []
94+
fn go(x : Node[T]) {
95+
match x {
96+
Cons(node) => {
97+
arr.push(node.content)
98+
go(node.sibling)
99+
go(node.child)
100+
}
101+
Nil => ()
100102
}
101-
None => ()
102103
}
104+
105+
go(self.top)
106+
arr.sort_by(fn(x, y) { if x < y { 1 } else { -1 } })
103107
arr
104108
}
105109
@@ -112,16 +116,13 @@ test "to_array" {
112116
pub fn as_iter[T : Compare](self : PriorityQueue[T]) -> @iter.Iter[T] {
113117
@iter.Iter::_unstable_internal_make(
114118
fn(yield) {
115-
let queue = self.copy()
116-
loop queue.peek() {
117-
Some(p) => {
118-
if yield(p).not() {
119-
break false
120-
}
121-
queue.pop_exn()
122-
continue queue.peek()
119+
let arr = self.to_array()
120+
for i = 0; i < arr.length(); i = i + 1 {
121+
if yield(arr[i]).not() {
122+
break false
123123
}
124-
None => true
124+
} else {
125+
true
125126
}
126127
},
127128
)

0 commit comments

Comments
 (0)