Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(corelib): core::iter::zip #7050

Merged
merged 8 commits into from
Jan 19, 2025
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions corelib/src/iter.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,11 @@
//! often called 'iterator adapters', as they're a form of the 'adapter
//! pattern'.
//!
//! The only adapter for now is [`map`].
//! For more, see the [`map`] documentation.
//! Common iterators adapters include [`map`], [`enumerate`] and [`zip`].
//!
//! [`map`]: Iterator::map
//! [`enumerate`]: Iterator::enumerate
//! [`zip`]: Iterator::zip
//!
//! # Laziness
//!
Expand Down
5 changes: 5 additions & 0 deletions corelib/src/iter/adapters.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,8 @@ mod enumerate;
pub use enumerate::Enumerate;
#[allow(unused_imports)]
pub(crate) use enumerate::enumerated_iterator;

mod zip;
pub use zip::Zip;
#[allow(unused_imports)]
pub(crate) use zip::zipped_iterator;
37 changes: 37 additions & 0 deletions corelib/src/iter/adapters/zip.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/// An iterator that iterates two other iterators simultaneously.
///
/// This `struct` is created by [`zip`] or [`Iterator::zip`].
/// See their documentation for more.
///
/// [`Iterator::zip`]: core::iter::Iterator::zip
#[derive(Drop, Clone)]
#[must_use]
pub struct Zip<A, B> {
a: A,
b: B,
}

#[inline]
pub fn zipped_iterator<A, B>(a: A, b: B) -> Zip<A, B> {
Zip { a, b }
}

impl ZipIterator<
A,
B,
impl IterA: Iterator<A>,
impl IterB: Iterator<B>,
+Destruct<A>,
+Destruct<B>,
+Destruct<IterA::Item>,
+Destruct<IterB::Item>,
> of Iterator<Zip<A, B>> {
type Item = (IterA::Item, IterB::Item);

#[inline]
fn next(ref self: Zip<A, B>) -> Option<Self::Item> {
let a = self.a.next()?;
let b = self.b.next()?;
Option::Some((a, b))
}
}
53 changes: 52 additions & 1 deletion corelib/src/iter/traits/iterator.cairo
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use crate::iter::adapters::{Enumerate, Map, enumerated_iterator, mapped_iterator};
use crate::iter::adapters::{
Enumerate, Map, Zip, enumerated_iterator, mapped_iterator, zipped_iterator,
};

/// A trait for dealing with iterators.
///
Expand Down Expand Up @@ -128,4 +130,53 @@ pub trait Iterator<T> {
fn enumerate(self: T) -> Enumerate<T> {
enumerated_iterator(self)
}

/// 'Zips up' two iterators into a single iterator of pairs.
///
/// `zip()` returns a new iterator that will iterate over two other
/// iterators, returning a tuple where the first element comes from the
/// first iterator, and the second element comes from the second iterator.
///
/// In other words, it zips two iterators together, into a single one.
///
/// If either iterator returns [`Option::None`], [`next`] from the zipped iterator
/// will return [`Option::None`].
/// If the zipped iterator has no more elements to return then each further attempt to advance
/// it will first try to advance the first iterator at most one time and if it still yielded an
/// item try to advance the second iterator at most one time.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let mut iter = array![1, 2, 3].into_iter().zip(array![4, 5, 6].into_iter());
///
/// assert_eq!(iter.next(), Option::Some((1, 4)));
/// assert_eq!(iter.next(), Option::Some((2, 5)));
/// assert_eq!(iter.next(), Option::Some((3, 6)));
/// assert_eq!(iter.next(), Option::None);
/// ```
///
/// Since the argument to `zip()` uses [`IntoIterator`], we can pass
/// anything that can be converted into an [`Iterator`], not just an
/// [`Iterator`] itself. For example:
///
/// ```
/// let mut iter = array![1, 2, 3].into_iter().zip(array![4, 5, 6]);
///
/// assert_eq!(iter.next(), Option::Some((1, 4)));
/// assert_eq!(iter.next(), Option::Some((2, 5)));
/// assert_eq!(iter.next(), Option::Some((3, 6)));
/// assert_eq!(iter.next(), Option::None);
/// ``
///
/// [`enumerate`]: Iterator::enumerate
/// [`next`]: Iterator::next
#[inline]
fn zip<U, impl UIntoIter: IntoIterator<U>, +Destruct<T>>(
self: T, other: U,
) -> Zip<T, UIntoIter::IntoIter> {
zipped_iterator(self, other.into_iter())
}
}
18 changes: 18 additions & 0 deletions corelib/src/test/iter_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,21 @@ fn test_iterator_enumerate() {
assert_eq!(iter.next(), Option::Some((2, 'c')));
assert_eq!(iter.next(), Option::None);
}

#[test]
fn test_iterator_zip() {
let mut iter = array![1, 2, 3].into_iter().zip(array![4, 5, 6]);

assert_eq!(iter.next(), Option::Some((1, 4)));
assert_eq!(iter.next(), Option::Some((2, 5)));
assert_eq!(iter.next(), Option::Some((3, 6)));
assert_eq!(iter.next(), Option::None);

// Nested zips
let mut iter = array![1, 2, 3].into_iter().zip(array![4, 5, 6]).zip(array![7, 8, 9]);

assert_eq!(iter.next(), Option::Some(((1, 4), 7)));
assert_eq!(iter.next(), Option::Some(((2, 5), 8)));
assert_eq!(iter.next(), Option::Some(((3, 6), 9)));
assert_eq!(iter.next(), Option::None);
}
Loading