#! @file iteration.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the traits of iteration, and the iterators any container may lend: #! `iter`, which gives elements one at a time and which a `for` loop walks, with #! the adapters making one iterator of another and the consumers walking one to #! its end as its defaults; `sized_iterator`, which knows how many elements it #! has left; `backward_iterator`, which also walks from its far end; `iterable`, #! which lends an iterator over the elements a container holds; and #! `positions_iterator` and `position_mutator`, which read and write the #! elements of whatever is indexed by position, so a container need not write #! iterators of its own. module core; #! Gives elements one at a time, as `some` of each while there are more and #! `none` once there are no more. #! #! `for x in it` walks an iterator where it is, calling `next` until it gives #! `none`, so one that a loop stops early carries on from there in the next. An #! iterator that is `owning` and that a loop is given as a value, rather than as #! a variable, is closed where the loop ends, however it ends. #! #! A type naming the trait has its defaults: the adapters, which make an #! iterator of it, as `v.iter().filter(odd).map(square)`, and the consumers, #! which walk it to its end, or until they know their answer, as `.sum()`. Each #! is compiled for the type, so what it calls of the type is called directly. An #! adapter moves the iterator it is called on into what it makes, which closes #! it where that closes, so `it.map(f)` leaves `it` walked to its end. #! #! It is named as the types the syntax makes are, short, leaving `iterator` to #! the type a container lends, as `vector::iterator`. #! @tparam T The type of what it gives. pub trait iter { #! Gives the next element, or `none` once there are no more. #! @param this The iterator to advance. #! @returns Maybe the next element; otherwise, `nothing`. def next(&mut this): maybe; #! Gives what a function makes of each element. #! @tparam U What the function gives. #! @tparam F The function, a lambda, or anything `invokable`. #! @param this The iterator, moved into what is made. #! @param f The function, called on each element as it is given. #! @returns The iterator of what it makes. def map(&mut this, f: F): mapped where F: invokable { return mapped:: { _from = move(this), _f = move(&mut f) }; } #! Gives each element a test passes. #! @tparam F The test. #! @param this The iterator, moved into what is made. #! @param test The test, given a reference to each element. #! @returns The iterator of those that pass. def filter(&mut this, test: F): filtered where F: invokable { return filtered:: { _from = move(this), _test = move(&mut test) }; } #! Gives what a function makes of each element where it makes something, as #! `some`. #! @tparam U What the function may give. #! @tparam F The function. #! @param this The iterator, moved into what is made. #! @param f The function, called on each element. #! @returns The iterator of what it makes. def filter_map(&mut this, f: F): filter_mapped where F: invokable> { return filter_mapped:: { _from = move(this), _f = move(&mut f) }; } #! Gives each element with its index, counting from 0, as a `pair`. #! @param this The iterator, moved into what is made. #! @returns The iterator of pairs. def enumerate(&mut this): enumerated { return enumerated:: { _from = move(this), _at = 0 }; } #! Gives the elements of this iterator and another side by side, as a `pair`, #! until either ends. #! @tparam U What the other gives. #! @tparam J The other iterator. #! @param this The iterator, moved into what is made. #! @param other The other iterator, moved into what is made. #! @returns The iterator of pairs. def zip(&mut this, other: J): zipped where J: iter { return zipped:: { _from = move(this), _other = move(&mut other) }; } #! Gives this iterator's elements, then another's. #! @tparam J The other iterator, giving what this one gives. #! @param this The iterator, moved into what is made. #! @param other The other iterator, moved into what is made. #! @returns The iterator of both. def chain(&mut this, other: J): chained where J: iter { return chained:: { _first = move(this), _second = move(&mut other), _on_second = false }; } #! Gives the first elements, up to a count. #! @param this The iterator, moved into what is made. #! @param n How many to give at most. #! @returns The iterator of those. def take(&mut this, n: u64): taken { return taken:: { _from = move(this), _left = n }; } #! Gives the elements after the first, up to a count, which it passes over. #! @param this The iterator, moved into what is made. #! @param n How many to pass over. #! @returns The iterator of the rest. def skip(&mut this, n: u64): skipped { return skipped:: { _from = move(this), _skip = n }; } #! Gives the elements while a test passes them, ending at the first it does #! not. #! @tparam F The test. #! @param this The iterator, moved into what is made. #! @param test The test, given a reference to each element. #! @returns The iterator of the run that passes. def take_while(&mut this, test: F): taken_while where F: invokable { return taken_while:: { _from = move(this), _test = move(&mut test), _done = false }; } #! Gives the elements from the first a test does not pass on, passing over #! those before it. #! @tparam F The test. #! @param this The iterator, moved into what is made. #! @param test The test, given a reference to each element. #! @returns The iterator of the rest. def skip_while(&mut this, test: F): skipped_while where F: invokable { return skipped_while:: { _from = move(this), _test = move(&mut test), _past = false }; } #! Gives every `n`th element, the first included. #! @param this The iterator, moved into what is made. #! @param n How far apart the elements given are, at least 1. #! @returns The iterator of those. def step(&mut this, n: u64): stepped { if n == 0 { fault("An iterator steps by 0, which is no step."); } return stepped:: { _from = move(this), _by = n, _first = true }; } #! Gives the elements from the far end. #! @param this The iterator, moved into what is made. #! @returns The iterator walking backward. def rev(&mut this): reversed where self: backward_iterator { return reversed:: { _from = move(this) }; } #! Gives the elements, and looks at the next before it is given, by `peek`. #! @param this The iterator, moved into what is made. #! @returns The iterator that peeks. def peekable(&mut this): peeking { return peeking:: { _from = move(this), _held = nothing {} }; } #! Gives the elements of each iterator a function makes of each element. #! @tparam U What the iterators it makes give. #! @tparam J The iterators it makes. #! @tparam F The function. #! @param this The iterator, moved into what is made. #! @param f The function, called on each element. #! @returns The iterator of what each gives, in turn. def flat_map(&mut this, f: F): flat_mapped where F: invokable where J: iter { return flat_mapped:: { _from = move(this), _f = move(&mut f), _inner = nothing {} }; } #! Gives a copy of what each reference it gives refers to, of what closes #! nothing. #! @tparam X What the references refer to. #! @param this The iterator of references, moved into what is made. #! @returns The iterator of copies. def copied(&mut this): copying where self: iter<&X> { return copying:: { _from = move(this) }; } #! Gives the elements as they are, after calling a function on each. #! @tparam F The function. #! @param this The iterator, moved into what is made. #! @param f The function, given a reference to each element. #! @returns The iterator. def inspect(&mut this, f: F): inspected where F: invokable { return inspected:: { _from = move(this), _f = move(&mut f) }; } #! Walks to the end, counting the elements. #! @param this The iterator. #! @returns How many it gave. def count(&mut this): u64 { var n: u64 = 0; while this.next() is some(x) { n++; } return n; } #! Walks to the end, adding the elements up. #! @param this The iterator, of numbers. #! @returns The sum, or 0 where it gives none. def sum(&mut this): T where T: numeric { var total: T = 0; while this.next() is some(x) { total += x; } return total; } #! Walks to the end, multiplying the elements together. #! @param this The iterator, of numbers. #! @returns The product, or 1 where it gives none. def product(&mut this): T where T: numeric { var total: T = 1; while this.next() is some(x) { total *= x; } return total; } #! Walks to the end, folding each element into a value: `f(f(start, x0), x1)` #! and on. #! @tparam A The value. #! @tparam F The function folding each in. #! @param this The iterator. #! @param start The value before any element is folded in. #! @param f The function, given the value so far and the element. #! @returns The value once every element is folded in. def fold(&mut this, start: A, f: F): A where F: invokable { var made := move(&mut start); while this.next() is some(x) { made = f(move(&mut made), move(&mut x)); } return made; } #! Walks to the end, folding the elements into the first: `f(f(x0, x1), x2)` #! and on. #! @tparam F The function folding each in. #! @param this The iterator. #! @param f The function, given the value so far and the element. #! @returns Maybe the value; otherwise, `nothing` where it gives no elements. def reduce(&mut this, f: F): maybe where F: invokable { var first := this.next(); if first is not some(&mut start) { return nothing {}; } var made := move(start); while this.next() is some(x) { made = f(move(&mut made), move(&mut x)); } return made; } #! Whether a test passes any element, walking until one does. #! @tparam F The test. #! @param this The iterator. #! @param test The test, given a reference to each element. #! @returns Whether it passes one. def any(&mut this, test: F): bool where F: invokable { while this.next() is some(x) { return true if test(&x); } return false; } #! Whether a test passes every element, walking until one fails it. #! @tparam F The test. #! @param this The iterator. #! @param test The test, given a reference to each element. #! @returns Whether it passes all of them, as it does where there are none. def all(&mut this, test: F): bool where F: invokable { while this.next() is some(x) { return false if !test(&x); } return true; } #! The first element a test passes, walking until it finds one. #! @tparam F The test. #! @param this The iterator. #! @param test The test, given a reference to each element. #! @returns Maybe the element; otherwise, `nothing`. def find(&mut this, test: F): maybe where F: invokable { while this.next() is some(x) { return move(&mut x) if test(&x); } return nothing {}; } #! The index of the first element a test passes, counting from 0, walking #! until it finds one. #! @tparam F The test. #! @param this The iterator. #! @param test The test, given a reference to each element. #! @returns Maybe the index; otherwise, `nothing`. def position(&mut this, test: F): maybe where F: invokable { var at: u64 = 0; while this.next() is some(x) { return at if test(&x); at++; } return nothing {}; } #! Walks to the end, keeping the least element, the first of those equally #! least. #! @param this The iterator, of what is ordered. #! @returns Maybe the least; otherwise, `nothing` where it gives none. def min(&mut this): maybe where T: ordered { var first := this.next(); if first is not some(&mut start) { return nothing {}; } var best := move(start); while this.next() is some(x) { if x < best { best = move(&mut x); } } return best; } #! Walks to the end, keeping the greatest element, the last of those equally #! greatest. #! @param this The iterator, of what is ordered. #! @returns Maybe the greatest; otherwise, `nothing` where it gives none. def max(&mut this): maybe where T: ordered { var first := this.next(); if first is not some(&mut start) { return nothing {}; } var best := move(start); while this.next() is some(x) { if !(x < best) { best = move(&mut x); } } return best; } #! Walks to the end, keeping the least element as an order says, the first of #! those equally least. #! @tparam F The order. #! @param this The iterator. #! @param order Whether one element comes before another. #! @returns Maybe the least; otherwise, `nothing` where it gives none. def min_by(&mut this, order: F): maybe where F: invokable { var first := this.next(); if first is not some(&mut start) { return nothing {}; } var best := move(start); while this.next() is some(x) { if order(&x, &best) { best = move(&mut x); } } return best; } #! Walks to the end, keeping the greatest element as an order says, the last #! of those equally greatest. #! @tparam F The order. #! @param this The iterator. #! @param order Whether one element comes before another. #! @returns Maybe the greatest; otherwise, `nothing` where it gives none. def max_by(&mut this, order: F): maybe where F: invokable { var first := this.next(); if first is not some(&mut start) { return nothing {}; } var best := move(start); while this.next() is some(x) { if !order(&x, &best) { best = move(&mut x); } } return best; } #! Walks to the end, keeping the element whose key is least, the first of #! those equally least. #! @tparam K The key, which is ordered. #! @tparam F The function giving the key. #! @param this The iterator. #! @param key The function, given a reference to each element. #! @returns Maybe the element; otherwise, `nothing` where it gives none. def min_by_key(&mut this, key: F): maybe where F: invokable where K: ordered { var first := this.next(); if first is not some(&mut start) { return nothing {}; } var best := move(start); var least := key(&best); while this.next() is some(x) { var made := key(&x); if made < least { best = move(&mut x); least = move(&mut made); } } return best; } #! Walks to the end, keeping the element whose key is greatest, the last of #! those equally greatest. #! @tparam K The key, which is ordered. #! @tparam F The function giving the key. #! @param this The iterator. #! @param key The function, given a reference to each element. #! @returns Maybe the element; otherwise, `nothing` where it gives none. def max_by_key(&mut this, key: F): maybe where F: invokable where K: ordered { var first := this.next(); if first is not some(&mut start) { return nothing {}; } var best := move(start); var most := key(&best); while this.next() is some(x) { var made := key(&x); if !(made < most) { best = move(&mut x); most = move(&mut made); } } return best; } #! The last element: from the far end where the iterator walks backward, #! and otherwise by walking to the end. #! @param this The iterator. #! @returns Maybe the last element; otherwise, `nothing` where it gives none. def last(&mut this): maybe { if const self is backward_iterator { return this.next_back(); } var kept: maybe = nothing {}; while this.next() is some(x) { kept = move(&mut x); } return kept; } #! The element `n` along, counting from 0, passing over those before it. #! @param this The iterator. #! @param n How many to pass over first. #! @returns Maybe the element; otherwise, `nothing` where it gives fewer. def nth(&mut this, n: u64): maybe { var left := n; while left != 0 { return nothing {} if this.next() is not some(x); left--; } return this.next(); } #! Walks to the end, calling a function on each element. #! @tparam F The function. #! @param this The iterator. #! @param f The function, given each element. def for_each(&mut this, f: F): void where F: invokable { while this.next() is some(x) { f(move(&mut x)); } } #! Walks to the end, collecting the elements into a vector, which is given #! room for them all at once where the iterator knows how many it has left. #! @param this The iterator. #! @returns The vector. def to_vector(&mut this): vector { var made := vector::::new(); if const self is sized_iterator { made.reserve(this.remaining()); } while this.next() is some(x) { made.append(move(&mut x)); } return made; } #! Walks to the end, joining the text of the elements, as `$"{x}"` writes #! each, with text between each two. #! @param this The iterator. #! @param between What is written between each two elements. #! @returns The text. def to_string(&mut this, between: strview): string { var made := string::new(nothing {}); var first := true; while this.next() is some(x) { if !first { made.append(between); } first = false; val text := $"{x}"; made.append(text.span); } return made; } #! Walks to the end, appending each element to a container, as a `vector`, a #! `string`, or anything `extendable` is. #! @tparam C The container. #! @param this The iterator. #! @param target The container, which keeps what it held before. def into(&mut this, target: &mut C): void where C: extendable { while this.next() is some(x) { target.append(move(&mut x)); } } } #! An iterator that knows how many elements it has left, as a view, a range, #! and the containers' iterators do, so collecting it makes room for them at #! once. #! @tparam T The type of what it gives. pub trait sized_iterator : iter { #! How many elements it has left to give. #! @param this The iterator. #! @returns How many. def remaining(&this): u64; } #! An iterator that also walks from its far end, until the two ends meet, as a #! view, a range, a `deque`, and a `chain` do, which `rev` and `last` take. #! @tparam T The type of what it gives. pub trait backward_iterator : iter { #! Gives the element at the far end, or `none` once the ends have met. #! @param this The iterator. #! @returns Maybe the last element left; otherwise, `nothing`. def next_back(&mut this): maybe; } #! Lends an iterator over the elements it holds, as references to them. #! #! `for x in c` calls `iter(&this)` once and walks what it gives, copying each #! element, and `for &x in c` refers to each instead. `for &mut x in c` calls #! `iter(&mut this)`, which a container whose elements may be changed in place #! gives, and which one that only reads leaves out. What `iter` gives is closed #! where the loop ends, however it ends, where it is `owning`. #! #! The iterator types are asked of the container: an `iterator`, which only #! reads, and a `mutator`, which writes, as `type list::iterator = ...;`, so #! generic code names them through a bound, as `C::iterator` where #! `C: iterable`. A container lends them as properties of the same names too, #! as `v.iterator`. A container indexed by position need write neither, since #! `positions_iterator` and `position_mutator` walk it through its `at`. #! #! Within the container, as within this trait, `iterator` names the type it #! lends, so the trait is `iter` there, as `where I: iter`. #! @tparam T The type of the elements, which the iterators give references to. pub trait iterable { #! What `iter(&this)` gives, which gives references that read the elements. type iterator: iter<&T>; #! What `iter(&mut this)` gives, which gives references that write them. @optional type mutator: iter<&mut T>; #! Lends an iterator that reads the elements. #! @param this The container to iterate. #! @returns The iterator, which refers into the container. def iter(&this): iterator; #! Lends an iterator that writes the elements where they are. #! @param this The container to iterate. #! @returns The iterator, which refers into the container. @optional def iter(&mut this): mutator; } #! Walks the elements of whatever is indexed by position, from `0` up to a #! length, giving a reference that reads each in turn through its `at`, from #! either end. It is the `iterator` of a container that has no faster way to #! walk its elements, as a ring buffer, whose elements are not one run, so the #! container writes none of its own: `type ring::iterator = #! positions_iterator, T>;`. #! #! It refers to the container rather than to its elements, so it is only good #! while the container stays where it is and holds at least as many elements. #! @tparam C The container, indexed by position. #! @tparam T The type of its elements. pub struct positions_iterator : sized_iterator<&T>, backward_iterator<&T> where C: indexable { var _of: *C; var _at: u64; var _left: u64; } #! Makes an iterator over the elements of a container, from position `0` up to #! a length. #! @param of The container, which the iterator refers to. #! @param length How many elements it gives, which the container holds. #! @returns The iterator. pub def positions_iterator::over(of: &C, length: u64): positions_iterator { return positions_iterator:: { _of = &of, _at = 0, _left = length }; } #! Gives the next element of the container. #! @param this The iterator to advance. #! @returns Maybe a reference to the next element; otherwise, `nothing`. pub def positions_iterator::next(&mut this): maybe<&T> { if this._left == 0 { return nothing {}; } val here := this._at; this._at = here + 1; this._left = this._left - 1; return &(*this._of)[here]; } #! How many elements the iterator has left to give. #! @param this The iterator. #! @returns How many. pub def positions_iterator::remaining(&this): u64 { return this._left; } #! Gives the last element the iterator has left, from the far end. #! @param this The iterator to advance from its far end. #! @returns Maybe a reference to the element; otherwise, `nothing`. pub def positions_iterator::next_back(&mut this): maybe<&T> { if this._left == 0 { return nothing {}; } this._left = this._left - 1; return &(*this._of)[this._at + this._left]; } #! Walks the elements of whatever is indexed by position and written there, #! from `0` up to a length, giving a reference that writes each in turn through #! its `at`, from either end. It is the `mutator` of a container that has no #! faster way to walk its elements, as `positions_iterator` is its `iterator`. #! #! It refers to the container rather than to its elements, so it is only good #! while the container stays where it is and holds at least as many elements. #! @tparam C The container, indexed by position and written there. #! @tparam T The type of its elements. pub struct position_mutator : sized_iterator<&mut T>, backward_iterator<&mut T> where C: assignable { var _of: *mut C; var _at: u64; var _left: u64; } #! Makes an iterator writing the elements of a container, from position `0` up #! to a length. #! @param of The container, which the iterator refers to. #! @param length How many elements it gives, which the container holds. #! @returns The iterator. pub def position_mutator::over(of: &mut C, length: u64): position_mutator { return position_mutator:: { _of = &mut of, _at = 0, _left = length }; } #! Gives the next element of the container, to be written. #! @param this The iterator to advance. #! @returns Maybe a reference to the next element; otherwise, `nothing`. pub def position_mutator::next(&mut this): maybe<&mut T> { if this._left == 0 { return nothing {}; } val here := this._at; this._at = here + 1; this._left = this._left - 1; return &mut (*this._of)[here]; } #! How many elements the iterator has left to give. #! @param this The iterator. #! @returns How many. pub def position_mutator::remaining(&this): u64 { return this._left; } #! Gives the last element the iterator has left, from the far end, to be #! written. #! @param this The iterator to advance from its far end. #! @returns Maybe a reference to the element; otherwise, `nothing`. pub def position_mutator::next_back(&mut this): maybe<&mut T> { if this._left == 0 { return nothing {}; } this._left = this._left - 1; return &mut (*this._of)[this._at + this._left]; }