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 set.each function #718

Merged
merged 2 commits into from
Oct 30, 2024
Merged
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
- The `list.concat` function has been deprecated in favour of `list.flatten`.
- The handling of float exponentials and signs in the `float.to_string` and
`string.inspect` functions have been improved on JavaScript.
- The `set` module gains the `each` function.

## v0.40.0 - 2024-08-19

Expand Down
25 changes: 25 additions & 0 deletions src/gleam/set.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -380,3 +380,28 @@ pub fn symmetric_difference(
minus: intersection(of: first, and: second),
)
}

/// Calls a function for each member in a set, discarding the return
/// value.
///
/// Useful for producing a side effect for every item of a set.
///
/// ```gleam
/// let set = from_list(["apple", "banana", "cherry"])
///
/// each(set, io.println)
/// // -> Nil
/// // apple
/// // banana
/// // cherry
/// ```
///
/// The order of elements in the iteration is an implementation detail that
/// should not be relied upon.
///
pub fn each(set: Set(member), fun: fn(member) -> a) -> Nil {
fold(set, Nil, fn(nil, member) {
fun(member)
nil
})
}
12 changes: 12 additions & 0 deletions test/gleam/set_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -158,3 +158,15 @@ pub fn symmetric_difference_test() {
set.symmetric_difference(set.from_list([1, 2, 3]), set.from_list([3, 4]))
|> should.equal(set.from_list([1, 2, 4]))
}

pub fn each_test() {
[1, 2, 3]
|> set.from_list
|> set.each(fn(member) {
case member {
1 | 2 | 3 -> Nil
_ -> panic as "unexpected value"
}
})
|> should.equal(Nil)
}