Lists and maps

Collections

Lists: []T

An ordered, growable sequence.

func main() {
    var nums = [10, 20, 30]
    nums.push(40)
    nums[0] = 11
    print(nums, nums.len(), nums[1])
    print(nums.pop(), nums)
    print(nums[1..3]) // a copy of part of the list

    var names: []string // empty list: write the type
    names.push("ann")
    print(names)

    var total = 0
    for n in nums { total += n }
    print(total)
}
[11, 20, 30, 40] 4 20
40 [11, 20, 30]
[20, 30]
[ann]
61

More list methods

func main() {
    var xs = [5, 3, 9]
    xs.insert(0, 7) // put 7 at position 0; the rest move up
    print(xs)
    print(xs.remove(1), xs) // take out the item at position 1 and get it
    print(xs.contains(9), xs.index_of(9), xs.index_of(4))
    xs.sort()
    print(xs)
    xs.reverse()
    print(xs)
    xs.clear()
    print(xs, xs.len())
}
[7, 5, 3, 9]
5 [7, 3, 9]
true 2 -1
[3, 7, 9]
[9, 7, 3]
[] 0
xs.push(v) / xs.pop() add at the end / take the last one
xs.insert(i, v) put v at position i (i may be xs.len(), the end)
xs.remove(i) take out the item at i and give it back
xs.clear() remove everything
xs.contains(v) / xs.index_of(v) is it there? / its first position, or -1
xs.reverse() turn the list around
xs.sort() smallest first (numbers, chars, strings A-Z)
xs.sort_by(less) your own order: less(a, b) says whether a goes before b

contains and index_of work where == does (numbers, strings, char, bool, enums without data). For structs, sort with sort_by:

struct Player {
    name: string
    score: int
}

func main() {
    var ps = [Player{"ann", 30}, Player{"bob", 50}, Player{"cy", 30}]
    ps.sort_by((a, b) => a.score > b.score) // highest first
    for p in ps {
        print(p.name, p.score)
    }
}
bob 50
ann 30
cy 30

Sorting is stable: items that compare equal keep their order (ann stays before cy).

Facts:

  • An empty list needs a type: var xs: []int.
  • Going outside the list (nums[9]) or popping an empty list stops the program with a message.
  • Lists are values. var b = a copies the list. Changing b leaves a alone.
func main() {
    var a = [1, 2, 3]
    var b = a
    b.push(4)
    print(a, b)
}
[1, 2, 3] [1, 2, 3, 4]

Maps: map[K, V]

A map finds a value by a key instead of a position, like a phone book.

func main() {
    var ages = {"alice": 30, "bob": 25}
    ages["carol"] = 41 // add a new entry
    ages["bob"] = 26   // change an existing one
    print(ages["bob"], ages.len())
    print(ages)
}
26 3
{alice: 30, bob: 26, carol: 41}

Making a map

func main() {
    var a = {"x": 1, "y": 2}     // types are guessed from the entries
    var b: map[string, int] = {} // empty: the type comes from the variable
    var c = map[int, string]{}   // empty: the type is written on the right
    b["z"] = 26
    c[7] = "seven"
    print(a, b, c)
}
{x: 1, y: 2} {z: 26} {7: seven}

An empty {} always needs a type from one of those two places.

Keys

A key can be an int (or another whole-number type), a string or a bool. The value can be anything: numbers, strings, lists, structs, even other maps.

Reading

Code Result
m[k] the value; stops the program if k is missing
m.has(k) true or false
m.get(k) the value or nil (type V?, see Errors and nil)
m.get_or(k, d) the value, or d if k is missing
m.len() number of entries
m.keys() a list of the keys
m.values() a list of the values
func main() {
    var stock = {"apple": 3, "pear": 0}
    print(stock.has("apple"), stock.has("fig"))
    print(stock.get("apple"), stock.get("fig"))
    print(stock.get_or("fig", -1))
    print(stock.keys(), stock.values())
}
true false
3 nil
-1
[apple, pear] [3, 0]

Changing

m[k] = v adds or replaces. m.remove(k) deletes (and does nothing if the key is missing).

func main() {
    var m = {"a": 1, "b": 2}
    m["c"] = 3
    m.remove("a")
    print(m)
}
{b: 2, c: 3}

Counting: += starts from zero

The most common map job is counting. m[k] += 1 on a key that isn’t there yet starts from zero, so you don’t have to check first.

func main() {
    var counts: map[string, int] = {}
    for w in "a b a c b a".split(" ") {
        counts[w] += 1
    }
    print(counts)
}
{a: 3, b: 2, c: 1}

(Only the compound forms += -= *= /= %= do this. Plain reading a missing key with m[k] still stops the program.)

Looping

Entries come out in the order they were added, so output is always predictable.

func main() {
    var prices = {"tea": 2.5, "cake": 4.0}
    for name, price in prices {
        print(name, "costs", price)
    }
    for name in prices { // just the keys
        print(name)
    }
}
tea costs 2.5
cake costs 4.0
tea
cake

Maps are values too

var b = a copies the whole map. A map inside a struct is copied with the struct.

func main() {
    var a = {"x": 1}
    var b = a
    b["y"] = 2
    print(a.len(), b.len())
}
1 2

Looking things up is fast: it does not slow down as the map grows. (remove has to re-arrange the entries to keep their order, so it is slower on huge maps.)

Next: Structs and enums

Spotted a mistake? This page comes fromdocs/05-lists-and-maps.md in the Rex repo.