aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/gleam/iterator.gleam34
-rw-r--r--test/gleam/iterator_test.gleam10
2 files changed, 28 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
}
diff --git a/test/gleam/iterator_test.gleam b/test/gleam/iterator_test.gleam
index e7f749a..5601672 100644
--- a/test/gleam/iterator_test.gleam
+++ b/test/gleam/iterator_test.gleam
@@ -482,6 +482,16 @@ pub fn try_fold_test() {
|> should.equal(Error("tried to add an odd number"))
}
+pub fn first_test() {
+ iterator.from_list([1, 2, 3])
+ |> iterator.first
+ |> should.equal(Ok(1))
+
+ iterator.empty()
+ |> iterator.first
+ |> should.equal(Error(Nil))
+}
+
pub fn at_test() {
iterator.from_list([1, 2, 3, 4])
|> iterator.at(2)