Iteration

"for" loops

The usual way to iterate a collection is with a for loop.

main void() a nat[] = 1, 2, 3 for x in a log x

A for loop is an expression. It can be void, or return an output collection.

main void() a nat[] = 1, 2, 3 b nat[] = for x in a x * 10 log b

A type annotation after the for keyword types the entire for expression.

main void() a nat[] = 1, 2, 3 log for::nat[] x in a x * 10

A for loop can be squeezed onto one line using then.

main void() a nat[] = 1, 2, 3 log for::nat[] x in a then x * 10

for loops are a convenient syntax for calling a function named for-loop with a lambda.

main void() a nat[] = 1, 2, 3 log for-loop::nat[] a, of x then x * 10

If you want the collection indices too, use with-index.

main void() a string[] = "a", "b", "c" for index, value in with-index a log index, value

for? loops work like for loops, but the body can return an option. An empty option value will be ignored.
These call a function named for-option.

main void() a nat[] = 1, 2, 3, 4, 5 log for?::nat[] x in a if is-even x x * 10

There are also for* loops, which work like for loops, but the body returns an array that is flattened into the result.
These call a function named for-star.

main void() a nat[] = 1, 2, 3 log for*::nat[] x in a x, x

Ranges

nat types are iterable too. The number acts like a collection of all the numbers less than it.

main void() for x in 3::nat log x

ranges are also iterable (if the type in the range has a next function).

main void() for x in 1::nat .. 11 log x

You can reverse most iterable things.

main void() for x in 3::nat log x log "" for x in reverse 1::nat .. 11 log x

Iteration with early return

There is no early return from a for loop; it always iterates every element of the collection.

The most primitive iteration function is some which stops when the lambda returns true.

main void() a nat[] = 1, 2, 3 log some a, of x log "checking {x}" is-even x

A more general function is first. Here, the callback returns an option, and the first non-empty result is returned.

main void() a nat[] = 1, 2, 3 log first a, of x log "checking {x}" if is-even x x * 10

first works a lot like an until loop with a condition-body (see Loops); it keeps running the body until it gets a result.
Unlike an until loop, it can also stop running if it reaches the end of the collection, so it returns an option.