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.
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 need | Use |
|---|---|
| Elements in order, read by position | Array[T], built with [...] |
| A value for each key | Map[K, V], built with Map{ ... } |
| Each value once, and membership tests | Set[T], built with Set.of([...]) |
| Elements computed one at a time, maybe endlessly | Seq[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:
let prices = Map{ tea: 3, cake: 5, soup: 7 }
prices.filter({ x.value > 4 }).keys() // ["cake", "soup"]
prices | Map.values() | Array.sum() // 15Array.sum, Array.min, and Array.max return null when the array is empty, so ?? supplies a default:
prices.filter({ x.value > 10 }).values().sum() ?? 0 // 0Reading 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:
ages["bob"] // null
ages["bob"] ?? 0 // 0
scores.get(5) // null
scores[5] // panic: index 5 out of range for an array of length 3A 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:
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}")
}ada 36
linus 54
red
blue
0: a
1: bIndexed 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:
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:
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] // falseA 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:
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 // 3Functions by job
Building
- Array literals:
[1, 2, 3], with...to spread an array - Map literals:
Map{ key: value } - Array.range: the
ints fromfromup toto - Array.filled:
ncopies of one value - Set.of: a set of the first of each value of an array, in order
- Map.fromEntries: a map from an array of entries; later entries win
- Iter.range: a sequence of the
ints fromfromup toto - Iter.fromArray: a sequence of the elements of an array
Size and membership
- len: the length of an array or the size of a map or set
- Array.length, Map.size, Set.size: the number of elements, entries, or members
- Array.isEmpty, Map.isEmpty, Set.isEmpty: whether there are none
- Array.contains: whether a value is an element
- Map.has: whether there is an entry for a key
- Set.has: whether a value is a member
Reading
- Array.get: element
i, ornullwhen out of range - Array.first, Array.last: the first or last element, or
null - Map.get: the value for a key, or
null; the same asm[k]
Changing a collection in place
- Array.push: append a value
- Array.extend: append the elements of another array
- Array.pop: remove and return the last element
- Array.insert: put a value at index
i - Array.removeAt: remove and return element
i - Map.set: store a value under a key; the same as
m[k] = v - Map.remove: remove a key and return its value, or
null - Set.add: add a member;
truewhen it was not already there - Set.remove: remove a member;
truewhen it was there
Transforming
- Array.map, Map.map: compute a new element or value from each
- Array.flatMap: map to arrays and concatenate them
- Array.filter, Map.filter: keep what a predicate accepts
- Array.reverse: the elements in reverse order
- Array.slice: the elements from
fromup toto - Array.concat: two arrays, one after the other
- Array.flatten: an array of arrays, concatenated
- Array.unique, Array.uniqueBy: the first of each equal value or key
- Map.merge: the entries of two maps; the second map's entries win
Searching and testing
- Array.find, Array.findLast: the first or last element a predicate accepts
- Array.findIndex, Array.findLastIndex: its index
- Array.indexOf, Array.lastIndexOf: the first or last index of a value
- Array.some: whether a predicate accepts any element
- Array.every: whether it accepts every element
- Array.countWhere: how many elements it accepts
Ordering
- Array.sort: ascending, stable
- Array.sortBy: ascending by a key
- Array.sortWith: by a comparison function
- Array.min, Array.max: the least or greatest element
- Array.minBy, Array.maxBy: the element with the least or greatest key
Folding and grouping
- Array.reduce: fold the elements into one value
- Array.sum: the sum of numbers, or
nullwhen empty - Array.chunk: split into arrays of
nelements - Array.groupBy: a map from each key to its elements
Converting to arrays
- Map.keys, Map.values: the keys or the values, in insertion order
- Map.entries: the entries, as Entry records
- Set.values: the members, in insertion order
- Array.entries: each element with its index, as Indexed records
- Iter.toArray: run a sequence and collect its elements
Combining sets
- Set.union: the members of
a, then those ofbthatalacks - Set.intersect: the members of
athatbhas - Set.difference: the members of
athatblacks - Set.isSubset: whether every member of
ais a member ofb
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
nelements, then stop the source
Identity
- Array.same, Map.same, Set.same: whether two names hold the same collection, not only an equal one
Applications
An empty [], Map{}, or Set.of([]) takes its element type from the declared type, so annotate the name:
let seen = Set.of([]) // error: cannot infer the element type of an empty array; annotate itCount words with a map. ?? supplies 0 for a word not seen yet:
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:
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:
let lines = ["b", "a", "b", "c", "a"]
let seen: Set[string] = Set.of([])
for line in lines {
if seen.add(line) {
println(line)
}
}b
a
cFind the tags two posts share, and the ones only the first has:
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:
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
