Skip to content

Commit

Permalink
Add set difference function
Browse files Browse the repository at this point in the history
  • Loading branch information
dtykocki authored and lpil committed Jan 4, 2024
1 parent f88b832 commit c153d1a
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- The `set` module gains the `difference` function.

## v0.34.0 - 2023-12-17

- The `int.random` function now takes a single argument.
Expand Down
17 changes: 17 additions & 0 deletions src/gleam/set.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -260,3 +260,20 @@ pub fn intersection(
let #(larger, smaller) = order(first, second)
take(from: larger, keeping: to_list(smaller))
}

/// Creates a new set that contains members that are present in the first set
/// but not the second.
///
/// ## Examples
///
/// ```gleam
/// > difference(from_list([1, 2]), from_list([2, 3, 4])) |> to_list
/// [1]
/// ```
///
pub fn difference(
from first: Set(member),
minus second: Set(member),
) -> Set(member) {
drop(from: first, drop: to_list(second))
}
7 changes: 7 additions & 0 deletions test/gleam/set_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ pub fn fold_test() {
[1, 3, 9]
|> set.from_list
|> set.fold(from: 0, with: fn(m, a) { m + a })
|> should.equal(13)
}

pub fn filter_test() {
Expand Down Expand Up @@ -100,3 +101,9 @@ pub fn intersection_test() {
|> set.to_list
|> should.equal([2])
}

pub fn difference_test() {
set.difference(set.from_list([1, 2]), set.from_list([2, 3, 4]))
|> set.to_list
|> should.equal([1])
}

0 comments on commit c153d1a

Please sign in to comment.