aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorMarcin Puc <5671049+tranzystorek-io@users.noreply.github.com>2021-03-08 23:50:29 +0100
committerGitHub <noreply@github.com>2021-03-08 23:50:29 +0100
commit926a0c57cb27bc6a8ee3d4f9fd73fe430ddcf787 (patch)
treee946e869650654689bf65b9c7c1e07d2419b3907 /src
parentd86237c4c07426d5f5df8fefd8f3e046b35ef4a4 (diff)
downloadgleam_stdlib-926a0c57cb27bc6a8ee3d4f9fd73fe430ddcf787.tar.gz
gleam_stdlib-926a0c57cb27bc6a8ee3d4f9fd73fe430ddcf787.zip
Add iterator.index (#169)
Diffstat (limited to 'src')
-rw-r--r--src/gleam/iterator.gleam26
1 files changed, 26 insertions, 0 deletions
diff --git a/src/gleam/iterator.gleam b/src/gleam/iterator.gleam
index f441859..9146833 100644
--- a/src/gleam/iterator.gleam
+++ b/src/gleam/iterator.gleam
@@ -495,6 +495,32 @@ pub fn find(
}
}
+fn do_index(
+ continuation: fn() -> Action(element),
+ next: Int,
+) -> fn() -> Action(tuple(Int, element)) {
+ fn() {
+ case continuation() {
+ Continue(e, continuation) ->
+ Continue(tuple(next, e), do_index(continuation, next + 1))
+ Stop -> Stop
+ }
+ }
+}
+
+/// Wraps values yielded from an iterator with indices, starting from 0.
+///
+/// ## Examples
+///
+/// > from_list(["a", "b", "c"]) |> index |> to_list
+/// [tuple(0, "a"), tuple(1, "b"), tuple(2, "c")]
+///
+pub fn index(over iterator: Iterator(element)) -> Iterator(tuple(Int, element)) {
+ iterator.continuation
+ |> do_index(0)
+ |> Iterator
+}
+
/// Creates an iterator that inifinitely applies a function to a value.
///
/// ## Examples