Sn Tin

Learn Tin · Part 1: The language · Chapter 2

Values and types

let, var, numbers, strings and how Tin infers types.

Naming values: let and var

let gives a value a name for good. var makes a variable you can change later. Start with let; switch to var when you really need to change something.

let-var.tintin run let-var.tin
fn main() {
  let name = "Tin"       // let: this name always means this value
  var score = 10         // var: this one can change
  score = score + 5
  score += 1
  print("{name} scored {score}")
}
Tin scored 16

score += 1 is short for score = score + 1. Changing a let is an error, and the compiler tells you the fix:

let-reassign.tintin check let-reassign.tin
fn main() {
  let score = 10
  score = 11
}
error: 'score' is immutable
 --> let-reassign.tin:3:3
  |
3 |   score = 11
  |   ^^^^^
  = note: declare it with `var score = ...` to allow reassignment
  = fix: declare score with var

Lines marked fix: are edits the compiler can make for you. Run tin fix file.tin and it changes let to var.

The basic types

Every value has a type. You rarely need to write it: Tin works it out from the value. That is called type inference.

types.tintin run types.tin
fn main() {
  let year = 2026          // int: a whole number
  let price = 4.5          // float: a number with a fractional part
  let open = true          // bool: true or false
  let city = "Lisbon"      // string: text
  print("{year} {price} {open} {city}")

  let count: int = 3       // you can write the type when it helps a reader
  let ratio: float = 2     // a whole-number literal can be a float
  print("{count} {ratio}")
}
2026 4.5 true Lisbon
3 2.0

Once a name has a type, it keeps it. Putting a value of another type in it is an error, caught before the program runs:

wrong-type.tintin check wrong-type.tin
fn main() {
  let count: int = 2.5
}
error: expected int, found float
 --> wrong-type.tin:2:20
  |
2 |   let count: int = 2.5
  |                    ^^^
  = note: convert with int(x)
  = fix: wrap it in int(...)

Numbers

There are two everyday number types: int for whole numbers and float for numbers with a fraction. Dividing two ints gives an int.

numbers.tintin run numbers.tin
fn main() {
  print(7 / 2)              // int / int is integer division
  print(7 % 2)              // the remainder
  print(7.0 / 2.0)
  let n = 7
  print(float(n) / 2)       // convert first to get a fraction
  print(int(3.9))           // int() drops the fraction
  print((2.0 / 3.0).fixed(2))
}
3
1
3.5
3.5
3
0.67

Tin never mixes them silently. Multiplying an int by a float is an error until you say which one you mean. This seems strict at first, but it is also why Tin never rounds your numbers without you noticing.

no-mixing.tintin check no-mixing.tin
fn main() {
  let items = 3
  let price = 4.5
  print(items * price)
}
error: '*' needs both sides to have the same type, found int and float
 --> no-mixing.tin:4:9
  |
4 |   print(items * price)
  |         ^^^^^^^^^^^^^
  = note: Tin never converts numbers silently: use float(x) or int(x)
  = fix: wrap it in float(...)

How big can an int be?

An int is 32 bits: it goes up to 2,147,483,647. Going past that doesn't wrap around to a negative number like in C, and it doesn't quietly turn into a float like in JavaScript. The program stops with a panic, an error at run time:

overflow.tintin run overflow.tin
fn main() {
  var big = 2147483647      // the largest int
  print("about to add one")
  print(big + 1)
}
about to add one
panic: integer overflow

For bigger whole numbers, such as byte counts or timestamps in nanoseconds, use i64. You create one with i64(…), and it never mixes with int either:

i64.tintin run i64.tin
fn main() {
  let big = i64(2147483647) + i64(1)
  print(big)
  let bytes = i64(3) * i64(1024) * i64(1024) * i64(1024)
  print("3 GiB is {bytes} bytes")
}
2147483648
3 GiB is 3221225472 bytes

Strings

Strings hold text. + joins two strings, and methods are called with a dot.

strings.tintin run strings.tin
fn main() {
  let word = "tin"
  print(word.upper())
  print(word + " can")                // + joins two strings
  print("{word} has {word.len} letters")
  print("  spaced  ".trim())
  print("a,b,c".split(","))
  print("ha".repeat(3))
  print(word.contains("in"))
}
TIN
tin can
tin has 3 letters
spaced
["a", "b", "c"]
hahaha
true

len counts bytes, not letters. For plain English text they are the same, but "é".len is 2. Keep this in mind when you work with text in other languages.

A hole can say how to format its value after a colon: {price:.2} for 2 decimals, {n:>4} for a width of 4, {n:04} to pad with zeros:

format.tintin run format.tin
fn main() {
  let price = 3.14159
  print("price: {price:.2}")               // 2 decimals
  print("[{7:>4}] [{7:04}] [{"ok":<4}]")   // a width, zeros, left-aligned
  let rows = [("tea", 2.5), ("coffee", 13.0)]
  for r in rows {
    print("{r.0:<8}{r.1:>7.2}")            // a little table
  }
}
price: 3.14
[   7] [0007] [ok  ]
tea        2.50
coffee    13.00

When you need the characters themselves, s.chars() gives them as char values. A char is one character in single quotes; text in double quotes is always a string:

chars.tintin run chars.tin
fn main() {
  let word = "héllo"
  print(word.len)                          // 6 bytes: é takes two
  let letters = word.chars()               // the characters, as char values
  print(letters.len)                       // 5 characters
  print(letters)
  let first = letters[0]                   // a char is written in single quotes: 'h'
  print(first == 'h')
  print(first.upper())
  print(int('A'))                          // its code point
  print(char(66))
}
6
5
['h', 'é', 'l', 'l', 'o']
true
H
65
B
char-vs-string.tintin check char-vs-string.tin
fn main() {
  let first = "hello".chars()[0]
  print(first == "h")
}
error: '==' compares a char with a string
 --> char-vs-string.tin:3:9
  |
3 |   print(first == "h")
  |         ^^^^^^^^^^^^
  = note: a char is written in single quotes: 'a'; or turn the char into text with str(c)
  = fix: use the char 'h'

A char and a string are different types. The fix writes 'h'.

True or false

A bool is true or false. Comparisons produce one, and && (and), || (or) and ! (not) combine them.

bools.tintin run bools.tin
fn main() {
  let age = 20
  let member = false
  print(age >= 18)
  print(age >= 18 && member)     // and
  print(age >= 18 || member)     // or
  print(!member)                 // not
  print("tin" == "tin")
}
true
false
true
true
true

Tasks

●○○ Task 1: Celsius to Fahrenheit

Store a temperature in Celsius, say 21.5, and print it in Fahrenheit (F = C × 9 / 5 + 32) as 21.5 C is 70.7 F.

Solution
task-1.solution.tintin run task-1.solution.tin
fn main() {
  let celsius = 21.5
  let fahrenheit = celsius * 9 / 5 + 32
  print("{celsius} C is {fahrenheit} F")
}
21.5 C is 70.7 F

●●○ Task 2: Pay for the apples

This doesn't compile. Make it print Total: 1.20, with exactly two digits after the point. Hint: x.fixed(2) gives a string with two decimals.

task-2.tintin check task-2.tin
fn main() {
  let apples = 3
  let pricePerApple = 0.4
  print("Total: {apples * pricePerApple}")
}
error: '*' needs both sides to have the same type, found int and float
 --> task-2.tin:4:18
  |
4 |   print("Total: {apples * pricePerApple}")
  |                  ^^^^^^^^^^^^^^^^^^^^^^
  = note: Tin never converts numbers silently: use float(x) or int(x)
  = fix: wrap it in float(...)
Solution
task-2.solution.tintin run task-2.solution.tin
fn main() {
  let apples = 3
  let pricePerApple = 0.4
  print("Total: {(float(apples) * pricePerApple).fixed(2)}")
}
Total: 1.20

●●○ Task 3: Seconds to hours, minutes and seconds

Turn 100000 seconds into 100000s is 27h 46m 40s using only int arithmetic: / and %.

Solution
task-3.solution.tintin run task-3.solution.tin
fn main() {
  let seconds = 100000
  let hours = seconds / 3600
  let minutes = seconds % 3600 / 60
  let rest = seconds % 60
  print("{seconds}s is {hours}h {minutes}m {rest}s")
}
100000s is 27h 46m 40s

What's next

Next: Functions. Parameters, return types and functions that are one expression.

In the reference: Variables and values · Numbers · Strings · String functions