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

add compare for sorted_set #1470

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
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
35 changes: 34 additions & 1 deletion sorted_set/set.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -299,9 +299,42 @@ pub fn disjoint[V : Compare](self : T[V], src : T[V]) -> Bool {

// General collection operations

///|
pub impl[V : Compare] Compare for T[V] with compare(self : T[V], other : T[V]) -> Int {
let rhs = other.to_array()
let mut i = 0
let mut result = 0
fn dfs(root : Node[V]?) -> Unit {
match root {
Some(root) => {
if i >= rhs.length() {
return
}
dfs(root.left)
let cmp = root.value.compare(rhs[i])
if cmp != 0 {
result = cmp
return
}
i = i + 1
dfs(root.right)
}
None => ()
}
()
}

dfs(self.root)
if result != 0 {
result
} else {
(self.size - other.size).to_int()
}
Comment on lines +327 to +332
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here we do dfs first and then compare length, which is weird.

}

///|
pub fn op_equal[V : Compare](self : T[V], other : T[V]) -> Bool {
self.to_array() == other.to_array()
self.compare(other) == 0
}

///|
Expand Down
17 changes: 17 additions & 0 deletions sorted_set/set_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,20 @@ test "range" {
let result = set.range(2, 4)
inspect!(result, content="[2, 3, 4]")
}

test "compare" {
let xs = [1, 2, 3]
let ys = [1, 2]
let xs = @sorted_set.of(xs)
let ys = @sorted_set.of(ys)
inspect!(xs < ys, content="false")
inspect!(xs > ys, content="true")
inspect!(xs == ys, content="false")
let xs = [2, 7, 4]
let ys = [1]
let xs = @sorted_set.of(xs)
let ys = @sorted_set.of(ys)
inspect!(xs < ys, content="false")
inspect!(xs > ys, content="true")
inspect!(xs == ys, content="false")
}
1 change: 1 addition & 0 deletions sorted_set/sorted_set.mbti
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ impl T {
intersection[V : Compare](Self[V], Self[V]) -> Self[V]
is_empty[V : Compare](Self[V]) -> Bool
iter[V](Self[V]) -> Iter[V]
compare[V : Compare](Self[V], Self[V]) -> Int
op_equal[V : Compare](Self[V], Self[V]) -> Bool
range[V : Compare](Self[V], V, V) -> Iter[V]
remove[V : Compare](Self[V], V) -> Unit
Expand Down
Loading