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): iter::adapters::Map #6949

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
231 changes: 231 additions & 0 deletions corelib/src/iter.cairo
Original file line number Diff line number Diff line change
@@ -1,2 +1,233 @@
//! Composable external iteration.
//!
//! If you've found yourself with a collection of some kind, and needed to
//! perform an operation on the elements of said collection, you'll quickly run
//! into 'iterators'. Iterators are heavily used in idiomatic code, so
//! it's worth becoming familiar with them.
//!
//! Before explaining more, let's talk about how this module is structured:
//!
//! # Organization
//!
//! This module is largely organized by type:
//!
//! * [Traits] are the core portion: these traits define what kind of iterators
//! exist and what you can do with them. The methods of these traits are worth
//! putting some extra study time into.
//! * [Functions] provide some helpful ways to create some basic iterators.
//! * [Structs] are often the return types of the various methods on this
//! module's traits. You'll usually want to look at the method that creates
//! the `struct`, rather than the `struct` itself. For more detail about why,
//! see '[Implementing Iterator](#implementing-iterator)'.
//!
//! [Traits]: #traits
//! [Functions]: #functions
//! [Structs]: #structs
//!
//! That's it! Let's dig into iterators.
//!
//! # Iterator
//!
//! The heart and soul of this module is the [`Iterator`] trait. The core of
//! [`Iterator`] looks like this:
//!
//! ```
//! trait Iterator {
//! type Item;
//! fn next(ref self) -> Option<Self::Item>;
//! }
//! ```
//!
//! An iterator has a method, [`next`], which when called, returns an
//! <code>[Option]\<Item></code>. Calling [`next`] will return [`Option::Some(Item)`] as long as
//! there are elements, and once they've all been exhausted, will return `Option::None` to
//! indicate that iteration is finished.
//!
//! [`Iterator`]'s full definition includes a number of other methods as well,
//! but they are default methods, built on top of [`next`], and so you get
//! them for free.
//!
//! Iterators are also composable, and it's common to chain them together to do
//! more complex forms of processing. See the [Adapters](#adapters) section
//! below for more details.
//!
//! [`Option::Some(Item)`]: Option::Some
//! [`next`]: Iterator::next
//!
//! # Forms of iteration
//!
//! There is currently only one common method which can create iterators from a collection:
//!
//! * `into_iter()`, which iterates over `T`.
//!
//! # Implementing Iterator
//!
//! Creating an iterator of your own involves two steps: creating a `struct` to
//! hold the iterator's state, and then implementing [`Iterator`] for that `struct`.
//! This is why there are so many `struct`s in this module: there is one for
//! each iterator and iterator adapter.
//!
//! Let's make an iterator named `Counter` which counts from `1` to `5`:
//!
//! ```
//! // First, the struct:
//!
//! /// An iterator which counts from one to five
//! #[derive(Drop)]
//! struct Counter {
//! count: usize,
//! }
//!
//! // we want our count to start at one, so let's add a new() method to help.
//! // This isn't strictly necessary, but is convenient. Note that we start
//! // `count` at zero, we'll see why in `next()`'s implementation below.
//! #[generate_trait]
//! impl CounterImpl of CounterTrait {
//! fn new() -> Counter {
//! Counter { count: 0 }
//! }
//! }
//!
//! // Then, we implement `Iterator` for our `Counter`:
//!
//! impl CounterIter of core::iter::Iterator<Counter> {
//! // we will be counting with usize
//! type Item = usize;
//!
//! // next() is the only required method
//! fn next(ref self: Counter) -> Option<Self::Item> {
//! // Increment our count. This is why we started at zero.
//! self.count += 1;
//!
//! // Check to see if we've finished counting or not.
//! if self.count < 6 {
//! Option::Some(self.count)
//! } else {
//! Option::None
//! }
//! }
//! }
//!
//! // And now we can use it!
//!
//! let mut counter = CounterTrait::new();
//!
//! assert!(counter.next() == Option::Some(1));
//! assert!(counter.next() == Option::Some(2));
//! assert!(counter.next() == Option::Some(3));
//! assert!(counter.next() == Option::Some(4));
//! assert!(counter.next() == Option::Some(5));
//! assert!(counter.next() == Option::None);
//! ```
//!
//! Calling [`next`] this way gets repetitive. Cairo has a construct which can
//! call [`next`] on your iterator, until it reaches `Option::None`. Let's go over that
//! next.
//!
//! # `for` loops and `IntoIterator`
//!
//! Cairo's `for` loop syntax is actually sugar for iterators. Here's a basic
//! example of `for`:
//!
//! ```
//! let values = array![1, 2, 3, 4, 5];
//!
//! for x in values {
//! println!("{x}");
//! }
//! ```
//!
//! This will print the numbers one through five, each on their own line. But
//! you'll notice something here: we never called anything on our array to
//! produce an iterator. What gives?
//!
//! There's a trait in the core library for converting something into an
//! iterator: [`IntoIterator`]. This trait has one method, [`into_iter`],
//! which converts the thing implementing [`IntoIterator`] into an iterator.
//! Let's take a look at that `for` loop again, and what the compiler converts
//! it into:
//!
//! [`into_iter`]: core::iter::IntoIterator::into_iter
//!
//! ```
//! let values = array![1, 2, 3, 4, 5];
//!
//! for x in values {
//! println!("{x}");
//! }
//! ```
//!
//! Cairo de-sugars this into:
//!
//! ```
//! let values = array![1, 2, 3, 4, 5];
//! {
//! let mut iter = IntoIterator::into_iter(values);
//! let result = loop {
//! let mut next = 0;
//! match iter.next() {
//! Option::Some(val) => next = val,
//! Option::None => {
//! break;
//! },
//! };
//! let x = next;
//! let () = { println!("{x}"); };
//! };
//! result
//! }
//! ```
//!
//! First, we call `into_iter()` on the value. Then, we match on the iterator
//! that returns, calling [`next`] over and over until we see a `Option::None`. At
//! that point, we `break` out of the loop, and we're done iterating.
//!
//! There's one more subtle bit here: the core library contains an
//! interesting implementation of [`IntoIterator`]:
//!
//! ```ignore (only-for-syntax-highlight)
//! impl IteratorIntoIterator<T, +Iterator<T>> of IntoIterator<T>
//! ```
//!
//! In other words, all [`Iterator`]s implement [`IntoIterator`], by just
//! returning themselves. This means two things:
//!
//! 1. If you're writing an [`Iterator`], you can use it with a `for` loop.
//! 2. If you're creating a collection, implementing [`IntoIterator`] for it
//! will allow your collection to be used with the `for` loop.
//!
//! # Adapters
//!
//! Functions which take an [`Iterator`] and return another [`Iterator`] are
//! 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.
//!
//! [`map`]: Iterator::map
//!
//! # Laziness
//!
//! Iterators (and iterator [adapters](#adapters)) are *lazy*. This means that
//! just creating an iterator doesn't _do_ a whole lot. Nothing really happens
//! until you call [`next`]. This is sometimes a source of confusion when
//! creating an iterator solely for its side effects. For example, the [`map`]
//! method calls a closure on each element it iterates over:
//!
//! ```
//! let v = array![1, 2, 3, 4, 5];
//! let _ = v.into_iter().map(|x| println!("{x}"));
//! ```
//!
//! This will not print any values, as we only created an iterator, rather than
//! using it. The compiler will warn us about this kind of behavior:
//!
//! ```text
//! Unhandled `#[must_use]` type
//! ```
//!
//! [`map`]: Iterator::map
mod adapters;
mod traits;
pub use traits::{IntoIterator, Iterator};
4 changes: 4 additions & 0 deletions corelib/src/iter/adapters.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
mod map;
pub use map::Map;
#[allow(unused_imports)]
pub(crate) use map::mapped_iterator;
32 changes: 32 additions & 0 deletions corelib/src/iter/adapters/map.cairo
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/// An iterator that maps the values of `iter` with `f`.
///
/// This `struct` is created by the [`map`] method on [`Iterator`]. See its
/// documentation for more.
///
/// [`map`]: Iterator::map
/// [`Iterator`]: core::iter::Iterator
///
#[must_use]
#[derive(Drop, Clone)]
pub struct Map<I, F> {
iter: I,
f: F,
}

pub fn mapped_iterator<I, F>(iter: I, f: F) -> Map<I, F> {
Map { iter, f }
}

impl MapIterator<
I,
F,
impl TIter: Iterator<I>,
impl func: core::ops::Fn<F, (TIter::Item,)>,
+Destruct<I>,
+Destruct<F>,
> of Iterator<Map<I, F>> {
type Item = func::Output;
fn next(ref self: Map<I, F>) -> Option<func::Output> {
self.iter.next().map(@self.f)
}
}
94 changes: 92 additions & 2 deletions corelib/src/iter/traits/iterator.cairo
Original file line number Diff line number Diff line change
@@ -1,8 +1,98 @@
/// An iterator over a collection of values.
use crate::iter::adapters::{Map, mapped_iterator};

/// A trait for dealing with iterators.
///
/// This is the main iterator trait. For more about the concept of iterators
/// generally, please see the [module-level documentation]. In particular, you
/// may want to know how to [implement `Iterator`][impl].
///
/// [module-level documentation]: crate::iter
/// [impl]: crate::iter#implementing-iterator
pub trait Iterator<T> {
/// The type of the elements being iterated over.
type Item;

/// Advance the iterator and return the next value.

/// Advances the iterator and returns the next value.
///
/// Returns [`Option::None`] when iteration is finished.
///
/// [`Option::Some(Item)`]: Option::Some
///
/// # Examples
///
/// ```
/// let a = array![1, 2, 3];
///
/// let mut iter = a.into_iter();
///
/// // A call to next() returns the next value...
/// assert!(Option::Some(1) == iter.next());
/// assert!(Option::Some(2) == iter.next());
/// assert!(Option::Some(3) == iter.next());
///
/// // ... and then None once it's over.
/// assert!(Option::None == iter.next());
///
/// // More calls may or may not return `Option::None`. Here, they always will.
/// assert!(Option::None == iter.next());
/// assert!(Option::None == iter.next());
/// ```
fn next(ref self: T) -> Option<Self::Item>;


/// Takes a closure and creates an iterator which calls that closure on each
/// element.
///
/// `map()` transforms one iterator into another, by means of its argument:
/// something that implements [`FnOnce`]. It produces a new iterator which
/// calls this closure on each element of the original iterator.
///
/// If you are good at thinking in types, you can think of `map()` like this:
/// If you have an iterator that gives you elements of some type `A`, and
/// you want an iterator of some other type `B`, you can use `map()`,
/// passing a closure that takes an `A` and returns a `B`.
///
/// `map()` is conceptually similar to a `for` loop. However, as `map()` is
/// lazy, it is best used when you're already working with other iterators.
/// If you're doing some sort of looping for a side effect, it's considered
/// more idiomatic to use `for` than `map()`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = array![1, 2, 3];
///
/// let mut iter = a.into_iter().map(|x| 2 * x);
///
/// assert!(iter.next() == Option::Some(2));
/// assert!(iter.next() == Option::Some(4));
/// assert!(iter.next() == Option::Some(6));
/// assert!(iter.next() == Option::None);
/// ```
///
/// If you're doing some sort of side effect, prefer `for` to `map()`:
///
/// ```
/// // don't do this:
/// let _ = (0..5_usize).into_iter().map(|x| println!("{x}"));
///
/// // it won't even execute, as it is lazy. Cairo will warn you about this if not specifically
/// ignored, as is done here.
///
/// // Instead, use for:
/// for x in 0..5_usize {
/// println!("{x}");
/// }
/// ```
#[inline]
fn map<
B, F, impl TIter: Self, +core::ops::Fn<F, (TIter::Item,)>[Output: B], +Drop<T>, +Drop<F>,
>(
self: T, f: F,
) -> Map<T, F> {
mapped_iterator(self, f)
}
}
6 changes: 3 additions & 3 deletions corelib/src/option.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ pub trait OptionTrait<T> {
/////////////////////////////////////////////////////////////////////////

/// Maps an `Option<T>` to `Option<U>` by applying a function to a contained value (if `Some`)
/// or returns `None` (if `None`).
/// or returns `Option::None` (if `None`).
///
/// # Examples
///
Expand All @@ -526,7 +526,7 @@ pub trait OptionTrait<T> {
/// let x: Option<ByteArray> = Option::None;
/// assert!(x.map(|s: ByteArray| s.len()) == Option::None);
/// ```
fn map<U, F, +Drop<F>, +core::ops::FnOnce<F, (T,)>[Output: U]>(
fn map<U, F, +Destruct<F>, +core::ops::FnOnce<F, (T,)>[Output: U]>(
self: Option<T>, f: F,
) -> Option<U>;

Expand Down Expand Up @@ -722,7 +722,7 @@ pub impl OptionTraitImpl<T> of OptionTrait<T> {
}

#[inline]
fn map<U, F, +Drop<F>, +core::ops::FnOnce<F, (T,)>[Output: U]>(
fn map<U, F, +Destruct<F>, +core::ops::FnOnce<F, (T,)>[Output: U]>(
self: Option<T>, f: F,
) -> Option<U> {
match self {
Expand Down
Loading
Loading