← core

core/iter.kur

//! The iterator protocol and iterator adapters.
// core::iter -- `Iterator`, the iteration protocol; a base producer
// (`Range`, from `range`); the adapters `map`, `filter`, `zip`,
// `enumerate`, `take`, `skip`, `take_while` and `chain`; and what drives
// them: `fold`, `count`, `any`, `all` and `find`. Every iterator has the
// adapters as methods (`it.map(f)`), and `map`, `filter`, `zip` and `fold`
// are free functions too.
//
// `Iterator[Self -> Item]`: the iterator's own type determines its item
// type, so each iterator type has one instance. Inference solves `Item` from
// `Self` (`filter(range(0, 10), |x| x % 2 == 0)` types `x` as `usize` with no
// annotation), and `it.next()` dispatches on the iterator.
//
// `next` takes the iterator in-out (`&it`): `let item = &it.next();` advances
// `it` in place. A linear iterator threads through like any other linear
// value, and every function here hands it back when done rather than
// dropping it.

use package as core;

use core::option::Option;

/// A source of items, produced one per call to `next`.
forall Self -> Item.
trait Iterator {
    /// The next item, advancing the iterator; `None` once it has run out.
    fn next(&it: Self) -> Option[Item];
}

/// The numbers from `cur` up to, not including, `end`.
exposed struct Range {
    cur: usize,
    end: usize,
}

/// The numbers from `start` up to, not including, `end`.
fn range(start: usize, end: usize) -> Range {
    Range.{ cur: start, end }
}

/// `range`: the next number, and `None` from `end` on, however often it is asked.
instance Iterator[Range -> usize] {
    fn next(&it: Range) -> Option[usize] {
        if it.cur < it.end {
            let cur = it.cur;
            it = Range.{ cur: cur + 1usize, end: it.end };
            Option::Some.(cur)
        } else {
            Option::None
        }
    }
}

/// Left-folds `f` over every item, returning the exhausted iterator with the
/// result. `f` captures freely; `Copy[Env]` lets the one closure be called for
/// every item.
forall Self, Item, Acc, Env where Iterator[Self -> Item], Copy[Env].
fn fold(it: Self, acc: Acc, f: closure[Env](Acc, Item) -> Acc) -> (Self, Acc) {
    var it = it;
    let item_opt = &it.next();
    match item_opt {
        Some(item) => fold(it, f(acc, item), f),
        None => (it, acc),
    }
}

// ------------------------------------------------------------ adapters --
// Each adapter's instance is conditional on its inner iterator's:
// `Iterator[Map[I, In, Out, Env] -> Out]` holds when `Iterator[I -> In]`
// does. The constructors carry the same bound, so a call's closure is typed
// from the inner iterator's items. An adapter destructures itself once per
// `next`, since its inner iterator may be linear.

/// `f` applied to each item.
forall I, In, Out, Env.
exposed struct Map {
    inner: I,
    f: closure[Env](In) -> Out,
}

/// Each item of `it` through `f`.
forall I, In, Out, Env where Iterator[I -> In].
fn map(it: I, f: closure[Env](In) -> Out) -> Map[I, In, Out, Env] {
    Map.{ inner: it, f }
}

/// `map`: the next item of the inner iterator, through `f`.
forall I, In, Out, Env where Iterator[I -> In], Copy[Env].
instance Iterator[Map[I, In, Out, Env] -> Out] {
    fn next(&m: Map[I, In, Out, Env]) -> Option[Out] {
        var { inner, f } = m;
        let item_opt = &inner.next();
        m = Map.{ inner, f };
        match item_opt {
            Some(item) => Option::Some.(f(item)),
            None => Option::None,
        }
    }
}

/// The items `pred` keeps. `Copy[In]`: a rejected item is dropped.
forall I, In, Env where Copy[In].
exposed struct Filter {
    inner: I,
    pred: closure[Env](In) -> bool,
}

/// The items of `it` that `pred` keeps.
forall I, In, Env where Iterator[I -> In], Copy[In].
fn filter(it: I, pred: closure[Env](In) -> bool) -> Filter[I, In, Env] {
    Filter.{ inner: it, pred }
}

/// Pulls from the inner iterator until `pred` keeps an item or it runs out.
/// A plain function rather than the instance's own body, so that it recurses
/// on the inner `I` itself.
forall I, In, Env where Iterator[I -> In], Copy[In], Copy[Env].
fn filter_skip(&it: I, pred: closure[Env](In) -> bool) -> Option[In] {
    let item_opt = &it.next();
    match item_opt {
        Some(item) => {
            let keep = pred(item);
            if keep {
                Option::Some.(item)
            } else {
                filter_skip(&it, pred)
            }
        },
        None => Option::None,
    }
}

/// `filter`: the next item of the inner iterator that `pred` keeps.
forall I, In, Env where Iterator[I -> In], Copy[In], Copy[Env].
instance Iterator[Filter[I, In, Env] -> In] {
    fn next(&flt: Filter[I, In, Env]) -> Option[In] {
        var { inner, pred } = flt;
        let item_opt = filter_skip(&inner, pred);
        flt = Filter.{ inner, pred };
        item_opt
    }
}

/// A named pair: the item type of `zip` and `enumerate`.
forall A, B.
exposed struct Pair {
    a: A,
    b: B,
}

/// Pairs the two iterators' items until either runs out. Both sides are
/// pulled before either is inspected, so an item left over when the other
/// side ends is dropped: `Copy[ItemA]`, `Copy[ItemB]`. Once one side has
/// run out, neither is pulled again (`done`).
forall IA, IB.
exposed struct Zip {
    a: IA,
    b: IB,
    done: bool,
}

/// The items of `a` and `b` in pairs, until either runs out.
forall IA, IB.
fn zip(a: IA, b: IB) -> Zip[IA, IB] {
    Zip.{ a, b, done: false }
}

/// `zip`: the next item of each, paired, until either runs out.
forall IA, IB, ItemA, ItemB where Iterator[IA -> ItemA], Iterator[IB -> ItemB], Copy[ItemA], Copy[ItemB].
instance Iterator[Zip[IA, IB] -> Pair[ItemA, ItemB]] {
    fn next(&z: Zip[IA, IB]) -> Option[Pair[ItemA, ItemB]] {
        let { a, b, done } = z;
        if done {
            z = Zip.{ a, b, done };
            return Option::None;
        }
        var a = a;
        var b = b;
        let a_opt = &a.next();
        let b_opt = &b.next();
        let pair = match a_opt {
            Some(av) => match b_opt {
                Some(bv) => Option::Some.(Pair.{ a: av, b: bv }),
                None => Option::None,
            },
            None => Option::None,
        };
        z = Zip.{ a, b, done: pair.is_none() };
        pair
    }
}

/// Each item with its index, counting from 0: `Pair { a: index, b: item }`.
forall I.
exposed struct Enumerate {
    inner: I,
    index: usize,
}

/// `enumerate`: the next item with its index.
forall I, T where Iterator[I -> T].
instance Iterator[Enumerate[I] -> Pair[usize, T]] {
    fn next(&e: Enumerate[I]) -> Option[Pair[usize, T]] {
        var { inner, index } = e;
        let item = &inner.next();
        match item {
            Some(v) => {
                e = Enumerate.{ inner, index: index + 1usize };
                Option::Some.(Pair.{ a: index, b: v })
            },
            None => {
                e = Enumerate.{ inner, index };
                Option::None
            },
        }
    }
}

/// At most `left` more items; the inner iterator is not pulled past them,
/// nor again once it has run out (`left` drops to 0).
forall I.
exposed struct Take {
    inner: I,
    left: usize,
}

/// `take`: the next item while any of the count is left.
forall I, T where Iterator[I -> T].
instance Iterator[Take[I] -> T] {
    fn next(&t: Take[I]) -> Option[T] {
        var { inner, left } = t;
        if left == 0usize {
            t = Take.{ inner, left };
            return Option::None;
        }
        let item = &inner.next();
        let (item, left) = match item {
            Some(v) => (Option::Some.(v), left - 1usize),
            None => (Option::None, 0usize),
        };
        t = Take.{ inner, left };
        item
    }
}

/// The items after the first `left`. `Copy[T]`: the skipped ones are dropped.
/// Once the inner iterator has run out, while skipping or after, it is not
/// pulled again (`done`).
forall I.
exposed struct Skip {
    inner: I,
    left: usize,
    done: bool,
}

/// `skip`: the items after the first `left`.
forall I, T where Iterator[I -> T], Copy[T].
instance Iterator[Skip[I] -> T] {
    fn next(&s: Skip[I]) -> Option[T] {
        var { inner, left, done } = s;
        while left > 0usize && !done {
            let skipped = &inner.next();
            done = skipped.is_none();
            left = left - 1usize;
        }
        let item = if done { Option::None } else { &inner.next() };
        s = Skip.{ inner, left: 0usize, done: done || item.is_none() };
        item
    }
}

/// Items while `pred` keeps them; the first it rejects ends the iterator and
/// is dropped (`Copy[T]`).
forall I, T, Env where Copy[T].
exposed struct TakeWhile {
    inner: I,
    pred: closure[Env](T) -> bool,
    done: bool,
}

/// `take_while`: the next item while `pred` holds of it.
forall I, T, Env where Iterator[I -> T], Copy[T], Copy[Env].
instance Iterator[TakeWhile[I, T, Env] -> T] {
    fn next(&w: TakeWhile[I, T, Env]) -> Option[T] {
        var { inner, pred, done } = w;
        if done {
            w = TakeWhile.{ inner, pred, done };
            return Option::None;
        }
        let item = &inner.next();
        let kept = match item {
            Some(v) => if pred(v) {
                Option::Some.(v)
            } else {
                Option::None
            },
            None => Option::None,
        };
        let done = match kept {
            Some(_v) => false,
            None => true,
        };
        w = TakeWhile.{ inner, pred, done };
        kept
    }
}

/// The first iterator's items, then the second's. Once the first has run
/// out it is not pulled again (`a_done`).
forall IA, IB.
exposed struct Chain {
    a: IA,
    b: IB,
    a_done: bool,
}

/// `chain`: the items of `a`, then those of `b`.
forall IA, IB, T where Iterator[IA -> T], Iterator[IB -> T].
instance Iterator[Chain[IA, IB] -> T] {
    fn next(&c: Chain[IA, IB]) -> Option[T] {
        var { a, b, a_done } = c;
        let first = if a_done { Option::None } else { &a.next() };
        let item = match first {
            Some(v) => Option::Some.(v),
            None => {
                a_done = true;
                &b.next()
            },
        };
        c = Chain.{ a, b, a_done };
        item
    }
}

// ------------------------------------------------------------- methods --
// The adapters as methods of every iterator, through an extension impl:
// `range(0, 10).filter(|x| x % 2 == 0).map(|x| x * x).fold(0, |a, x| a + x)`.
forall I, T where Iterator[I -> T].
impl I {
    /// Each item through `f`.
    forall Out, Env.
    fn map(self, f: closure[Env](T) -> Out) -> Map[I, T, Out, Env] {
        map(self, f)
    }

    /// The items `pred` keeps.
    forall Env where Copy[T].
    fn filter(self, pred: closure[Env](T) -> bool) -> Filter[I, T, Env] {
        filter(self, pred)
    }

    /// This iterator's items paired with `other`'s, until either runs out.
    forall J.
    fn zip(self, other: J) -> Zip[I, J] {
        zip(self, other)
    }

    /// Left-folds `f` over every item, returning the exhausted iterator with
    /// the result.
    forall Acc, Env where Copy[Env].
    fn fold(self, acc: Acc, f: closure[Env](Acc, T) -> Acc) -> (I, Acc) {
        fold(self, acc, f)
    }

    /// Each item with its index, counting from 0.
    fn enumerate(self) -> Enumerate[I] {
        Enumerate.{ inner: self, index: 0usize }
    }

    /// At most the first `count` items.
    fn take(self, count: usize) -> Take[I] {
        Take.{ inner: self, left: count }
    }

    /// This iterator's items, then `other`'s.
    forall J.
    fn chain(self, other: J) -> Chain[I, J] {
        Chain.{ a: self, b: other, a_done: false }
    }
}

// The methods that drop items they pass over or reject, so `Copy[T]`. Each
// consumer returns the iterator with its answer, as `fold` does; one that
// stops early leaves the rest unread.
forall I, T where Iterator[I -> T], Copy[T].
impl I {
    /// The items after the first `count`.
    fn skip(self, count: usize) -> Skip[I] {
        Skip.{ inner: self, left: count, done: false }
    }

    /// The items up to the first one `pred` rejects.
    forall Env where Copy[Env].
    fn take_while(self, pred: closure[Env](T) -> bool) -> TakeWhile[I, T, Env] {
        TakeWhile.{ inner: self, pred, done: false }
    }

    /// How many items are left, with the exhausted iterator.
    fn count(self) -> (I, usize) {
        var it = self;
        var n = 0usize;
        for x in &it {
            n = n + 1usize;
        }
        (it, n)
    }

    /// Whether `pred` holds for some item, with the iterator, read up to
    /// that item.
    forall Env where Copy[Env].
    fn any(self, pred: closure[Env](T) -> bool) -> (I, bool) {
        var it = self;
        for x in &it {
            if pred(x) {
                return (it, true);
            }
        }
        (it, false)
    }

    /// Whether `pred` holds for every item, with the iterator, read up to
    /// the first item it fails for.
    forall Env where Copy[Env].
    fn all(self, pred: closure[Env](T) -> bool) -> (I, bool) {
        var it = self;
        for x in &it {
            if !pred(x) {
                return (it, false);
            }
        }
        (it, true)
    }

    /// The first item `pred` holds for, with the iterator, read up to that
    /// item.
    forall Env where Copy[Env].
    fn find(self, pred: closure[Env](T) -> bool) -> (I, Option[T]) {
        var it = self;
        for x in &it {
            if pred(x) {
                return (it, Option::Some.(x));
            }
        }
        (it, Option::None)
    }
}