From e1dce822e1ff14664a30b429b5e2e2cbf3748221 Mon Sep 17 00:00:00 2001 From: drew Date: Tue, 3 Nov 2020 07:22:37 -0600 Subject: Add `step` eliminator for iterators The `step` function allows eager access to the first item in the iterator, but does not force the rest of the iterator. --- src/gleam/iterator.gleam | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'src') diff --git a/src/gleam/iterator.gleam b/src/gleam/iterator.gleam index bfc8455..e75b0a7 100644 --- a/src/gleam/iterator.gleam +++ b/src/gleam/iterator.gleam @@ -168,6 +168,34 @@ pub fn to_list(iterator: Iterator(element)) -> List(element) { |> list.reverse } +/// Eagerly access the first value of an interator, returning a `Next` +/// that contains the first value and the rest of the iterator. +/// +/// If called on an empty iterator, `Done` is returned. +/// +/// ## Examples +/// +/// > assert Next(head, tail) = +/// > [1, 2, 3, 4] +/// > |> from_list +/// > |> step +/// > head +/// 1 +/// > tail |> to_list +/// [2, 3, 4] +/// +/// > [] +/// > |> from_list +/// > |> step +/// Done +/// +pub fn step(iterator: Iterator(e)) -> Step(e, Iterator(e)) { + case iterator.continuation() { + Stop -> Done + Continue(e, a) -> Next(e, Iterator(a)) + } +} + fn do_take( continuation: fn() -> Action(e), desired: Int, -- cgit v1.2.3