Loops#
for / in visits collection values; while repeats while a Bool condition holds. break ends the loop; continue starts the next iteration. Loop over a collection when you already have the values, over a range when you need a count, and with while when the next step depends on a condition. A custom type can be iterable by implementing the standard Iterator interface (Iterators
).
Traversing a list#
fn sum(values List[Int]) Int {
var total = 0
for value in values {
total += value
}
return total
}Counting loops#
start..end includes start, excludes end, and counts up by one; it needs no import. The bounds are Int values. Arithmetic binds first, so 0..n + 1 means 0..(n + 1); ranges cannot be chained. A for over start..end counts directly without allocating a list.
import panic from "@std/core.ms"
test "sum indexes" {
var total = 0
for index in 0..5 {
total += index
}
if total != 10 {
return panic(f"Expected 10, got {total}")
}
}end <= start visits nothing. Bounds are evaluated once, in order, before the first iteration. As a plain value, (0..count) is a List[Int]; over 268,435,456 items faults, so use range_by with RangeOptions(max_items:) for larger lists.
Use while with a counter for other steps or computed exits:
import panic from "@std/core.ms"
test "five iterations" {
var index = 0
var total = 0
while index < 5 {
total += index
index += 1
}
if index != 5 or total != 10 {
return panic("Expected five iterations and total 10")
}
}Increment the counter before any continue that would skip its update.
Stepped ranges#
range_by(start, end, step, RangeOptions(max_items: n)) returns List[Int]!. Negative steps count down: range_by(start: 5, end: 0, step: -2) is [5, 3, 1]. Equal endpoints or a step away from the end give an empty list. step: 0 is "EINVAL"; exceeding max_items is "EOVERFLOW". Unwrap the Result before looping:
import (
range_by from "@std/collections/collections.ms",
expect_equal from "@std/test/test.ms",
)
test "sum even indexes" {
indexes := range_by(start: 0, end: 6, step: 2)?
var total = 0
for index in indexes {
total += index
}
expect_equal(total, 6)?
}? unwraps the range in a function or test whose error type is compatible; get_or([]) supplies a fallback. Use range_by for steps; .. has no step form. See the range_by declaration
.
Iterable types and binding#
The iterable is evaluated once. Traversal borrows the collection for the loop body; mutating, reassigning, or moving that collection while the borrow is live is rejected. The loop variable is one immutable name per iteration, or a list or record pattern (see Destructuring the element ); it takes no annotation. Supported iterables:
| Iterable | Iteration binding type | Traversal order |
|---|---|---|
List[T] | T | Position order |
Set[T] | T | Insertion order |
Map[K, V] | MapEntry[K, V] | Key insertion order |
Iterator[T] implementation | T | Order of next() results |
MapEntry[K, V] is a record with key K and value V. Iterating needs no import; only constructing one does (@std/collections/collections.ms). It is a record rather than a positional pair, so destructure it with {key, value} rather than [key, value]. The entry is borrowed from the map, not copied.
for e in m.entries(), m.values() and m.keys() visit the map directly, without building a list, when the body does not change the map. When the body does change the map, the list is built first, so the loop sees the entries as they were.
fn total(values Map[String, Int]) Int {
var sum = 0
for entry in values {
{key: _key, value} := entry
sum += value
}
return sum
}for [key, value] in values { ... } is a type error: a MapEntry is a record, so write for {key, value} in values { ... }. Numbers, text, optionals, functions, and types without a next method of the Iterator shape are not iterable.
Each iteration has a new scope. Assigning to the loop variable is rejected, but an outer var can change.
Destructuring the element#
A list or record pattern after for binds the same names as := does with the element, so for [a, b] in pairs { ... } is for pair in pairs { ... } followed by [a, b] := pair. The element is borrowed, the names are scoped to the body, and a pattern that does not fit the element type is rejected as it is after :=. A closure parameter takes the same patterns: pairs.map(([a, b]) => a + b).
import expect_equal from "@std/test/test.ms"
test "destructure each element" {
var total = 0
for [a, b] in [[1, 2], [3, 4]] {
total += a * b
}
expect_equal(total, 14)?
var names = ""
for {key, value: _value} in {"x": 1, "y": 2} {
names = f"{names}{key}"
}
expect_equal(names, "xy")?
}Iterators#
A type that implements Iterator[T] from @std/core.ms is iterable. for item in source { ... } calls source.next() until it returns null, binding each T as the owned result of next (var fn next() T?). It behaves like while true { ... } with if item := source.next() { ... } else { break }, so break, continue and return work as in any loop.
A variable or field path is advanced in place and must be declared var; any other expression (a call, say) is held by the loop alone. After the loop, an in-place iterator keeps its final state, which is how LineReader.error() reports why reading stopped.
import Iterator from "@std/core.ms"
type Countdown {
left Int
}
fn var Countdown.next() Int? {
if self.left == 0 {
return null
}
self.left -= 1
return self.left + 1
}
fn main() Void {
for n in Countdown(3) {
print(n)
}
}Output:
3
2
1Walking a Deque, Queue or PriorityQueue#
These containers are not iterable. Walk one by position with length() and get(index), which returns an optional (null when out of range, negative indexes count from the end):
import Deque from "@std/collections/deque.ms"
fn main() Void {
var steps = Deque[Int]()
steps.push_back(11)
steps.push_back(12)
for index in 0..steps.length() {
step := steps.get(index)
if step != null { print(step) }
}
}Output:
11
12Repeating while a condition holds#
fn count_down(start Int) Int {
var remaining = start
while remaining > 0 {
remaining -= 1
}
return remaining
}while re-tests its condition before every iteration, including after continue. An empty iterable or initially false condition runs no body.
Exiting an iteration#
break and continue target the nearest enclosing loop in the same function body, take no labels or arguments, and are rejected outside a loop; an anonymous function cannot break its enclosing loop. return exits the function.
Each of the three runs cleanup for the scopes it exits. Each iteration is its own scope, so a resource bound in the body closes when the iteration ends; a binding that is not a resource registers no cleanup. See lexical cleanup .
Cancellation#
A promise is cancelled at its next wait, so a loop that never waits is not stopped by cancellation or a timeout. Wait inside the loop, or return. Lint rule MSL111 flags a while true loop in a module that imports @std/concurrency/promise.ms when its body neither waits nor exits.