Skip to content

Commit

Permalink
Fix sorted map (moonbitlang#615)
Browse files Browse the repository at this point in the history
  • Loading branch information
yj-qin authored Jun 27, 2024
1 parent 77d6613 commit fdea545
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
8 changes: 6 additions & 2 deletions sorted_map/map.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,12 @@ pub fn of[K : Compare, V](entries : Array[(K, V)]) -> T[K, V] {
pub fn add[K : Compare, V](self : T[K, V], key : K, value : V) -> Unit {
let parent = loop self.root, self.root {
Some(curr), _ =>
continue if key < curr.key { curr.left } else { curr.right }, Some(curr)
if key == curr.key {
curr.value = value
return
} else {
continue if key < curr.key { curr.left } else { curr.right }, Some(curr)
}
None, parent => parent
}
let new = new_node(key, value, ~parent)
Expand All @@ -51,7 +56,6 @@ pub fn add[K : Compare, V](self : T[K, V], key : K, value : V) -> Unit {
} else {
parent.unwrap().right = Some(new)
}
new.parent = parent
self.balance(new)
self.size += 1
}
Expand Down
7 changes: 7 additions & 0 deletions sorted_map/map_test.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ test "add" {
inspect(map.size(), content="8")?
}

test "add duplicate key" {
let map = of([(3, "c"), (2, "b"), (1, "a")])
inspect(map.debug_tree(), content="([1]2,b,([0]1,a,_,_),([0]3,c,_,_))")?
map.add(1, "x")
inspect(map.debug_tree(), content="([1]2,b,([0]1,x,_,_),([0]3,c,_,_))")?
}

test "RL rotate" {
let map = new()
map.add(5, "a")
Expand Down

0 comments on commit fdea545

Please sign in to comment.