We have been using the iterative for statement since the first chapters, to traverse ranges, lists and maps. This chapter explains what the statement does, and how to make it work with our own data; a function or a class of our own can take part in a for loop just like the built-in types.
Semantics of the Iterative for
Consider the following loop:
for var item in [10, 20, 30]
{
print(item)
}The for statement is built around the notion of an iterator. An iterator is just a function that takes no arguments and, each time it is called, returns the next value of a sequence. When the sequence is exhausted, the iterator must return nil.
We can observe an iterator directly. Lists, maps and ranges all have an iter method that creates a new one:
var next = [10, 20, 30].iter()
print(next()) // 10
print(next()) // 20
print(next()) // 30
print(next()) // nil
A for loop does nothing more than call the iterator repeatedly. Conceptually, the loop above is equivalent to:
var next = [10, 20, 30].iter()
var item = next()
while item != nil
{
print(item)
item = next()
}More precisely, the statement proceeds as follows.
First, it evaluates the expression after in exactly once. Then, it obtains an iterator from the resulting value:
- if the value is a function, the function itself is the iterator;
- otherwise, the value must have an
itermethod, which is called without arguments and whose result is the iterator. A value with neither raises an error.
Finally, it calls the iterator before each iteration. If the result is nil, the loop ends; otherwise the result is bound to the loop variable, and the body is executed. A break or continue statement alter the continuation of the loop, as usual.
Since every loop calls iter anew, each traversal of a collection has its own independent state. Two nested loops over the same list, for instance, do not interfere with each other.
What the Built-in Types Produce
The built-in types use the protocol in the way we would expect. A range produces its numbers, a list produces its items in order, and a map produces one [key, value] pair for each entry, in no particular order.
Several Loop Variables
A loop may declare more than one variable. In that case each value produced by the iterator must be a list, and its items are distributed among the variables with the same rules as a multi-variable declaration.
This is what makes the following idiomatic way of traversing a map possible:
var ages = {ada = 36, grace = 45}
for var name, age in ages
{
print("${name}: ${age}")
}The Role of nil
Because nil marks the end of the sequence, an iterator cannot produce nil as a value. A loop over [1, nil, 3] stops after the first item. When a sequence must be able to contain nil, the iterator can wrap each value in an object, like a list, which is never nil itself, and the loop can unpack it in several variables. We will use this technique in the example at the end of the chapter.
Writing Your Own Iterator
The description above translates directly into the two ways of creating iterators: by writing a function that returns an iterator, or by giving a class an iter method.
Iterator Functions
An iterator is an ordinary function, and its state is kept in the variables it closes over. A function that creates iterators is therefore basically just a closure factory, of the kind we saw in the chapter on functions:
function countdown(n)
{
return () => {
if n <= 0 { return nil }
var value = n
n -= 1
return value
}
}
for var i in countdown(3)
{
print(i) // 3, 2, 1
}Here countdown(3) returns a function, so the for statement uses it directly as the iterator. Each call decrements the captured variable n, until it reaches zero.
Nothing requires an iterator to end. A sequence can be infinite, in which case the loop should be left with a break, to avoid an infinite loop:
function naturals()
{
var n = 0
return () => {
n += 1
return n
}
}
for var n in naturals()
{
if n > 3 { break }
print(n) // 1, 2, 3
}Iterable Classes
To make instances of a class usable in a for loop, we define an iter method. It is called when the loop starts, and it must return an iterator function. Since it runs once per loop, it is the natural place to create the state of the traversal.
As an illustration, here is the stack that is traversed from the most recently pushed item down to the oldest, an order that a plain list does not give us directly:
class Stack
{
new()
{
self.items = []
}
function push(value)
{
self.items.add(value)
}
function iter()
{
var items = self.items
var i = items.len - 1
return () => {
if i < 0 { return nil }
var item = items[i]
i -= 1
return item
}
}
}
var s = Stack.new()
s.push("first")
s.push("second")
s.push("third")
for var item in s
{
print(item) // third, second, first
}The position i is a local variable of iter, captured by the returned function. Each call to iter creates a fresh i, which is why two loops over the same stack run independently.
An Example
When iteration yields several values at a time, the pair travels as a list, and the loop header names its parts. The following program uses this to define two small iterator functions that are common in other languages. enumerate pairs each item of a list with its position, and zip walks two lists in parallel, stopping when the shorter one ends:
function enumerate(list)
{
var i = 0
return () => {
if i >= list.len { return nil }
var pair = [i, list[i]]
i += 1
return pair
}
}
function zip(a, b)
{
var i = 0
return () => {
if i >= a.len or i >= b.len { return nil }
var pair = [a[i], b[i]]
i += 1
return pair
}
}
var names = ["Ada", "Grace", "Linus"]
var langs = ["Analytical Engine", "COBOL", "C"]
for var i, name in enumerate(names)
{
print("${i}: ${name}")
}
for var name, lang in zip(names, langs)
{
print("${name} -> ${lang}")
}$ tea pairs.tea
0: Ada
1: Grace
2: Linus
Ada -> Analytical Engine
Grace -> COBOL
Linus -> C
Both iterators return a new two-item list at each step, so the end of the sequence is still signaled by a single nil, while the values inside the pair are free to be anything, nil included.
This chapter closes the part of the guide dedicated to the language itself. The following chapters describe how Teascript can be embedded into, and extended from, programs written in C.