while
while cond { ... } evaluates cond and runs its block as long as it is true. Its type is void, or never for a while true with no break.
Details
- The condition is evaluated before each iteration, so a condition that starts
falseruns the block zero times. It must be abool; there is no truthiness. while truewith nobreakin its body has typenever: onlyreturnor a panic leaves it. With abreak, its type isvoid.- After a
whilewhose body has nobreak, the complement of the condition holds, sowhile x == null { ... }leavesxwithoutnullbelow the loop. - An assignment anywhere in the body cancels a narrowing from before the loop, from the loop head on.
- A record or map literal in the condition must be parenthesized, since its
{would otherwise begin the body.
Basic examples
Count down while a counter is positive:
var n = 3
while n > 0 {
println(n)
n -= 1
}
println("liftoff")3
2
1
liftoffTake work from a queue until it is empty:
let queue = ["fetch", "parse", "save"]
while !queue.isEmpty() {
let job = queue.removeAt(0)
println("running ${job}")
}running fetch
running parse
running saveScope
A condition that starts false
The block runs zero times:
var n = 0
while n > 0 {
println(n)
n -= 1
}
println("done")donewhile true
A while true loop with no break has type never, so it can end a function that returns a value. The function leaves through return:
func isPrime(n: int): bool {
if n < 2 { return false }
var d = 2
while d * d <= n {
if n % d == 0 { return false }
d += 1
}
true
}
func nextPrime(after: int): int {
var n = after + 1
while true {
if isPrime(n) { return n }
n += 1
}
}
println(nextPrime(10))
println(nextPrime(13))11
17Run the body at least once
Ant has no do, so a loop that runs its body at least once puts the test at the end of a while true body. The break makes the loop's type void:
var n = 0
while true {
n += 1
println(n)
if n >= 3 { break }
}1
2
3Narrowing after the loop
The loop ends only when its condition is false, so below a loop with no break, reading is an int:
var reading: int | null = null
var tries = 0
while reading == null {
tries += 1
if tries == 3 { reading = 42 }
}
println(reading + 1)43Walking a linked structure
while node != null narrows node inside the body, and the body moves it along:
type Node = { value: int, next: Node | null }
func sum(head: Node | null): int {
var node = head
var total = 0
while node != null {
total += node.value
node = node.next
}
total
}
let list = Node{ value: 1, next: Node{ value: 2, next: Node{ value: 3, next: null } } }
println(sum(list))
println(sum(null))6
0continue and break
continue goes back to the condition, and break leaves the loop. Advance the counter before a continue, or the loop sees the same element again:
let xs = [4, -1, 0, 7, -3, 9]
var i = 0
while i < xs.length() {
let x = xs[i]
i += 1
if x < 0 { continue }
if x == 0 { break }
println(x)
}4Applications
Greatest common divisor
Euclid's algorithm runs until the remainder is zero:
func gcd(a: int, b: int): int {
var x = a
var y = b
while y != 0 {
let r = x % y
x = y
y = r
}
x
}
println(gcd(48, 18))
println(gcd(17, 5))6
1Binary search
The range to search shrinks until it is empty:
func search(xs: Array[int], target: int): int | null {
var lo = 0
var hi = xs.length()
while lo < hi {
let mid = (lo + hi) / 2
if xs[mid] == target { return mid }
if xs[mid] < target {
lo = mid + 1
} else {
hi = mid
}
}
null
}
let primes = [2, 3, 5, 7, 11, 13]
println(search(primes, 7))
println(search(primes, 4))3
nullRead input to the end
readLine returns null at the end of input, and ?? break leaves the loop there:
let input = Os.stdin()
var total = 0
while true {
let line = try input.readLine() ?? break
total += line.toInt() ?? 0
}
println(total)12Properties and relations
A while with a counter visits the same numbers as a for over Iter.range:
let viaWhile: Array[int] = []
var i = 0
while i < 5 {
viaWhile.push(i)
i += 1
}
let viaFor: Array[int] = []
for j in Iter.range(0, 5) {
viaFor.push(j)
}
assert(viaWhile == viaFor)When the loop goes over a collection or a range, prefer for: it cannot forget the step.
After a loop with no break, its condition is false:
var n = 37
var steps = 0
while n != 1 {
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 }
steps += 1
}
assert(n == 1)
assert(steps == 21)Possible issues
The condition must be a bool
An int is not a condition. Compare it:
var n = 3
while n { // error: cannot use int where bool is expected
n -= 1
}Write while n > 0 instead.
A record literal in the condition
The { of a record literal would begin the body, so the checker asks for parentheses:
type Point = { x: int, y: int }
var p = Point{ x: 0, y: 0 }
while p != Point{ x: 3, y: 0 } { // error: a record or map literal in the while header must be parenthesized
p.x += 1
}Write while p != (Point{ x: 3, y: 0 }).
An assignment in the body cancels a narrowing
A guard narrows item to int, but the body assigns it a value that may be null, so the narrowing does not reach the condition:
let stock = Map{ tea: 3 }
var item: int | null = stock.get("tea")
if item == null { panic("no tea") }
while item > 0 { // error: > needs both operands of one type, got int | null and int
item = stock.get("rice")
}A break undoes the narrowing after the loop
With a break, the loop can end while the condition still holds, so nothing narrows below it:
var reading: int | null = null
var tries = 0
while reading == null {
tries += 1
if tries == 3 { reading = 42 }
if tries > 10 { break }
}
println(reading + 1) // error: + needs both operands of one type, got int | null and intTest reading again after the loop, or use reading ?? 0.
A while true with break has type void
A break makes the loop's type void, so it no longer ends a function that returns a value:
func firstPowerOver(limit: int): int {
var n = 1
while true { // error: cannot use void where int is expected
n *= 2
if n > limit { break }
}
}Return the value from inside the loop instead: if n > limit { return n }.
A loop that never ends
A while stops only when its condition changes. A continue placed before the step, or a step that never reaches the end, keeps the loop running forever. Put the step first, as in the continue example above, or use for over a collection or a range.
