Learn Tin · Part 1: The language · Chapter 4
Control flow
if, loops and ranges. Most things are expressions.
Choosing with if
if runs a block when a condition is true. else if and else handle
the other cases. The condition needs no parentheses, but the braces are always required.
tin run if.tinfn main() {
let temperature = 31
if temperature > 30 {
print("hot")
} else if temperature > 15 {
print("mild")
} else {
print("cold")
}
} hot if has a value
With an else, an if is an expression: it produces the value of whichever branch ran.
That replaces the ?: operator from other languages, and it works inside strings too.
tin run if-value.tinfn main() {
let stock = 0
// with an else, if is an expression: it has a value
let label = if stock == 0 { "sold out" } else { "{stock} left" }
print(label)
print("We have {if stock > 0 { "some" } else { "none" }}.")
} sold out
We have none. A condition must be a bool. There are no "truthy" values: a number or a string is never true
on its own. Say what you mean, such as items > 0:
tin check no-truthy.tinfn main() {
let items = 3
if items {
print("not empty")
}
} error: expected bool, found int
--> no-truthy.tin:3:6
|
3 | if items {
| ^^^^^ Repeating with while
while repeats its block as long as the condition holds.
tin run while.tinfn main() {
var n = 1
while n < 100 {
n = n * 2
}
print("first power of two from 100: {n}")
} first power of two from 100: 128 Counting with for
for i in a..b counts from a up to, but not including, b. So
0..3 is 0, 1, 2, and 1..101 is 1 to 100.
tin run for-range.tinfn main() {
for i in 0..3 { // 0, 1 and 2: the end is not included
print("lap {i}")
}
var total = 0
for n in 1..101 {
total += n
}
print("1 + 2 + ... + 100 = {total}")
} lap 0
lap 1
lap 2
1 + 2 + ... + 100 = 5050 for also walks the items of a list. Add a second name to get each item's position too.
(Lists get their own chapter later. For now, […] is a list.)
tin run for-items.tinfn main() {
for word in ["red", "green", "blue"] {
print(word.upper())
}
for i, word in ["red", "green", "blue"] { // with the position, from 0
print("{i}: {word}")
}
} RED
GREEN
BLUE
0: red
1: green
2: blue Skipping and stopping
continue jumps to the next round of the loop. break leaves the loop.
tin run break-continue.tinfn main() {
for n in 1..20 {
if n % 3 != 0 { continue } // skip to the next n
if n > 10 { break } // leave the loop
print(n)
}
} 3
6
9 loop repeats forever, until a break or return. Use it when the stopping
point is easiest to decide in the middle of the work.
tin run loop.tinfn main() {
// loop runs until a break (or a return)
var guess = 1.0
var steps = 0
loop {
guess = (guess + 2.0 / guess) / 2.0 // Newton's method for the square root of 2
steps += 1
if steps == 5 { break }
}
print("sqrt(2) is about {guess.fixed(6)} after {steps} steps")
} sqrt(2) is about 1.414214 after 5 steps Blocks are expressions
This is the rule from the last chapter, applied everywhere. Any { … } block has a value: its
last line. Names you make inside it don't leak out.
tin run block-value.tinfn main() {
// a block { } is an expression too: its value is its last line
let area = {
let width = 3
let height = 4
width * height
}
print(area)
} 12 Tasks
●○○ Task 1: FizzBuzz
Print the numbers 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of
5 and FizzBuzz for multiples of both. Try to use one print and an if
expression.
Solution
tin run task-1.solution.tinfn main() {
for n in 1..16 {
let line = if n % 15 == 0 { "FizzBuzz" }
else if n % 3 == 0 { "Fizz" }
else if n % 5 == 0 { "Buzz" }
else { "{n}" }
print(line)
}
} 1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz ●●○ Task 2: Sum of digits
Write digitSum(number: int): int that adds the digits of a number: 2026 gives
10. Hint: n % 10 is the last digit and n / 10 drops it.
Solution
tin run task-2.solution.tinfn digitSum(number: int): int {
var n = number
var sum = 0
while n > 0 {
sum += n % 10
n = n / 10
}
sum
}
fn main() {
print(digitSum(2026))
print(digitSum(99999))
} 10
45 ●○○ Task 3: A staircase
Print four lines: *, **, *** and ****.
Solution
tin run task-3.solution.tinfn main() {
for row in 1..5 {
print("*".repeat(row))
}
} *
**
***
**** What's next
Next: Structs and methods. Group values into a type and give it methods.
In the reference: Control flow