From 926a0c57cb27bc6a8ee3d4f9fd73fe430ddcf787 Mon Sep 17 00:00:00 2001 From: Marcin Puc <5671049+tranzystorek-io@users.noreply.github.com> Date: Mon, 8 Mar 2021 23:50:29 +0100 Subject: Add iterator.index (#169) --- src/gleam/iterator.gleam | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'src') 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 -- cgit v1.2.3