4. Control flow
So far every program ran from top to bottom, once. Real programs make decisions and repeat things. This chapter covers the statements that do that.
In this chapter you will learn:
ifandelsefor decisions,- loops:
while,do/while,forover ranges, collections and strings, and the C-stylefor, - how to leave or skip ahead in a loop, including from nested loops,
switchandmatchfor choosing among many cases, andmatchas an expression,deferfor clean-up code that must run when a block ends.
Decisions: if and else
fn main() {
let temperature = 31
if (temperature > 30) {
print("hot")
} else if (temperature > 15) {
print("mild")
} else {
print("cold")
}
}hotThe condition goes in parentheses and must be a bool. The branches are blocks in braces; braces are required even for one statement, which avoids a classic class of bugs where a second line looks like it belongs to the if but does not.
Grav checks the conditions one after another and runs the first branch whose condition is true. The else branch runs when none was.
For choosing between two values, the conditional operator is shorter than an if:
fn main() {
let items = 1
print("${items} ${items == 1 ? "item" : "items"}")
}1 itemWhen working out the value takes more than one expression, if itself can give a value. Each branch is an expression, or a block whose last line is the value; the else is required, since there must always be a value:
fn grade(score: int) -> string {
return if (score >= 90) "A" else if (score >= 75) "B" else "C"
}
fn main() {
let score = 82
let note = if (score >= 75) {
let margin = score - 75
"passed by ${margin}"
} else "try again"
print("${grade(score)}: ${note}")
}B: passed by 7Loops
while
while repeats its block as long as the condition is true. The condition is checked before each round, so the body may run zero times.
fn main() {
let n = 1
while (n < 100) {
n *= 3
}
print(n)
}243do / while
do { ... } while (condition) checks after each round, so the body always runs at least once. It suits "try, then decide whether to try again":
fn main() {
let attempts = 0
do {
attempts++
print("attempt ${attempts}")
} while (attempts < 3)
}attempt 1
attempt 2
attempt 3Counting with ranges
The most common loop counts through numbers. a..b is the range from a up to, but not including, b; a..=b includes b:
import "std"
fn main() {
for (i in 0..5) { printRaw("${i} ") }
print("")
for (i in 1..=5) { printRaw("${i} ") }
print("")
for (i in 0..=20 step 5) { printRaw("${i} ") }
print("")
for (i in 10..0 step -3) { printRaw("${i} ") }
print("")
}0 1 2 3 4
1 2 3 4 5
0 5 10 15 20
10 7 4 1 (printRaw from the standard library prints without a line break.)
stepchanges how much is added each time. A negative step counts down.- The loop variable (
i) is a new variable for the loop; it does not exist after it. - The start, end and step are worked out once, before the first round. Changing a variable used in them inside the loop does not change the loop.
Why does 0..5 exclude 5? Because it matches how indexes work: a list of 5 elements has indexes 0..5, and for (i in 0..xs.size()) visits each exactly once.
Looping over things: for-each
for (x in collection) visits each element in turn. It works with fixed arrays, the standard collections (Array, List, Deque and others), strings (each character), binary values (each byte) and variadic parameters:
import "std"
fn main() {
let primes = [2, 3, 5, 7]
let sum = 0
for (p in primes) { sum += p }
print(sum)
let names: Array<string> = ["Ada", "Grace", "Barbara"]
for (i, name in names) {
print("${i + 1}. ${name}")
}
for (ch in "hey") { print(ch) }
}17
1. Ada
2. Grace
3. Barbara
h
e
yThe two-name form for (i, x in xs) also gives the position of each element.
Maps, and pairs in general, can be taken apart in the loop header: for ((key, value) in map). See Structs, enums and tuples.
Your own classes work in a for-each loop too, in one of three ways:
- a
size()(orlength()) method and aget(i)(orat(i)) method: the loop counts through the positions; hasNext()andnext(): the object is an iterator, and the loop asks it for values untilhasNext()says false;- an
iterator()method that gives such an object, a new one for each loop.
An iterator suits values that have no position, or that are made as they are asked for, such as a linked list, the lines of a file, or a sequence with no end. The standard interfaces Iterator<T> and Iterable<T> name the last two ways (see iter); implementing them is optional, but lets a function take anything that can be walked:
import "std"
class Countdown implements Iterator<int> {
private n: int
constructor(n: int) { self.n = n }
fn hasNext() -> bool { return self.n > 0 }
fn next() -> int {
self.n -= 1
return self.n + 1
}
}
fn total(xs: Iterable<int>) -> int {
let sum = 0
for (x in xs) { sum += x }
return sum
}
fn main() {
for (x in new Countdown(3)) { print(x) }
let list = new LinkedList<int>()
list.add(10)
list.add(20)
print(total(list))
}3
2
1
30When a class has both, iterator() wins: get(i) on a linked list walks from one end each time, and on a map it takes a key rather than a position.
Generators: functions that yield
Writing an iterator class means keeping track, in fields, of where you are. A generator lets a function do it in its locals instead: a function that returns Iterator<T> and uses yield hands out one value at each yield, and carries on from there when the loop asks for the next:
import "std"
fn countdown(n: int) -> Iterator<int> {
while (n > 0) {
yield n
n -= 1
}
}
fn evens() -> Iterator<int> { // no end: the loop decides when to stop
let i = 0
while (true) {
yield i
i += 2
}
}
fn main() {
for (x in countdown(3)) { print(x) }
for (e in evens()) {
if (e > 6) { break }
print("even ${e}")
}
}3
2
1
even 0
even 2
even 4
even 6A bare return ends a generator early; a finally in it runs even when the loop stops early. Methods can yield too, and a generator can loop over another, which makes walking trees and other nested structures short. The body runs on a thread of its own, one step at a time with the loop, so each value costs a thread switch: use generators for values that come from files, sockets, queries or long computations, and plain loops for tight arithmetic. See generator.
The C-style for
The three-part loop from C is there too: a start statement, a condition checked before each round, and an update run after each round.
fn main() {
let total = 0
for (let i = 1; i <= 10; i++) {
total += i
}
print(total)
}55Prefer a range when you are counting; use this form when the update is unusual (doubling, following a linked list, two variables at once).
Leaving a loop early
break ends the loop at once. continue skips the rest of this round and goes on with the next one.
import "std"
fn main() {
for (i in 1..100) {
if (i % 2 == 0) { continue } // skip even numbers
if (i > 9) { break } // stop after 9
printRaw("${i} ")
}
print("")
}1 3 5 7 9 Labels: leaving nested loops
break and continue act on the innermost loop. To act on an outer one, give it a label, then name the label:
fn main() {
search: for (i in 0..5) {
for (j in 0..5) {
if (i * j == 6) {
print("found ${i} x ${j}")
break search // leaves both loops
}
if (j > i) { continue search }
}
}
}found 2 x 3Labels must be unique among the loops they are nested in, and break/continue must name a label of an enclosing loop. Clean-up code on the way out (defer, finally) still runs.
Choosing among many cases: switch and match
When one value decides between many branches, a chain of else ifs gets long. switch compares a value against each case in turn and runs the first that fits. match is another name for the same statement; use whichever reads better.
fn kind(day: string) -> string {
switch (day) {
case "sat", "sun": { return "weekend" }
case "fri": { return "almost weekend" }
default: { return "weekday" }
}
}
fn main() {
print(kind("sun"))
print(kind("fri"))
print(kind("tue"))
}weekend
almost weekend
weekday- A case can list several values separated by commas.
- Only the matching case runs. There is no "fall-through" into the next case, so there is no
breakto forget. defaultruns when no case fits.- The value can be an integer, a string, an enum, or a data enum.
A case body is everything from the colon up to the next case, default or the closing brace: one statement, several (on separate lines or split by ;), or a { block }. A case cannot be empty: where C would let case 1: case 2: fall through, write case 1, 2:.
Ranges and guards
A case can be a range of numbers (or strings). A guard, if condition before the colon, makes a case apply only when the condition is also true; otherwise the following cases are tried:
fn describe(n: int) -> string {
switch (n) {
case 0: { return "zero" }
case 1..10 if n % 2 == 0: { return "small and even" }
case 1..10: { return "small and odd" }
case 10..=99: { return "two digits" }
default: { return "big" }
}
}
fn main() {
print(describe(4))
print(describe(7))
print(describe(42))
print(describe(1000))
}small and even
small and odd
two digits
bigSwitching on enums
An enum is a type with a fixed set of named values (chapter 8). A switch over an enum without a default should handle every value: leaving one out is a warning that names it, which is how the compiler reminds you to update every switch when you add a new value.
enum Light { Red, Yellow, Green }
fn next(l: Light) -> Light {
switch (l) {
case Light.Red: { return Light.Green }
case Light.Green: { return Light.Yellow }
case Light.Yellow: { return Light.Red }
}
return l
}
fn main() {
print(next(Light.Red))
print(next(Light.Green))
}Green
YellowData enums, whose values carry extra data, are matched the same way and can bind that data to names (case Circle(r): ...). That is covered in chapter 8.
match as an expression
Where a value is expected, match picks one. Each case gives an expression instead of a block:
enum Size { Small, Medium, Large }
fn main() {
let n = 3
let word = match (n) { case 1: "one" case 2, 3: "a few" default: "many" }
print(word)
let s = Size.Medium
let price = match (s) {
case Size.Small: 2.5
case Size.Medium: 3.0
case Size.Large: 3.5
}
print(price)
}a few
3A match expression must always produce a value, so it needs a default unless its cases cover every value of an enum.
Clean-up with defer
Some code must run when a block ends, however it ends: closing a file, releasing a lock, printing a closing tag. defer schedules it right next to the code that made it necessary:
fn work(fail: bool) -> string {
print("open")
defer print("close") // runs last
defer { print("flush") } // runs first
if (fail) { return "failed" }
return "done"
}
fn main() {
print(work(false))
print(work(true))
}open
flush
close
done
open
flush
close
failed- Deferred code runs when the enclosing block is left: at its end, or through
return,breakorcontinue. - Several defers run in reverse order: the last one registered runs first, so things are undone in the opposite order they were done.
- In a
return, the value is computed first, then the deferred code runs. - A deferred block cannot itself
return,breakorcontinue. deferdoes not run when an exception leaves the block. For code that must run even then, usetry/finally(Errors).
Summary
if/else if/elseneedsboolconditions and braces.whilechecks first,do/whilechecks last.for (i in a..b)counts (..=includes the end,stepchanges the stride);for (x in xs)andfor (i, x in xs)walk collections, strings and iterators.breakandcontinuework on the innermost loop, or on a labeled one.switch/matchpicks one case, never falls through, and supports value lists, ranges, guards and enums;matchalso works as an expression.deferruns clean-up code, last-in first-out, when a block ends.
Exercises
- Print the numbers 1 to 30, but print
Fizzfor multiples of 3,Buzzfor multiples of 5 andFizzBuzzfor multiples of both. - Find the first number above 1000 that is divisible by 7, 11 and 13, using a
whileloop andbreak. - Print a right-angled triangle of
*with 5 rows using two nested range loops. - Write
fn season(month: int) -> stringwith aswitchon ranges (3..=5is spring, and so on). - Write a function that prints
start, then usesdeferto printend, and returns early from the middle. Check thatendis still printed.
Next: Functions →