aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJulia Pitts <julia.pitts@outlook.com>2024-06-16 15:21:41 -0700
committerLouis Pilfold <louis@lpil.uk>2024-06-18 13:03:23 +0100
commit7be3f6d4138ae51b79f61699c85b96a4bf7d25bc (patch)
treedcefb1915c963541f2b844cc06fabfaeb2951421
parentc42b9ad21f8933a5c4b04471fc3bc32ca70e014f (diff)
downloadgleam_stdlib-7be3f6d4138ae51b79f61699c85b96a4bf7d25bc.tar.gz
gleam_stdlib-7be3f6d4138ae51b79f61699c85b96a4bf7d25bc.zip
Add gleam/set.{map}.
-rw-r--r--src/gleam/set.gleam15
-rw-r--r--test/gleam/set_test.gleam7
2 files changed, 22 insertions, 0 deletions
diff --git a/src/gleam/set.gleam b/src/gleam/set.gleam
index 12bfba1..9e64b07 100644
--- a/src/gleam/set.gleam
+++ b/src/gleam/set.gleam
@@ -218,6 +218,21 @@ pub fn filter(
Set(dict.filter(in: set.dict, keeping: fn(m, _) { predicate(m) }))
}
+/// Creates a new set from a given set with the result of applying the given
+/// function to each member.
+///
+/// ## Examples
+///
+/// ```gleam
+/// map(from_list([1, 2, 3, 4], fn(x) { x * 2 }))
+/// // -> [2, 4, 6, 8]
+/// ```
+pub fn map(set: Set(member), with fun: fn(member) -> mapped) -> Set(mapped) {
+ fold(over: set, from: new(), with: fn(acc, member) {
+ insert(acc, fun(member))
+ })
+}
+
/// Creates a new set from a given set with all the same entries except any
/// entry found on the given list.
///
diff --git a/test/gleam/set_test.gleam b/test/gleam/set_test.gleam
index 908fe29..46d4d13 100644
--- a/test/gleam/set_test.gleam
+++ b/test/gleam/set_test.gleam
@@ -83,6 +83,13 @@ pub fn fold_test() {
|> should.equal(13)
}
+pub fn map_test() {
+ [1, 2, 3, 4]
+ |> set.from_list
+ |> set.map(with: fn(x) { x * 2 })
+ |> should.equal(set.from_list([2, 4, 6, 8]))
+}
+
pub fn filter_test() {
[1, 4, 6, 3, 675, 44, 67]
|> set.from_list()