Iterators and generators
A method that contains yield is a generator. It returns an Iterator<T>. A class works in
foreach when it implements Iterable<T> or Iterator<T>. A class that gives a key with each
value implements KeyedIterable<K, V> or KeyedIterator<K, V>.
Generators
A generator is a method that gives out its values one at a time, as a loop asks for them.
Write yield in the body and declare Iterator<T> as the return type. Calling the method runs none of the body. It returns a cursor, and each step of a foreach loop runs the body as far as the next yield. When the loop ends, the body stops where it is. This makes a generator cheap. It has one value at a time, and it can give a sequence that goes on forever.
Good to know: a generator is walked once. A second foreach over the same cursor sees nothing, and calling the method again gives you a new cursor that starts at the beginning.
You cannot clone a generator. clone Gen::count(3) does not compile. If the generator is in a mixed or Iterator<T> variable, clone throws a LogicError. To start again, call the method again.
The examples below show a small generator first, then a sequence with no end, then two generators reading one report together. Then they show separate cursors and return;, a finally block, an error thrown in a generator, and two code examples that do not compile.
A method that yields its values
<?nvs// Shows how to write a generator: a method whose body contains `yield`. It gives// out one value at a time, and the body runs only as far as the loop asks.
class Countdown{ // A generator declares `Iterator<T>` as its return type. Each `yield` gives one `T`. public static function from(int $start): Iterator<int> { echo "the body starts\n"; int $n = $start; while ($n > 0) { yield $n; $n = $n - 1; } echo "the body ends\n"; }}
// Calling the method runs none of the body. It returns a cursor, and prints nothing.Iterator<int> $numbers = Countdown::from(3);echo "the cursor exists\n";
// The loop is what runs the body. This prints 3, 2 and 1.foreach ($numbers as int $n) { echo $n, "\n";}the cursor existsthe body starts321the body endsA sequence with no end
<?nvs// Shows a generator whose loop has no end. The body runs one step per value, so a// sequence without an end is safe to write and safe to walk.
class Backoff{ // Every wait is twice the one before it: 1, 2, 4, 8, and so on. public static function delays(int $first): Iterator<int> { int $wait = $first; while (true) { yield $wait; $wait = $wait * 2; } }}
int $attempt = 0;foreach (Backoff::delays(1) as int $seconds) { $attempt = $attempt + 1; echo "attempt {$attempt} waits {$seconds}s\n"; // `break` leaves the generator where it stopped. The body runs no further, // so the loop above ends after four values. if ($attempt == 4) { break; }}attempt 1 waits 1sattempt 2 waits 2sattempt 3 waits 4sattempt 4 waits 8sScanning a report line by line
<?nvs// Shows two generators working together: one reads the lines of a report, the other// keeps the lines that matter. A program uses this shape to scan a long report while// holding one line at a time.
class Report{ // Gives out the lines of the text, one per `yield`. public static function lines(string $text): Iterator<string> { foreach (Core\Str::lines($text) as string $line) { yield $line; } }
// Reads the generator above and keeps only the failures. A `foreach` with a // `yield` inside it is how one generator reads another. public static function failures(Iterator<string> $lines): Iterator<string> { foreach ($lines as string $line) { if (Core\Str::startsWith($line, 'ERROR')) { yield $line; } } }}
string $log = "INFO started\nERROR disk full\nINFO retry\nERROR timeout\nINFO done\n";
// This prints the two `ERROR` lines. The report is walked once, and neither// generator builds a list of its own.foreach (Report::failures(Report::lines($log)) as string $failure) { echo $failure, "\n";}ERROR disk fullERROR timeoutEach call gives its own cursor
<?nvs// Shows that each call gives a new cursor, that `return;` ends the values early,// and that a cursor is walked once.
class Numbers{ public static function count(int $n): Iterator<int> { int $i = 0; while ($i < $n) { yield $i; $i = $i + 1; } }
public static function early(bool $stop): Iterator<int> { yield 1; if ($stop) { return; } yield 2; }}
// Two calls give two cursors. Each one keeps its own place, so this prints 10.Iterator<int> $a = Numbers::count(3);Iterator<int> $b = Numbers::count(3);$a->advance();$a->advance();$b->advance();echo $a->current(), $b->current(), "\n";
// `return;` stops the values. This prints 1, then 12.foreach (Numbers::early(true) as int $v) { echo $v;}echo "\n";foreach (Numbers::early(false) as int $v) { echo $v;}echo "\n";
// The second loop over the same cursor gets no values. This prints 01 once.Iterator<int> $once = Numbers::count(2);foreach ($once as int $v) { echo $v;}foreach ($once as int $v) { echo $v;}echo "\n";1011201Finally runs when the loop stops
<?nvs// Shows that a `finally` block in a generator runs when the body ends, and also// when the loop stops early with `break`.
class Rows{ public static function read(int $n): Iterator<int> { try { int $i = 0; while ($i < $n) { yield $i; $i = $i + 1; } } finally { echo '[closed]'; } }}
// The body reaches its end, so this prints 012[closed].foreach (Rows::read(3) as int $v) { echo $v;}echo "\n";
// `break` stops the loop after 1. The `finally` block still runs, so this prints 01[closed].foreach (Rows::read(5) as int $v) { echo $v; if ($v == 1) { break; }}echo "\n";012[closed]01[closed]An error thrown by a generator
<?nvs// Shows that an error thrown in a generator reaches the loop that reads it.
class Feed{ public static function upTo(int $n): Iterator<int> { int $i = 0; while ($i < $n) { if ($i == 2) { throw new RuntimeError('bad element 2'); } yield $i; $i = $i + 1; } }}
// The loop gets 0 and 1 first. Then the error reaches the `catch` block,// so this prints 0;1;caught: bad element 2.try { foreach (Feed::upTo(5) as int $v) { echo $v, ';'; }} catch (RuntimeError $e) { echo 'caught: ', $e->message, "\n";}0;1;caught: bad element 2Yield from does not exist
<?nvs// Shows that `yield from` does not compile. To give out the values of another// generator, loop over it and `yield` each value.// proof: compile-error
class Pages{ public static function first(): Iterator<int> { yield 1; }
public static function all(): Iterator<int> { yield from Pages::first(); }}error[E0448]: `yield from` does not exist in Novis --> 07-yield-from-does-not-exist.nvs:15:9 |15 | yield from Pages::first(); | ^^^^^^^^^^^^^^^^^^^^^^^^^ this delegation form = help: write `foreach ($inner as T $v) { yield $v; }`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.A generator cannot return a value
<?nvs// Shows that a generator cannot return a value. `return 5;` does not compile.// Write `return;` to stop, or `yield 5;` to give the value to the loop.// proof: compile-error
class Totals{ public static function sums(): Iterator<int> { yield 1; return 5; }}error[E0447]: a generator cannot return a value --> 08-a-generator-cannot-return-a-value.nvs:11:16 |11 | return 5; | ^ this value has nowhere to go = help: write `return;` to stop the generator, or `yield` this value
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
A method with yield in its body must return Iterator<T>. Any other return type is the error E0446. This is true for Iterable<T>, array<T> and void. Generator is not declared, so it is the error E0303. A method that returns Iterator<T> but has no yield is an ordinary method. It must return a value, or it is the error E0739.
yield works only in the body of the generator itself. A yield at the top level of a file, or in an anonymous function, is the error E0445. This is also true for an anonymous function inside a generator.
A static method, an instance method and iterate() may each be a generator. An iterate() that yields gives a new generator for each loop, so the object can be walked many times.
yield is a statement and has no value. These forms are the error E0448:
int $x = yield 2;, since nothing is sent back into a generator.yield "a" => 1;, since anIterator<T>has no keys.yield;with no value.yield from G::inner();. Writeforeach (G::inner() as int $v) { yield $v; }instead.
The value of a yield must have the type T. yield "a"; in an Iterator<int> is the error E0401.
return; ends the sequence early. return 5; is the error E0447, because a generator has no return value.
A generator cannot take an inout parameter. That is the error E0492. The arguments are copied when the method is called. A change to the caller's array after the call is not seen by the generator.
current() called before the first advance(), or after advance() returned false, throws a LogicError. Once the sequence has ended, every later advance() returns false.
A loop over a generator cannot have a key. foreach (G::g() as string $k => int $v) is the error E0444.
clone G::g() is the error E0858. clone of a generator in a variable throws a LogicError with the message clone(): a generator is a suspended frame, so it has no meaning on the other side of a copy boundary.
A finally block around a yield runs when the body reaches its end. It also runs when the loop stops early with break, before the code after the loop. A generator that was advanced and then freed runs its finally too. This happens when its last variable gets a new value. A generator that was never advanced runs nothing.
A throw in the body reaches the foreach loop or the advance() call that resumed the generator. The values yielded before it have already been given to the loop. A try and catch inside the body can catch the error, and the body can then go on yielding.
A generator can read another generator with foreach, and a generator can call itself in the same way. A generator stored in a mixed variable is an Iterator<T> for is. A foreach over the mixed variable is the error E0443.
Iterable and Iterator
A class implements Iterator<T> or Iterable<T> so that a foreach loop can get values from its objects. A loop that gets a key with each value uses KeyedIterator<K, V> and KeyedIterable<K, V>.
Iterator<T> is a cursor: an object that remembers its position in a sequence. advance() moves it to the next element and returns false once there are none left. current() returns the element the last advance() moved to. Iterable<T> has one method, iterate(), which returns a new Iterator<T>. A class implements one of the two with a concrete type, such as implements Iterator<int>. You can also use Iterator<T> and Iterable<T> as a parameter type or a variable type.
Good to know: foreach calls iterate() once per loop, so one Iterable<T> object can be walked twice, or nested inside a loop over itself. An Iterator<T> has no keys, so a loop over one cannot get a key. To give keys, implement KeyedIterable<K, V>.
The examples below show a cursor written by hand. Then a class gives out a new cursor for each loop, and a search result is read page by page. Example 04 shows that a key variable over a cursor does not compile.
A cursor written by hand
<?nvs// Shows the `Iterator<T>` interface. A class that has `advance()` and `current()` can be// walked by a `foreach` loop, and by a `while` loop that calls the two methods itself.
class Letters implements Iterator<string>{ // The cursor starts before the first element, so the first `advance()` reaches it. private int $at = -1;
public function constructor(private array<string> $items) {}
// Moves to the next element. The result is `false` once there are none left. public function advance(): bool { $this->at = $this->at + 1; return $this->at < (Core\Arr::count($this->items) as int); }
// Returns the element the last `advance()` moved to. public function current(): string { return $this->items[$this->at]; }}
array<string> $abc = ['a', 'b', 'c'];
// The two methods are the whole protocol, so this loop does what a `foreach` does.var $byHand = new Letters($abc);while ($byHand->advance()) { echo $byHand->current();}echo "\n";
// The same three letters, with the loop calling the two methods for you.foreach (new Letters($abc) as string $letter) { echo $letter;}echo "\n";abcabcA fresh cursor for every loop
<?nvs// Shows the `Iterable<T>` interface. Its one method `iterate()` returns a cursor, and// `foreach` calls it once per loop. Every loop therefore starts at the beginning.
class Countdown implements Iterable<int>{ public function constructor(private int $from) {}
// A method with `yield` returns an `Iterator<int>`, which is what this must give. public function iterate(): Iterator<int> { int $i = $this->from; while ($i > 0) { yield $i; $i = $i - 1; } }}
var $three = new Countdown(3);
// The same object is walked twice, and the second loop starts at 3 again.foreach ($three as int $n) { echo $n;}echo "\n";foreach ($three as int $n) { echo $n;}echo "\n";
// One loop inside another over the same object. Each loop has its own cursor, so this// prints all nine pairs.foreach ($three as int $outer) { foreach ($three as int $inner) { echo $outer, $inner, ' '; }}echo "\n";32132133 32 31 23 22 21 13 12 11Reading a search result page by page
<?nvs// Shows a real use: a search result stored in pages. The class implements `Iterable<string>`,// so the program reading the names never handles a page itself. A page the loop does not// reach is never read.
class Results implements Iterable<string>{ public function constructor(private array<array<string>> $pages) {}
public function iterate(): Iterator<string> { foreach ($this->pages as array<string> $page) { echo "(reading a page)\n"; foreach ($page as string $name) { yield $name; } } }}
var $results = new Results([ ['Ada Lovelace', 'Alan Turing'], ['Grace Hopper', 'Edsger Dijkstra'], ['Barbara Liskov'],]);
// The loop stops after three names, so the third page is never read.int $shown = 0;foreach ($results as string $name) { echo $name, "\n"; $shown = $shown + 1; if ($shown == 3) { break; }}(reading a page)Ada LovelaceAlan Turing(reading a page)Grace HopperAn iterator has no key
<?nvs// Shows that a loop over an `Iterator` cannot get a key. This loop does not// compile. Write `as int $v` alone, or count the steps in your own variable.// proof: compile-error
class Steps{ public static function upTo(int $n): Iterator<int> { int $i = 0; while ($i < $n) { yield $i; $i = $i + 1; } }}
foreach (Steps::upTo(3) as string $k => int $v) { echo $k, '=', $v, "\n";}error[E0444]: an `Iterable`/`Iterator` subject has no key to bind --> 04-an-iterator-has-no-key.nvs:18:28 |18 | foreach (Steps::upTo(3) as string $k => int $v) { | ^^^^^^^^^ no key exists here = help: an iterator has values but no keys. Remove the `$k =>`, or loop over an `array<T>` or a `KeyedIterable<K, V>`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
implements Iterator with no type argument is the error E0442. Write the element type, such as Iterator<int>. A class of your own cannot declare a type argument. class Box<T> and interface Pair<T> do not compile.
A class that implements Iterator<T> without advance() or current() is the error E0449. The same is true for Iterable<T> without iterate().
A class may implement both interfaces. iterate() may then return $this.
The three types are separate. An array<int> and an Iterator<int> are not an Iterable<int>, and an Iterable<int> object is not an Iterator<int>. Passing one where another is needed is the error E0401. The element type must match too: an Iterable<int> object is not an Iterable<int|string>.
current() called before the first advance(), or after advance() returned false, throws a LogicError. The message is current() outside the iteration protocol: it answers only after advance() returned true.
Iterator<T> has two methods. You can write them yourself, without yield.
| Method | What it does |
|---|---|
advance(): bool |
moves to the next value. It returns false when there are no more values |
current(): T |
returns the value that advance() moved to |
Iterable<T> has one method, iterate(): Iterator<T>.
KeyedIterator<K, V> has three methods. A loop over it can write $key => $value.
| Method | What it does |
|---|---|
advance(): bool |
moves to the next entry. It returns false when there are no more entries |
key(): K |
returns the key of the entry that advance() moved to |
current(): V |
returns the value of that entry |
KeyedIterable<K, V> has one method, iterateKeyed(): KeyedIterator<K, V>.
What does not exist
PHP's iteration helpers do not exist in Novis. Naming one is a compile error.
There is no ArrayAccess, Countable, IteratorAggregate, Traversable or Generator, and no iterator_to_array, count, current, next or reset. Each one has a replacement. A class becomes walkable by implementing Iterable<T> or Iterator<T>. A generator returns an Iterator<T>, so it needs no class of its own. Core\Arr holds what the free functions did: Core\Arr::count counts, and Core\Arr::from reads a sequence into an array. Reading an element of an object, $basket[0], has no interface behind it. Give the class a method and name it yourself.
Good to know: you meet all of these when you compile, never while the program is running.
The examples below show the three replacements: Iterable<T> for IteratorAggregate, Core\Arr for the free functions, and methods of your own for ArrayAccess and Countable. The last two examples show Countable and iterator_to_array as compile errors.
Iterable in place of iteratoraggregate
<?nvs// Shows the replacement for PHP's `IteratorAggregate` and `Traversable`. A class becomes// walkable by implementing `Iterable<T>` and writing one method, `iterate()`.
class Playlist implements Iterable<string>{ private array<string> $tracks = [];
public function add(string $title): void { $this->tracks[] = $title; }
// This replaces `getIterator()`. The return type names what the loop reads. public function iterate(): Iterator<string> { foreach ($this->tracks as string $title) { yield $title; } }}
var $playlist = new Playlist();$playlist->add('Blue in Green');$playlist->add('So What');
// The object is now a subject a `foreach` loop accepts.foreach ($playlist as string $title) { echo $title, "\n";}Blue in GreenSo WhatCore arr in place of the free functions
<?nvs// Shows the replacements for PHP's `iterator_to_array` and `count`. Both live on `Core\Arr`,// so there is no free function to call.
class Series{ public static function squares(int $upTo): Iterator<int> { int $i = 1; while ($i <= $upTo) { yield $i * $i; $i = $i + 1; } }}
// `Core\Arr::from` reads a sequence into an array. This replaces `iterator_to_array`.array<int> $squares = Core\Arr::from(Series::squares(5));echo $squares[0], ',', $squares[4], "\n";
// `Core\Arr::count` returns the number of elements. This replaces `count`.echo Core\Arr::count($squares), "\n";1,255Methods of your own in place of arrayaccess
<?nvs// Shows a real use: a basket that PHP would give `ArrayAccess` and `Countable`. Novis has// neither interface, so the class names its own methods. A reader of this code sees what// each one does without looking the interface up.
class Line{ public function constructor(public string $sku, public int $quantity) {}}
class Basket implements Iterable<Line>{ private array<Line> $lines = [];
public function put(string $sku, int $quantity): void { $this->lines[] = new Line($sku, $quantity); }
// This replaces `offsetGet`, and the name says which line it returns. public function lineAt(int $position): Line { return $this->lines[$position]; }
// This replaces `count`, and it returns the number of lines. public function size(): int { return Core\Arr::count($this->lines) as int; }
public function iterate(): Iterator<Line> { foreach ($this->lines as Line $line) { yield $line; } }}
var $basket = new Basket();$basket->put('COFFEE-1KG', 2);$basket->put('FILTER-100', 1);
// This prints 2 lines, then COFFEE-1KG.echo $basket->size(), " lines\n";echo $basket->lineAt(0)->sku, "\n";
foreach ($basket as Line $line) { echo $line->sku, ' x', $line->quantity, "\n";}2 linesCOFFEE-1KGCOFFEE-1KG x2FILTER-100 x1Countable is not declared
<?nvs// Shows that `Countable` is not declared, so this class does not compile.// Remove `implements Countable` and keep the method.// proof: compile-error
class Bag implements Countable{ public function count(): int { return 1; }}error[E0303]: `Countable` is not declared --> 04-countable-is-not-declared.nvs:6:22 |6 | class Bag implements Countable | ^^^^^^^^^ no matching declaration
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Iterator to array is not a function
<?nvs// Shows that `iterator_to_array` is not a function, so this call does not compile.// Write `Core\Arr::from(Numbers::upTo(3))` instead.// proof: compile-error
class Numbers{ public static function upTo(int $n): Iterator<int> { int $i = 1; while ($i <= $n) { yield $i; $i = $i + 1; } }}
var $all = iterator_to_array(Numbers::upTo(3));error[E0320]: `iterator_to_array` is not a function that exists --> 05-iterator-to-array-is-not-a-function.nvs:18:12 |18 | var $all = iterator_to_array(Numbers::upTo(3)); | ^^^^^^^^^^^^^^^^^ no free function has this name = help: every function is a method of a class. The built-in functions are in the `Core` namespace. Write `Core\Str::length($s)`, or write `use Core\Str;` and then `Str::length($s)`
error: aborting due to 1 errorTo read what a code means and how to fix it, run `nvs agent show <code>`.Details
Countable, ArrayAccess, IteratorAggregate, Traversable and Generator are not declared. A class that implements one, or a parameter of one of these types, is the error E0303. The message names no replacement.
iterator_to_array, iterator_count, count, current, next, reset and array_walk are not functions. A call to one is the error E0320.
$obj[0] on an object is the error E0482, for a read and for a write. Only an array can be read with [ ].
A foreach loop over an object that implements neither Iterable<T> nor Iterator<T> is the error E0443. A method named getIterator does not change this. A loop never reads an object's properties.
Use this when you need full control
Section titled “Use this when you need full control”A generator is the short way to write an Iterator<T>. Write the class with advance() and
current() yourself when the cursor needs methods or properties of its own.
Do and don’t
Section titled “Do and don’t”- Do use a generator to read a large or endless list one value at a time.
- Do implement
Iterablewhen the same object must work in more than one loop. Each loop then gets a new cursor, so each loop starts at the first element. - Don’t loop twice over one generator. Call the method again to get a new one.
- Don’t write
$obj[0]to read an element of an object.[]works only on an array. Give the class a method that returns the element.
