Control flow
Conditions and loops take no parentheses around the condition, and their body always has braces.
#If
let temperature = 23
if temperature > 30 {
println("hot")
} else if temperature > 15 {
println("nice")
} else {
println("cold")
}nice
#If as an expression
if gives a value: the last expression of the branch that ran. Then it needs an else.
let a = 4
let b = 9
let bigger = if a > b { a } else { b }
println(bigger)
fn sign(n: Int): String = if n > 0 { "positive" } else if n < 0 { "negative" } else { "zero" }
println(sign(-3))9 negative
#Match
match compares a value against patterns, and is also an expression. It has its own page: Pattern matching.
fn label(code: Int): String = match code {
200 -> "OK"
404 -> "Not found"
500..<600 -> "Server error"
_ -> "Something else"
}
println(label(404))
println(label(503))Not found Server error
Without a value, match checks conditions from top to bottom, like a chain of ifs:
let n = 15
let text = match {
n % 15 == 0 -> "FizzBuzz"
n % 3 == 0 -> "Fizz"
n % 5 == 0 -> "Buzz"
_ -> "{n}"
}
println(text)FizzBuzz
#For loops
for goes over anything you can iterate: ranges, lists, strings and maps.
for i in 1..3 {
println("round {i}")
}
for name in ["Ada", "Grace"] {
println(name)
}round 1 round 2 round 3 Ada Grace
#Ranges
| Range | Numbers |
|---|---|
0..5 | 0, 1, 2, 3, 4, 5 (including the end) |
0..<5 | 0, 1, 2, 3, 4 (up to the end) |
(0..20).step(5) | 0, 5, 10, 15, 20 |
(1..3).reversed() | 3, 2, 1 |
for i in (1..5).reversed() { print("{i} ") }
println()5 4 3 2 1
#Index and value
With two names, a for over a list gives the index too, and over a map the key and the value:
let colors = ["red", "green", "blue"]
for i, color in colors {
println("{i}: {color}")
}
let ages = ["Ada": 36, "Linus": 54]
for name, age in ages {
println("{name} is {age}")
}0: red 1: green 2: blue Ada is 36 Linus is 54
Use _ for a value you don't need: for _ in 1..3 { ... }.
#While loops
var n = 27
var steps = 0
while n != 1 {
n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 }
steps += 1
}
println("{steps} steps")111 steps
#Break and continue
break leaves the loop; continue goes on with the next round.
for i in 1..10 {
if i % 2 == 0 { continue }
if i > 7 { break }
print("{i} ")
}
println()1 3 5 7
#Return
return leaves a function, with a value if the function returns one. In a function with = expression there's no return: the expression is the value.
fn firstNegative(numbers: List<Int>): Int? {
for n in numbers {
if n < 0 { return n }
}
return null
}
println(firstNegative([3, -1, -5]))
println(firstNegative([1, 2]))-1 null
A lambda can't return; its value is its last expression. See Lambdas.
#Repeating something
n.repeat { } runs a block n times, with the round's number as it:
3.repeat { println("Hip hip hooray #{it + 1}") }Hip hip hooray #1 Hip hip hooray #2 Hip hip hooray #3