Sn Tin

Learn Tin · Part 1: The language · Chapter 8

Arrays and maps

Lists of values, lookups by key, and the methods you use every day.

Arrays

An array is an ordered list of values of one type. Its type is written int[], string[] and so on. Positions start at 0.

arrays.tintin run arrays.tin
fn main() {
  let primes = [2, 3, 5, 7, 11]
  print(primes)
  print(primes[0])               // positions start at 0
  print(primes.len)
  print(primes.contains(7))
  print(primes.slice(1, 3))      // from position 1 up to (not including) 3
  print(primes.reverse())
}
[2, 3, 5, 7, 11]
2
5
true
[3, 5]
[11, 7, 5, 3, 2]

Every item must have the same type:

one-type.tintin check one-type.tin
fn main() {
  let mixed = [1, "two", 3]
}
error: expected int, found string
 --> one-type.tin:2:19
  |
2 |   let mixed = [1, "two", 3]
  |                   ^^^^^

Need a list of different things? Make them one sum type (chapter 6), such as type Item = | Num(int) | Word(string), and the array is an Item[].

Changing an array

push, pop and assigning to xs[i] change the array, so it must be a var.

change.tintin run change.tin
fn main() {
  var todo = ["write", "test"]
  todo.push("ship")              // add at the end
  todo[0] = "write more"         // replace one item
  print(todo)
  let done = todo.pop()          // remove the last one and get it back
  print(done)
  print(todo)
}
["write more", "test", "ship"]
ship
["write more", "test"]

An empty array has no items to infer a type from, so you write the type yourself:

empty.tintin run empty.tin
fn main() {
  var names: string[] = []       // an empty array needs its type spelled out
  print(names.isEmpty())
  names.push("ada")
  print(names)
}
true
["ada"]
empty.tintin check empty.tin
fn main() {
  var names = []
  names.push("ada")
}
error: cannot tell the element type of `[]` here; add an annotation like `let xs: int[] = []`
 --> empty.tin:2:15
  |
2 |   var names = []
  |               ^^

Every index is checked

Reading past the end doesn't give you garbage or undefined. It panics and tells you the index and the length:

out-of-bounds.tintin run out-of-bounds.tin
fn main() {
  let xs = [1, 2, 3]
  var i = 0
  while true {
    print(xs[i])
    i += 1
  }
}
1
2
3
panic: index 3 is out of bounds for an array of length 3

Sorting, summing and friends

The standard library has the usual helpers. They return new arrays and leave the original alone.

sort.tintin run sort.tin
fn main() {
  let scores = [72, 95, 88, 60]
  print(sort(scores))            // a sorted copy; scores itself is unchanged
  print(scores)
  print(sum(scores))
  print(first(scores))           // Option: an empty array has no first item
  print(join(["a", "b", "c"], " / "))
}
[60, 72, 88, 95]
[72, 95, 88, 60]
315
Some(72)
a / b / c

sort and sortBy are stable: items that compare equal keep the order they had. To order by two keys, sort by the second one first, then by the main one.

Maps

A Map<K, V> looks up values by key. get returns an Option, because the key might not be there. m[k] is the short way when you know it is: like an array index past the end, a missing key panics.

maps.tintin run maps.tin
fn main() {
  var stock: Map<string, int> = newMap()
  stock.set("apple", 3)
  stock.set("pear", 0)
  stock.set("apple", 5)                  // set again: replaces the value
  print(stock.get("apple"))              // get returns an Option
  print(stock.get("kiwi"))
  print(stock.has("pear"))
  print(stock.size())
  stock["kiwi"] = 7                      // m[k] = v is the same as set
  stock["kiwi"] += 1
  print(stock["kiwi"])                   // m[k] reads the value; it panics if k is missing
  for fruit, n in stock {                // keys keep the order they were added in
    print("{fruit}: {n}")
  }
}
Some(5)
None
true
2
8
apple: 5
pear: 0
kiwi: 8

for name, value in m walks a map in the order the keys were added. A Set<T> keeps each value once:

sets.tintin run sets.tin
fn main() {
  var seen: Set<string> = newSet()
  for word in "to be or not to be".split(" ") {
    seen.add(word)                        // adding again changes nothing
  }
  print(seen)
  print(seen.size())
  print(seen.has("or"))
  let ages = mapOf([("ada", 36), ("alan", 41)])
  for name, age in ages {
    print("{name} is {age}")
  }
}
{"to", "be", "or", "not"}
4
true
ada is 36
alan is 41

Tasks

●○○ Task 1: The largest number

Write largest(xs: int[]): Option<int> with a loop. An empty array has no largest number.

Solution
task-1.solution.tintin run task-1.solution.tin
fn largest(xs: int[]): Option<int> {
  if xs.isEmpty() { return None }
  var best = xs[0]
  for x in xs {
    if x > best { best = x }
  }
  Some(best)
}

fn main() {
  print(largest([4, 19, 7]))
  let none: int[] = []
  print(largest(none))
}
Some(19)
None

●●○ Task 2: Count the words

Count how often each word appears in "the cat saw the dog and the cat ran" and print each word with its count, in order of first appearance. Hint: counts.get(word).or(0).

Solution
task-2.solution.tintin run task-2.solution.tin
fn main() {
  let text = "the cat saw the dog and the cat ran"
  var counts: Map<string, int> = newMap()
  for word in text.split(" ") {
    counts.set(word, counts.get(word).or(0) + 1)
  }
  for word, n in counts {
    print("{word}: {n}")
  }
}
the: 3
cat: 2
saw: 1
dog: 1
and: 1
ran: 1

●●○ Task 3: Remove duplicates

Write withoutDuplicates(xs: int[]): int[] that keeps the first copy of each number: [3, 1, 3, 2, 1, 3] gives [3, 1, 2].

Solution
task-3.solution.tintin run task-3.solution.tin
fn withoutDuplicates(xs: int[]): int[] {
  var seen: int[] = []
  for x in xs {
    if !seen.contains(x) { seen.push(x) }
  }
  seen
}

fn main() {
  print(withoutDuplicates([3, 1, 3, 2, 1, 3]))
}
[3, 1, 2]

What's next

Next: Closures and pipelines. Functions as values, and |> to chain them.

In the reference: Arrays · Array and Map functions