aboutsummaryrefslogtreecommitdiff
path: root/aoc-2020-gleam/src/ext/iteratorx.gleam
diff options
context:
space:
mode:
Diffstat (limited to 'aoc-2020-gleam/src/ext/iteratorx.gleam')
-rw-r--r--aoc-2020-gleam/src/ext/iteratorx.gleam21
1 files changed, 17 insertions, 4 deletions
diff --git a/aoc-2020-gleam/src/ext/iteratorx.gleam b/aoc-2020-gleam/src/ext/iteratorx.gleam
index 0e59f17..6c7838d 100644
--- a/aoc-2020-gleam/src/ext/iteratorx.gleam
+++ b/aoc-2020-gleam/src/ext/iteratorx.gleam
@@ -1,3 +1,6 @@
+import gleam/int
+import gleam/result as res
+import gleam/dict.{type Dict}
import gleam/iterator.{type Iterator, Next} as iter
pub fn length(iterator: Iterator(a)) -> Int {
@@ -11,6 +14,19 @@ pub fn count(iterator: Iterator(a), satisfying predicate: fn(a) -> Bool) -> Int
|> length
}
+pub fn counts(iterator: Iterator(a)) -> Dict(a, Int) {
+ iterator
+ |> iter.fold(from: dict.new(), with: fn(acc, value) {
+ acc
+ |> dict.insert(
+ value,
+ dict.get(acc, value)
+ |> res.unwrap(or: 0)
+ |> int.add(1),
+ )
+ })
+}
+
pub fn filter_map(
iterator: Iterator(a),
with mapper: fn(a) -> Result(b, c),
@@ -25,8 +41,5 @@ pub fn filter_map(
}
pub fn unfold_infinitely(from state: a, with fun: fn(a) -> a) -> Iterator(a) {
- iter.unfold(
- from: state,
- with: fn(s) { Next(element: s, accumulator: fun(s)) },
- )
+ iter.unfold(from: state, with: fn(s) { Next(element: s, accumulator: fun(s)) })
}