aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRyan M. Moore <rmm1047@gmail.com>2024-05-15 14:59:51 -0400
committerLouis Pilfold <louis@lpil.uk>2024-05-17 23:15:59 +0100
commit43e32953ba28a892fe5063d60b253c2c7282cbaf (patch)
treefd083dee875f6546a9e036ed4c9d64a46dc7c8e2
parent1d60b1842d4a27dc7403ae9c440c6b6f2264c255 (diff)
downloadgleam_stdlib-43e32953ba28a892fe5063d60b253c2c7282cbaf.tar.gz
gleam_stdlib-43e32953ba28a892fe5063d60b253c2c7282cbaf.zip
Add `dict.each`
-rw-r--r--CHANGELOG.md1
-rw-r--r--src/gleam/dict.gleam29
-rw-r--r--test/gleam/dict_test.gleam12
3 files changed, 42 insertions, 0 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f1348f6..b3851ca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@
- The `sort` function of the `list` module has been optimised in case it's
working on an already sorted list.
+- The `dict` module gains the `each` function.
- The `list` module gains the `wrap` function.
- The `iterator` module gains the `find_map` function.
- Fixed `string.inspect` not formatting the `\f` form feed control character
diff --git a/src/gleam/dict.gleam b/src/gleam/dict.gleam
index 8b459ec..6013f32 100644
--- a/src/gleam/dict.gleam
+++ b/src/gleam/dict.gleam
@@ -497,3 +497,32 @@ pub fn fold(
|> to_list
|> do_fold(initial, fun)
}
+
+/// Calls a function for each key and value in a dict, discarding the return
+/// value.
+///
+/// Useful for producing a side effect for every item of a dict.
+///
+/// ```gleam
+/// import gleam/io
+///
+/// let dict = from_list([#("a", "apple"), #("b", "banana"), #("c", "cherry")])
+///
+/// each(dict, fn(key, value) {
+/// io.println(key <> " => " <> value)
+/// })
+/// // -> Nil
+/// // a => apple
+/// // b => banana
+/// // c => cherry
+/// ```
+///
+/// The order of elements in the iteration is an implementation detail that
+/// should not be relied upon.
+///
+pub fn each(dict: Dict(k, v), fun: fn(k, v) -> b) -> Nil {
+ fold(dict, Nil, fn(nil, k, v) {
+ fun(k, v)
+ nil
+ })
+}
diff --git a/test/gleam/dict_test.gleam b/test/gleam/dict_test.gleam
index 3d77228..ca77bb9 100644
--- a/test/gleam/dict_test.gleam
+++ b/test/gleam/dict_test.gleam
@@ -220,6 +220,18 @@ pub fn fold_test() {
|> should.equal(0)
}
+pub fn each_test() {
+ let dict = dict.from_list([#("a", 1), #("b", 2), #("c", 3), #("d", 4)])
+
+ dict.each(dict, fn(k, v) {
+ let assert True = case k, v {
+ "a", 1 | "b", 2 | "c", 3 | "d", 4 -> True
+ _, _ -> False
+ }
+ })
+ |> should.equal(Nil)
+}
+
fn range(start, end, a) {
case end - start {
n if n < 1 -> a