diff --git a/src/gleamy/set.gleam b/src/gleamy/set.gleam index c6cbfd9..0d395ec 100644 --- a/src/gleamy/set.gleam +++ b/src/gleamy/set.gleam @@ -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 { diff --git a/test/set_test.gleam b/test/set_test.gleam index 8182714..043f39b 100644 --- a/test/set_test.gleam +++ b/test/set_test.gleam @@ -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) +}