diff options
author | Ethan Pang <ethan.pang@gitstart.com> | 2023-03-01 13:08:37 +0800 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2023-03-02 18:10:24 +0000 |
commit | 0b9f858a9694a18ad90ed74f1716455a540f4436 (patch) | |
tree | 1e26d55382f3231ed69f31faeabf92fd852f0778 | |
parent | 0c3698419b9115710795984e2147643488702ea0 (diff) | |
download | gleam_stdlib-0b9f858a9694a18ad90ed74f1716455a540f4436.tar.gz gleam_stdlib-0b9f858a9694a18ad90ed74f1716455a540f4436.zip |
Add iterator.length
-rw-r--r-- | src/gleam/iterator.gleam | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/src/gleam/iterator.gleam b/src/gleam/iterator.gleam index f445eb2..318ffd1 100644 --- a/src/gleam/iterator.gleam +++ b/src/gleam/iterator.gleam @@ -1380,3 +1380,32 @@ pub fn at(in iterator: Iterator(e), get index: Int) -> Result(e, Nil) { |> drop(index) |> first } + +fn do_length(over continuation: fn() -> Action(e), with length: Int) -> Int { + case continuation() { + Stop -> length + Continue(_, next) -> do_length(next, length + 1) + } +} + +/// Counts the number of elements in the given iterator. +/// +/// This function has to traverse the entire iterator to count its elements, +/// so it runs in linear time. +/// +/// ## Examples +/// +/// ```gleam +/// > empty() |> count +/// 0 +/// ``` +/// +/// ```gleam +/// > from_list([1, 2, 3, 4]) |> count +/// 4 +/// ``` +/// +pub fn length(in iterator: Iterator(e)) -> Int { + iterator.continuation + |> do_length(0) +} |