Skip to content

Commit

Permalink
adapt iter API for set
Browse files Browse the repository at this point in the history
  • Loading branch information
bobzhang committed Jan 12, 2025
1 parent ffb701d commit 147e136
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 6 deletions.
3 changes: 2 additions & 1 deletion sorted_map/map.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -258,18 +258,19 @@ fn range_aux[K : Compare, V](
Some(node) => {
let cmp_key_low = node.key.compare(low)
let cmp_key_high = node.key.compare(high)

if cmp_key_low > 0 {
// we should go left
guard let IterContinue = range_aux(node.left, low, high).run(yield_) else {
x => return x
}

}
if cmp_key_low >= 0 && cmp_key_high <= 0 {
// we should yield this node
guard let IterContinue = yield_(node.key, node.value) else {
x => return x
}

}
if cmp_key_high < 0 {
guard let IterContinue = range_aux(node.right, low, high).run(yield_) else {
Expand Down
36 changes: 32 additions & 4 deletions sorted_set/set.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -429,10 +429,38 @@ fn to_array[T](self : Node[T]) -> Array[T] {
}

///|
pub fn range[V : Compare](self : T[V], low : V, high : V) -> Array[V] {
let result = []
self.each(fn(x) { if x >= low && x <= high { result.push(x) } })
result
pub fn range[V : Compare](self : T[V], low : V, high : V) -> Iter[V] {
range_aux(self.root, low, high)
}

///|
fn range_aux[V : Compare](root : Node[V]?, low : V, high : V) -> Iter[V] {
Iter::new(fn(yield_) {
match root {
None => IterContinue
Some(node) => {
let cmp_key_low = node.value.compare(low)
let cmp_key_high = node.value.compare(high)
if cmp_key_low > 0 {
guard let IterContinue = range_aux(node.left, low, high).run(yield_) else {
x => return x
}

}
if cmp_key_low >= 0 && cmp_key_high <= 0 {
guard let IterContinue = yield_(node.value) else { x => return x }

}
if cmp_key_high < 0 {
guard let IterContinue = range_aux(node.right, low, high).run(yield_) else {
x => return x
}

}
IterContinue
}
}
})
}

// AVL tree operations
Expand Down
2 changes: 1 addition & 1 deletion sorted_set/sorted_set.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl T {
is_empty[V : Compare](Self[V]) -> Bool
iter[V](Self[V]) -> Iter[V]
op_equal[V : Compare](Self[V], Self[V]) -> Bool
range[V : Compare](Self[V], V, V) -> Array[V]
range[V : Compare](Self[V], V, V) -> Iter[V]
remove[V : Compare](Self[V], V) -> Unit
size[V : Compare](Self[V]) -> Int64
subset[V : Compare](Self[V], Self[V]) -> Bool
Expand Down

0 comments on commit 147e136

Please sign in to comment.