for
for x in e { ... } runs its block once for each element of e: an array, a map, a set, a string, Bytes, or a sequence function. The loop is a statement of type void.
Details
- Each iteration binds a fresh
let. A closure made in the body keeps that iteration's value, and assigning the loop variable is a compile error. - A map is visited as
Entryrecords and a set as its members, both in insertion order. A string yields each code point as a one-character string, andBytesyields eachbyte. - An array is read by index while the index is below its current length, so elements pushed during the loop are visited. Entries added to a map or a set during the loop are visited too.
- The left side may be a destructuring instead of a name. An array destructuring panics when an element has fewer elements than its fixed positions.
breakleaves the loop,continuegoes on with the next element, andreturnortryin the body leave the function the loop is in.
Basic examples
Visit each element of an array, in order:
let names = ["Ann", "Bob", "Cid"]
for name in names {
println("Hello, ${name}")
}Hello, Ann
Hello, Bob
Hello, CidDestructure each Entry of a map into its key and value:
let ages = Map{ "Ann": 31, "Bob": 27 }
for { key, value } in ages {
println("${key} is ${value}")
}Ann is 31
Bob is 27Count with a range from Iter.range, which excludes its end:
for i in Iter.range(0, 3) {
println(i)
}0
1
2Scope
Collections
Without destructuring, a map yields whole Entry records:
let stock = Map{ tea: 3, rice: 0 }
for entry in stock {
println(entry)
}Entry{ key: "tea", value: 3 }
Entry{ key: "rice", value: 0 }A set yields its members in the order they were first added; a repeated value is a member once:
let tags = Set.of(["red", "blue", "red", "green"])
for tag in tags {
println(tag)
}red
blue
greenA string yields one-character strings, one per code point:
for c in "añb" {
println("[${c}]")
}[a]
[ñ]
[b]Bytes yields each byte:
for b in "hi".toBytes() {
println(b)
}104
105An empty collection runs the block zero times:
let none: Array[int] = []
for n in none {
println(n)
}
println("done")doneDestructuring
A record destructuring binds the named fields; { field: name } renames one, and fields not mentioned are ignored:
type Point = { x: int, y: int, label: string }
let points = [Point{ x: 1, y: 2, label: "a" }, Point{ x: 3, y: 4, label: "b" }]
for { x: px, y: py } in points {
println(px * py)
}2
12An array destructuring binds by position. _ discards one, and ...rest binds what is left as a new array:
let rows = [["ann", "31", "Oslo"], ["bob", "27", "Rome"]]
for [name, _, city] in rows {
println("${name}: ${city}")
}
for [name, ...rest] in rows {
println("${name} has ${rest.length()} more")
}ann: Oslo
bob: Rome
ann has 2 more
bob has 2 moreArray.entries pairs each element with its index, for a loop that needs both:
for { index, value } in ["tea", "rice"].entries() {
println("${index + 1}. ${value}")
}1. tea
2. riceDestructurings nest:
type Customer = { name: string, city: string }
type Order = { id: int, customer: Customer }
let orders = [Order{ id: 7, customer: Customer{ name: "Ann", city: "Oslo" } }]
for { id, customer: { city } } in orders {
println("order ${id} ships to ${city}")
}order 7 ships to OsloSequences
A Seq[T] is a function that calls yield once per element. for runs the body at each call, and yield returns false after a break, so the sequence can stop:
func countdown(from: int): Seq[int] {
func(yield: func(int): bool) {
var n = from
while n > 0 {
if !yield(n) {
println("stopped at ${n}")
return
}
n -= 1
}
}
}
for n in countdown(5) {
if n == 3 { break }
println(n)
}5
4
stopped at 3The Iter functions build sequences lazily, so a pipe in the loop head computes only what the loop visits:
for n in Iter.range(1, 1000) | Iter.filter({ x % 7 == 0 }) | Iter.take(3) {
println(n)
}7
14
21Channel.values yields what a channel receives until it is closed:
let jobs: Channel[string] = Channel.new(capacity: 2)
jobs.send("build")
jobs.send("test")
jobs.close()
for job in jobs.values() {
println("running ${job}")
}running build
running testClosures
Each iteration has its own binding, so a closure made in the body keeps its own value:
let actions: Array[func(): string] = []
for name in ["Ann", "Bob"] {
actions.push({ "hi ${name}" })
}
println(actions.map({ x() }))["hi Ann", "hi Bob"]Leaving the loop
continue skips to the next element and break ends the loop:
for n in [1, -2, 3, 0, 5] {
if n < 0 { continue }
if n == 0 { break }
println(n)
}1
3In nested loops, break and continue act on the innermost loop. Ant has no labels:
for row in [[1, 2, 0, 4], [5, 0, 6]] {
for n in row {
if n == 0 { break }
println(n)
}
println("next row")
}1
2
next row
5
next rowTo leave both loops, put them in a function and use return.
return in the body leaves the enclosing function, and the loop with it:
type Task = { name: string, done: bool }
func firstOpen(tasks: Array[Task]): string {
for task in tasks {
if !task.done { return task.name }
}
"all done"
}
println(firstOpen([Task{ name: "a", done: true }, Task{ name: "b", done: false }]))
println(firstOpen([]))b
all doneArray.find gives the same result; the loop pays off when the body does more than test.
Applications
Parse every line and stop at the first failure. try in the body leaves the function from inside the loop:
func parseLine(line: string): Result[int, Error] {
let n = line.toInt() ?? return Result.fail("not a number: ${line}")
Result.ok(n)
}
func parseAll(lines: Array[string]): Result[Array[int], Error] {
let out: Array[int] = []
for { index, value: line } in lines.entries() {
out.push(try (parseLine(line) | Result.wrapErr("line ${index + 1}")))
}
Result.ok(out)
}
println(parseAll(["1", "2", "3"]))
println(parseAll(["1", "x", "3"]))Ok{ value: [1, 2, 3] }
Err{ error: Error{ message: "line 2: not a number: x" } }Build a map of counts, updating one entry per element:
let words = "the cat and the hat".split(" ")
let counts: Map[string, int] = Map{}
for word in words {
counts[word] = (counts.get(word) ?? 0) + 1
}
println(counts)Map{ "the": 2, "cat": 1, "and": 1, "hat": 1 }Process a work queue that grows while the loop runs. Pushed elements are visited:
let children = Map{ root: ["src", "docs"], src: ["lib"] }
let queue = ["root"]
for name in queue {
queue.extend(children.get(name) ?? [])
}
println(queue)["root", "src", "docs", "lib"]Properties and relations
A loop that pushes each element into a new array copies the array, in order:
let xs = [3, 1, 2]
let copy: Array[int] = []
for x in xs {
copy.push(x)
}
assert(copy == xs)A loop over a map visits the entries in the order Map.entries returns them:
let m = Map{ b: 2, a: 1, c: 3 }
let seen: Array[Entry[string, int]] = []
for e in m {
seen.push(e)
}
assert(seen == m.entries())A loop over a string visits as many one-character strings as String.length counts:
let s = "héllo"
var n = 0
for c in s {
assert(c.length() == 1)
n += 1
}
assert(n == s.length())Possible issues
The loop variable is a let. Assigning it would not change the array, so the checker rejects it:
let xs = [1, 2, 3]
for x in xs {
x = x * 2 // error: cannot assign to x, a for variable; declare a var to hold a value that changes
}To change the elements, use Array.map for a new array, or assign by index through Array.entries.
An array destructuring panics when an element is too short, as indexing past the end does:
let pairs = [[1, 2], [3]]
for [a, b] in pairs { // panic: a destructuring needs 2 elements, got 1
println(a + b)
}3for needs the collection itself, not a value that may be null. Handle null first:
func total(prices: Array[int] | null): int {
var sum = 0
for p in prices { // error: for needs an array, a map, a set, a string, Bytes, or a sequence, got Array[int] | null
sum += p
}
sum
}A guard such as if prices == null { return 0 } before the loop narrows prices to Array[int].
A string yields code points, not the characters a reader sees. An accented letter written with a combining mark is two iterations; String.graphemes gives what a reader sees as characters:
let word = "e\u{301}"
var steps = 0
for c in word {
steps += 1
}
println(steps)
println(word.graphemes().length())2
1Pushing to the array being visited, on every iteration, never ends the loop. Push only while a condition holds, as the work queue in Applications does, or loop over a copy.
See also
while · break · continue · let · var · Iter.range · Seq · Array.entries · Map.entries · Channel.values · String.graphemes
