diff options
author | Marcin Puc <marcin.e.puc@gmail.com> | 2021-09-28 23:37:52 +0200 |
---|---|---|
committer | Louis Pilfold <louis@lpil.uk> | 2021-10-12 20:54:39 +0100 |
commit | 5a71202f99c11641386f015284b73754a43e9366 (patch) | |
tree | 36e2e30e6f21432eb854d07a00716007539db988 /src | |
parent | 6aa64ddfd27f90fc6299a5036e17780210c46ccb (diff) | |
download | gleam_stdlib-5a71202f99c11641386f015284b73754a43e9366.tar.gz gleam_stdlib-5a71202f99c11641386f015284b73754a43e9366.zip |
Add iterator.first
Diffstat (limited to 'src')
-rw-r--r-- | src/gleam/iterator.gleam | 34 |
1 files changed, 18 insertions, 16 deletions
diff --git a/src/gleam/iterator.gleam b/src/gleam/iterator.gleam index 42ef635..65f5cec 100644 --- a/src/gleam/iterator.gleam +++ b/src/gleam/iterator.gleam @@ -1114,24 +1114,25 @@ pub fn try_fold( |> do_try_fold(f, initial) } -fn try_yield(continuation: fn() -> Action(e)) -> Result(e, Nil) { - case continuation() { +/// Returns the first element yielded by the given iterator, if it exists, +/// or `Error(Nil)` otherwise. +/// +/// ## Examples +/// +/// ``` +/// > from_list([1, 2, 3]) |> first +/// Ok(1) +/// +/// > empty() |> first +/// Error(Nil) +/// ``` +pub fn first(from iterator: Iterator(e)) -> Result(e, Nil) { + case iterator.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. @@ -1147,11 +1148,12 @@ fn do_at(continuation: fn() -> Action(e), index: Int) -> Result(e, Nil) { /// > from_list([1, 2, 3, 4]) |> at(4) /// Error(Nil) /// -/// > empty() |> iterator.at(0) +/// > empty() |> at(0) /// Error(Nil) /// ``` /// pub fn at(in iterator: Iterator(e), get index: Int) -> Result(e, Nil) { - iterator.continuation - |> do_at(index) + iterator + |> drop(index) + |> first } |