Skip to content

Commit

Permalink
set subtraction
Browse files Browse the repository at this point in the history
  • Loading branch information
schurhammer committed May 7, 2024
1 parent a0a0f83 commit ccdcc81
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/gleamy/set.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ pub fn union(of first: Set(a), and second: Set(a)) -> Set(a) {
tree.fold(first, second, fn(a, i) { tree.insert(a, i) })
}

/// Creates a new set containing the elements of the first set except for elements
/// that are also in the second set.
pub fn difference(from set: Set(a), remove removal: Set(a)) -> Set(a) {
tree.fold(removal, set, fn(set, i) { tree.delete(set, i) })
}

/// Returns the number of elements in the set.
/// Time complexity: O(n)
pub fn count(set: Set(a)) -> Int {
Expand Down
39 changes: 39 additions & 0 deletions test/set_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -262,3 +262,42 @@ pub fn insert_and_remove_test() {
|> set.to_list()
|> should.equal([1, 5, 7, 8, 11, 12, 13])
}

pub fn difference_test() {
let set = set.new(int.compare)
let remove_set = set.new(int.compare)

let from_set =
set
|> set.insert(1)
|> set.insert(2)
|> set.insert(3)
|> set.insert(4)

let remove_set =
remove_set
|> set.insert(2)
|> set.insert(3)

let result_set = set.difference(from_set, remove_set)

result_set
|> set.count()
|> should.equal(2)

result_set
|> set.contains(1)
|> should.equal(True)

result_set
|> set.contains(2)
|> should.equal(False)

result_set
|> set.contains(3)
|> should.equal(False)

result_set
|> set.contains(4)
|> should.equal(True)
}

0 comments on commit ccdcc81

Please sign in to comment.