Skip to content

Collections ​

Ant has three built-in collections and one lazy sequence type. An array holds elements in order, a map holds a value under each key, a set holds each value once, and a sequence produces its elements on demand. The functions for each live in a namespace: Array, Map, and Set for the collections, and Iter for sequences.

ant
let scores = [72, 95, 88]
let ages = Map{ ada: 36, linus: 54 }
let tags = Set.of(["red", "blue", "red"])
let sevens = Iter.range(0, 1000000) | Iter.filter({ x % 7 == 0 })
scores[1]                              // 95
ages["ada"]                            // 36
tags                                   // Set.of(["red", "blue"])
tags.has("red")                        // true
sevens | Iter.take(3) | Iter.toArray() // [0, 7, 14]

Choosing a collection ​

You needUse
Elements in order, read by positionArray[T], built with [...]
A value for each keyMap[K, V], built with Map{ ... }
Each value once, and membership testsSet[T], built with Set.of([...])
Elements computed one at a time, maybe endlesslySeq[T], built and consumed with Iter

Keys and members compare by ==, so a record or an array can be a key or a member. Maps and sets keep insertion order: a for loop, Map.keys, and Set.values visit keys and members in the order they were inserted.

How they behave ​

A function that takes a collection takes it first, so a call goes through . or down a pipe:

ant
let prices = Map{ tea: 3, cake: 5, soup: 7 }
prices.filter({ x.value > 4 }).keys() // ["cake", "soup"]
prices | Map.values() | Array.sum()   // 15

Array.sum, Array.min, and Array.max return null when the array is empty, so ?? supplies a default:

ant
prices.filter({ x.value > 10 }).values().sum() ?? 0 // 0

Reading a missing key gives null, and so does Array.get out of range, but indexing an array out of range panics. Use ?? for a default:

ant
ages["bob"]      // null
ages["bob"] ?? 0 // 0
scores.get(5)    // null
scores[5]        // panic: index 5 out of range for an array of length 3

A for loop over a map yields each Entry, over a set each member, and Array.entries pairs each element of an array with its index:

ant
let ages = Map{ ada: 36, linus: 54 }
for { key, value } in ages {
  println("${key} ${value}")
}
for tag in Set.of(["red", "blue"]) {
  println(tag)
}
for e in ["a", "b"].entries() {
  println("${e.index}: ${e.value}")
}
text
ada 36
linus 54
red
blue
0: a
1: b

Indexed assignment (xs[i] = v, m[k] = v) and the functions under Changing a collection in place change a collection. Every other function leaves it unchanged:

ant
let xs = [3, 1, 2]
xs.sort() // [1, 2, 3]
xs        // [3, 1, 2]
xs.push(4)
xs // [3, 1, 2, 4]

A collection is a reference, so copying a variable shares it. == compares contents; same asks whether two names hold the same collection. Two maps or two sets are equal in any order, two arrays only in the same order:

ant
let a = Map{ x: 1, y: 2 }
let b = Map{ y: 2, x: 1 }
a == b                           // true
Map.same(a, b)                   // false
Set.of([1, 2]) == Set.of([2, 1]) // true
[1, 2] == [2, 1]                 // false

A sequence runs nothing until a for loop or Iter.toArray consumes it, and it stops once the consumer has what it needs. On an array .map is the eager Array.map; on a sequence it is the lazy Iter.map:

ant
var calls = 0
let squares = Iter.range(0, 1000000).map({ calls += 1; x * x })
calls                                   // 0
squares | Iter.take(3) | Iter.toArray() // [0, 1, 4]
calls                                   // 3

Functions by job ​

Building ​

Size and membership ​

Reading ​

Changing a collection in place ​

Transforming ​

Searching and testing ​

Ordering ​

Folding and grouping ​

Converting to arrays ​

Combining sets ​

Lazy sequences ​

  • Seq: a sequence, func(func(T): bool): void
  • Iter.map: apply a function to each element, as the sequence runs
  • Iter.filter: the elements a predicate accepts
  • Iter.take: at most the first n elements, then stop the source

Identity ​

Applications ​

An empty [], Map{}, or Set.of([]) takes its element type from the declared type, so annotate the name:

ant
let seen = Set.of([]) // error: cannot infer the element type of an empty array; annotate it

Count words with a map. ?? supplies 0 for a word not seen yet:

ant
let text = "the ant and the bee and the wasp"
let counts: Map[string, int] = Map{}
for word in text.split(" ") {
  counts[word] = (counts[word] ?? 0) + 1
}
counts // Map{ "the": 3, "ant": 1, "and": 2, "bee": 1, "wasp": 1 }

Rank the counts. Map.entries turns the map into an array, which sorts:

ant
counts
  | Map.entries()
  | Array.sortBy({ -x.value })
  | Array.map({ "${x.key} ${x.value}" }) // ["the 3", "and 2", "ant 1", "bee 1", "wasp 1"]

Print each line the first time it appears. Set.add says whether the line was new:

ant
let lines = ["b", "a", "b", "c", "a"]
let seen: Set[string] = Set.of([])
for line in lines {
  if seen.add(line) {
    println(line)
  }
}
text
b
a
c

Find the tags two posts share, and the ones only the first has:

ant
let first = Set.of(["go", "rust", "ant"])
let second = Set.of(["ant", "zig", "go"])
first.intersect(second)  // Set.of(["go", "ant"])
first.difference(second) // Set.of(["rust"])

Group records by a field, then summarize each group. Array.groupBy returns a map, so .map on it is Map.map:

ant
type Order = { customer: string, total: int }
let orders = [
  Order{ customer: "Ann", total: 30 },
  Order{ customer: "Bob", total: 12 },
  Order{ customer: "Ann", total: 8 },
]
let byCustomer = orders.groupBy({ x.customer })
byCustomer.map({ x.value.length() }) // Map{ "Ann": 2, "Bob": 1 }
byCustomer.keys()                    // ["Ann", "Bob"]

See also ​

Array, Map, Set, Iter, Collections and sequences, Array type, Map type, Set type, for, Text