blob: 4e184bd32cb87ea8313e258f410cdab1c06055f9 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
import gleam/iterator.{Iterator, Next} as iter
pub fn length(iterator: Iterator(a)) -> Int {
iterator
|> iter.fold(from: 0, with: fn(c, _) { c + 1 })
}
pub fn count(iterator: Iterator(a), satisfying predicate: fn(a) -> Bool) -> Int {
iterator
|> iter.filter(for: predicate)
|> length
}
pub fn filter_map(
iterator: Iterator(a),
with mapper: fn(a) -> Result(b, c),
) -> Iterator(b) {
iterator
|> iter.flat_map(with: fn(elem) {
case mapper(elem) {
Ok(new) -> iter.single(new)
Error(_) -> iter.empty()
}
})
}
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)) },
)
}
|