diff options
author | Marcin Puc <marcin.e.puc@gmail.com> | 2021-09-25 16:01:19 +0200 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2021-10-12 20:54:39 +0100 |
commit | 6aa64ddfd27f90fc6299a5036e17780210c46ccb (patch) | |
tree | d7fe91af48fdae8fddd8c7da0b6ebfc19d843bda /src | |
parent | 31960280846b7c76c274c58f0b9c4b82924580ab (diff) | |
download | gleam_stdlib-6aa64ddfd27f90fc6299a5036e17780210c46ccb.tar.gz gleam_stdlib-6aa64ddfd27f90fc6299a5036e17780210c46ccb.zip |
Add iterator.at
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/iterator.gleam | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/src/gleam/iterator.gleam b/src/gleam/iterator.gleam index 05bf331..42ef635 100644 --- a/src/gleam/iterator.gleam +++ b/src/gleam/iterator.gleam @@ -1113,3 +1113,45 @@ pub fn try_fold( iterator.continuation |> do_try_fold(f, initial) } + +fn try_yield(continuation: fn() -> Action(e)) -> Result(e, Nil) { + case continuation() { + Stop -> Error(Nil) + Continue(e, _) -> Ok(e) + } +} + +fn do_at(continuation: fn() -> Action(e), index: Int) -> Result(e, Nil) { + case index > 0 { + False -> try_yield(continuation) + True -> + case continuation() { + Stop -> Error(Nil) + Continue(_, next) -> do_at(next, index - 1) + } + } +} + +/// Returns nth element yielded by the given iterator, where 0 means the first element. +/// +/// If there are not enough elements in the iterator, `Error(Nil)` is returned. +/// +/// For any `index` less than 0 this function behaves as if it was set to 0. +/// +/// ## Examples +/// +/// ``` +/// > from_list([1, 2, 3, 4]) |> at(2) +/// Ok(3) +/// +/// > from_list([1, 2, 3, 4]) |> at(4) +/// Error(Nil) +/// +/// > empty() |> iterator.at(0) +/// Error(Nil) +/// ``` +/// +pub fn at(in iterator: Iterator(e), get index: Int) -> Result(e, Nil) { + iterator.continuation + |> do_at(index) +} |