From 1f693fae46e607d6ba811f7d01a9b903f0762420 Mon Sep 17 00:00:00 2001 From: Marcin Puc Date: Tue, 9 Mar 2021 14:37:11 +0100 Subject: Add iterator.zip --- src/gleam/iterator.gleam | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'src') diff --git a/src/gleam/iterator.gleam b/src/gleam/iterator.gleam index 9146833..010d82a 100644 --- a/src/gleam/iterator.gleam +++ b/src/gleam/iterator.gleam @@ -534,3 +534,33 @@ pub fn iterate( ) -> Iterator(element) { unfold(initial, fn(element) { Next(element, f(element)) }) } + +fn do_zip( + left: fn() -> Action(a), + right: fn() -> Action(b), +) -> fn() -> Action(tuple(a, b)) { + fn() { + case left() { + Stop -> Stop + Continue(el_left, next_left) -> + case right() { + Stop -> Stop + Continue(el_right, next_right) -> + Continue(tuple(el_left, el_right), do_zip(next_left, next_right)) + } + } + } +} + +/// Zips two iterators together, emitting values from both +/// until the shorter one runs out. +/// +/// ## Examples +/// +/// > from_list(["a", "b", "c"]) |> zip(range(20, 30)) |> to_list +/// [tuple("a", 20), tuple("b", 21), tuple("c", 22)] +/// +pub fn zip(left: Iterator(a), right: Iterator(b)) -> Iterator(tuple(a, b)) { + do_zip(left.continuation, right.continuation) + |> Iterator +} -- cgit v1.2.3