<!-- Arrays and maps · Tin · https://tin.ad/docs/learn/collections/ · generated from the built page -->

[Learn](https://tin.ad/docs/learn/) · The language · 8 of 34

# Arrays and maps

**Goal.** Store, change, sort and look up values with arrays and maps.

## 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.tin · tin run arrays.tin*

```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())
}
```

<!-- output -->
```text
[2, 3, 5, 7, 11]
2
5
true
[3, 5]
[11, 7, 5, 3, 2]
```

Every item must have the same type:

*one-type.tin · tin check one-type.tin*

```tin
fn main() {
  let mixed = [1, "two", 3]
}
```

<!-- compiler output -->
```text
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.tin · tin run change.tin*

```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)
}
```

<!-- output -->
```text
["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.tin · tin run empty.tin*

```tin
fn main() {
  var names: string[] = []       // an empty array needs its type spelled out
  print(names.isEmpty())
  names.push("ada")
  print(names)
}
```

<!-- output -->
```text
true
["ada"]
```

*empty.tin · tin check empty.tin*

```tin
fn main() {
  var names = []
  names.push("ada")
}
```

<!-- compiler output -->
```text
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.tin · tin run out-of-bounds.tin*

```tin
fn main() {
  let xs = [1, 2, 3]
  var i = 0
  while true {
    print(xs[i])
    i += 1
  }
}
```

<!-- output -->
```text
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.tin · tin run sort.tin*

```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"], " / "))
}
```

<!-- output -->
```text
[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.tin · tin run maps.tin*

```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}")
  }
}
```

<!-- output -->
```text
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.tin · tin run sets.tin*

```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}")
  }
}
```

<!-- output -->
```text
{"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.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-1.solution.tin · tin run task-1.solution.tin*

```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))
}
```

<!-- output -->
```text
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)`.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-2.solution.tin · tin run task-2.solution.tin*

```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}")
  }
}
```

<!-- output -->
```text
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]`.

Your answer   Checking needs JavaScript; the solution below works without it.

**Solution

*task-3.solution.tin · tin run task-3.solution.tin*

```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]))
}
```

<!-- output -->
```text
[3, 1, 2]
```

## Recap

- Arrays grow with `push`; every index is checked.
- Maps look values up by key and give an `Option` back.
- Methods like `sort`, `sum` and `len` cover the daily work.

In the reference: [Arrays](https://tin.ad/docs/ref/language/#arrays) · [Array and Map functions](https://tin.ad/docs/ref/stdlib/#built-in)
