Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve each for sorted_set and refactor eachi #1458

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 11 additions & 29 deletions sorted_set/set.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -322,39 +322,11 @@ pub fn size[V : Compare](self : T[V]) -> Int64 {
///|
/// Iterates the set.
pub fn each[V](self : T[V], f : (V) -> Unit) -> Unit {
match self.root {
None => ()
Some(root) => root.each(f)
}
}

///|
fn each[V](self : Node[V], f : (V) -> Unit) -> Unit {
let s = []
let mut p = Some(self)
while not(p.is_empty()) || not(s.is_empty()) {
while not(p.is_empty()) {
s.push(p)
p = p.unwrap().left
}
if not(s.is_empty()) {
p = s.unsafe_pop()
f(p.unwrap().value)
p = p.unwrap().right
}
}
}

///|
/// Iterates the set with index.
pub fn eachi[V](self : T[V], f : (Int, V) -> Unit) -> Unit {
let mut i = 0
fn dfs(root : Node[V]?) -> Unit {
match root {
Some(root) => {
dfs(root.left)
f(i, root.value)
i = i + 1
f(root.value)
dfs(root.right)
}
None => ()
Expand All @@ -365,6 +337,16 @@ pub fn eachi[V](self : T[V], f : (Int, V) -> Unit) -> Unit {
dfs(self.root)
}

///|
/// Iterates the set with index.
pub fn eachi[V](self : T[V], f : (Int, V) -> Unit) -> Unit {
let mut i = 0
self.each(fn(v) {
f(i, v)
i = i + 1
})
}

///|
/// Converts the set to an array.
pub fn to_array[V](self : T[V]) -> Array[V] {
Expand Down
Loading