plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


9eba29b — Peter John 2026-11-10T15:03:31+05:30
std/collections: Map is the one ordered map
docs/std.md CHANGED
@@ -11,7 +11,7 @@ The [game engine](game.md) has its own page.
11
11
  | [`Str`, `Buffer`](#text) | text |
12
12
  | [`List`, `Slice`, `Array`, `Grid`](#sequences) | sequences |
13
13
  | [`Map`, `Set`, `Deque`, `Heap`](#collections) | other collections |
14
- | [`AvlTree`, `Trie`, `Graph`, ...](#persistent-trees-heaps-and-graphs) | persistent trees, heaps and graphs |
14
+ | [`BTree`, `Trie`, `Graph`, ...](#persistent-trees-heaps-and-graphs) | persistent trees, heaps and graphs |
15
15
  | [`Option`, `Result`](#option-and-result) | missing values and failures |
16
16
  | [`Json`](#json) | reading and writing JSON |
17
17
  | [`Decimal`](#decimal) | exact decimal numbers, to and from `Float` |
@@ -123,34 +123,35 @@ fun main() =
123
123
  - **Build:** `Map.empty()`, `Map[Str, Int]()`, `Map.single(k, v)`, a literal `[k => v, ..]` (it is `Map.empty().with(k, v)...`, so O(n log n), and a later duplicate key wins), `Map.fromSlice(entries)` and `Map.fromList(entries)` (O(n) when the keys already strictly ascend, else O(n log n); a later duplicate wins).
124
124
  - **Read, O(log n):** `get(k)` (an `Option`), `getOr(k, fallback)` (no `Option` made), `has(k)`; O(1): `length`, `isEmpty`.
125
125
  - **Update, O(log n), each returning the new map:** `with(k, v)` (also called `set`), `remove(k)`, `putIfAbsent(k, v)`, `upsert(k, v, f)` (`f` of the old value, or `v` when absent: Data.Map's `insertWith`), `update(k, f)` (only when present: `adjust`), `alter(k, f)` (`f` takes the value or `None` and returns the new one or `None` to leave `k` out).
126
- - **Order, O(log n):** `min`, `max` (the entry with the smallest or largest key, an `Option[Pair[K, V]]`), `removeMin`, `removeMax`, the neighbours of a key `below(k)` (largest key `< k`), `atMost(k)` (`<=`), `above(k)` (`>`), `atLeast(k)` (`>=`), `entryAt(i)` (the `i`-th entry from 0), `indexOf(k)` (an `Option[Int]`), `split(k)` (the maps of keys before and after `k`, as a `Pair`), `height`.
126
+ - **Order, O(log n):** `min`, `max` (the entry with the smallest or largest key, an `Option[Pair[K, V]]`), `removeMin`, `removeMax`, the neighbours of a key `below(k)` (largest key `< k`), `atMost(k)` (`<=`), `above(k)` (`>`), `atLeast(k)` (`>=`), `entryAt(i)` (the `i`-th entry from 0), `indexOf(k)` (an `Option[Int]`), `rank(k)` (how many keys come before `k`, present or not), `height`.
127
+ - **Ranges, O(log n), sharing nodes with the map:** `from(lo)` (keys `>= lo`), `until(hi)` (keys `< hi`), `range(lo, hi)` (`lo <= key < hi`), `split(k)` (the maps of keys before and after `k`, as a `Pair`), and its inverse `a.join(b)` (every key of `a` must be before every key of `b`, or it crashes). `foldRange(lo, hi, acc, f)` folds over `lo <= key < hi` without building a map.
127
128
  - **Combine, O(m log(n / m + 1)) for sizes m <= n:** `union` (a key in both keeps `self`'s value), `unionWith(o, f)` (`f(self's value, o's value)`), `intersection` (`self`'s values), `difference`.
128
129
  - **Walk, O(n), in key order:** `fold(acc, |acc, k, v| ..)`, `each(|k, v| ..)`, `map(|v| ..)` (same keys and shape), `filter(|k, v| ..)`, `any`, `all`, `keys`, `values` and `entries` (each a new `Slice`), `toStr` (`[1 => one, 2 => two]`; interpolating a map, `"{m}"`, isn't supported yet, so write `"{m.toStr()}"`), `==`. `for e := range m` takes O(log n) a step (each step is `min` and `removeMin`); `entries()` is cheaper when you read every entry. Every walk is O(log n) deep, so a 1,000,000-entry map is fine.
129
130
 
130
131
  Gone or changed from the old hash table: `set`, `remove` and `putIfAbsent` return the new map instead of changing the receiver (`with` no longer changes it either); `clear` is gone (use `Map.empty()`); keys need `compare` instead of `hash`; iteration is key order, not insertion order; `Map.toJson` writes object fields in key order. Against the hash table, `Map[Int, Int]` gets and sets are about 3x slower (`benchmarks/master_vs_simpler/branch/map`): every insert allocates the O(log n) nodes on its path, and the compiler's cell reuse does not yet reach a generic method, so those nodes are not updated in place even when the map is unique.
131
132
 
132
- **`Set[T]`** is a persistent ordered set, the keys of a `Map[T, Bool]`, with the same costs and the same `compare` on its members. `Set[Int]()` or `Set.empty()`, `Set.fromSlice`, `Set.fromList`; `add`, `remove` (each returns the new set), `has`, `length`, `isEmpty`, `min`, `max`, `removeMin`, `removeMax`, `below`, `atMost`, `above`, `atLeast`, `at(i)`, `split`, `union`, `intersection`, `difference`, `isSubsetOf`, `fold`, `each`, `filter`, `any`, `all`, `toSlice` (ascending), `for x := range s`, `==`, `toStr` (`[1, 2, 3]`). `clear` is gone.
133
+ **`Set[T]`** is a persistent ordered set, the keys of a `Map[T, Bool]`, with the same costs and the same `compare` on its members. `Set[Int]()` or `Set.empty()`, `Set.fromSlice`, `Set.fromList`; `add`, `remove` (each returns the new set), `has`, `length`, `isEmpty`, `min`, `max`, `removeMin`, `removeMax`, `below`, `atMost`, `above`, `atLeast`, `at(i)`, `indexOf`, `rank`, `from`, `until`, `range`, `foldRange`, `split`, `join`, `union`, `intersection`, `difference`, `isSubsetOf`, `fold`, `each`, `filter`, `any`, `all`, `toSlice` (ascending), `for x := range s`, `==`, `toStr` (`[1, 2, 3]`). `clear` is gone.
133
134
 
134
135
  - **`Deque`:** a queue you can use from both ends: `pushBack`, `pushFront`, `popBack`, `popFront`, `get`, `at` (crashes out of range)
135
136
  - **`Heap`:** gives back first the item nothing comes `before`: `h: Heap[Int] := Heap.by(|a, b| a < b)`, or `Heap.byKey(|n| n.cost)` by a key of any type with `<`; `push`, `pop`, `peek`
136
137
 
137
138
  ## Persistent trees, heaps and graphs
138
139
 
139
- `std/collections` also holds persistent trees, heaps and graphs, written as recursive `enum`s whose operations are methods that `match self` and recurse. No `for` or `while` loop and no `Slice`, `Map`, `Set`, `Buffer` or `Array` inside a structure or its algorithms: results are threaded through accumulators. Every update returns a new value that shares its unchanged subtrees. Sequences come back as `List` (`Cons`/`Nil`).
140
+ `std/collections` also holds persistent trees, heaps and graphs, written as recursive `enum`s whose operations are methods that `match self` and recurse. No `for` or `while` loop and no mutable std type (`Slice`, `Buffer`, `Array`) inside a structure or its algorithms: results are threaded through accumulators (`Map` and `Set` are persistent themselves, and `Graph` and `UnionFind` are built on them). Every update returns a new value that shares its unchanged subtrees. Sequences come back as `List` (`Cons`/`Nil`).
140
141
 
141
- Plum types are global by name, so each type and variant name here is unique in std (`AvlBranch`, `RbBranch`, `WbBranch`). Import each file (`import std/collections/AvlTree`). Their `toStr` joins the entries with `List.join`.
142
+ Plum types are global by name, so each type and variant name here is unique in std (`BtNode`, `HamtNode`, `RoseNode`). Import each file (`import std/collections/BTree`). Their `toStr` joins the entries with `List.join`.
142
143
 
143
144
  Only true tail calls run in constant stack; other recursion overflows at a few tens of thousands of frames. So anything whose depth depends on the data (a chain of vertices, a key's bytes, a heap's root list) walks with a tail call, keeping the path it passed in an accumulator and rebuilding it with a second tail call. Balanced trees recurse plainly, O(log n) deep.
144
145
 
145
- - **`Graph`:** a directed graph. `dfs` threads its visited set (an `AvlTree`) through a tail call.
146
- - **`AvlTree`, `RedBlackTree`, `WeightBalancedTree`, `Treap`, `IntervalTree`:** ordered maps; `entries`, `keys`, `values` and the queries return `List`s. `Treap` takes its priorities from an immutable `Random` that each insert carries forward.
146
+ - **`Graph`:** a directed graph. `dfs` threads its visited set (a `Set[Int]`) through a tail call.
147
+ - **`IntervalTree`:** an ordered map of intervals; `entries` and the queries return `List`s. The plain ordered map is [`Map`](#collections): std used to hold four more balanced search trees with the same operations (`WeightBalancedTree`, `AvlTree`, `RedBlackTree`, `Treap`), and they are gone. `Map` is the weight-balanced one, with their `rank`, `range` and `join`; a custom order is a key type with its own `compare`.
147
148
  - **`BTree`, `BPlusTree`:** the node keys and children are cons lists. `BPlusTree` has no linked leaf chain (a persistent tree can't keep one), so `range` recurses from the root, and `cursor()` / `from(lo)` return a persistent `BpCursor` (`next()` gives the entry and the rest).
148
149
  - **`Trie`, `RadixTree`:** each node's children are a sorted cons list. Every walk along a key is a tail call, so there's no limit on key length.
149
150
  - **`Hamt`:** 32-way on 5-bit hash slices; a branch is a bitmap plus a cons list of children in slot order (found by popcount).
150
151
  - **`SegmentTree`:** a range tree whose nodes cache the combined value of their range. `set` and `update` return a new tree. `get` is O(log n), and there is no `ofArray`.
151
152
  - **`FenwickTree`:** a prefix-sum tree: a segment tree specialised to `Int` sums, keeping only each node's left-half sum (what prefix queries read). The `i & -i` index trick needs an array, so it isn't used.
152
153
  - **`Quadtree`, `KdTree`, `Bvh`:** spatial trees over `Vec2` and `Aabb`. Leaf buckets and query results are cons lists. Balanced builds sort with a merge sort on `List` (`KdTree`) or pick medians with a quickselect (`Bvh`).
153
- - **`UnionFind`:** a persistent parent map (two `AvlTree`s: parents and set sizes) with union by size and no path compression. `find`, `union` and `connected` are O(log² n). `union` returns the new forest.
154
+ - **`UnionFind`:** a persistent parent map (two `Map[Int, Int]`s: parents and set sizes) with union by size and no path compression. `find`, `union` and `connected` are O(log² n). `union` returns the new forest.
154
155
  - **`RoseTree`:** a tree with any number of children per node, in left-child, right-sibling form (`RoseEmpty`, `RoseNode(value, firstChild, nextSibling)`). `RoseTree.leaf(v)` and `RoseTree.of(v, kids)` build nodes, `RoseTree.chainOf(ns)` links a `List` of them as siblings. A value is a node with its later siblings; every walk runs in constant stack along the siblings (a node with 200,000 children is fine), and only the tree's depth takes stack. `filter`, `replace` and `update` return untouched subtrees as they were. std/game/SceneTree's `SceneTree[M]` is a `RoseTree[Actor[M]]`, a tree of trait objects. An actor the pointer can hit is `Clickable` as well (`is Actor[M], Clickable`), and the tree's pointer walk tells it from the others with a downcast (`Clickable as c`, one type-tag test).
155
156
  - **`LeftistHeap`, `PairingHeap`:** priority queues with `fold` in place of an iterator. The pairing heap's two-pass `pop` is tail recursive, so a root with 100,000 children is fine.
156
157
 
std/collections/AvlTree.plum DELETED
@@ -1,387 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Float
5
- import std/Str
6
- import std/Option
7
- import std/Pair
8
- import std/collections/List
9
- import std/Slice
10
- import std/collections/Map
11
-
12
- # The persistent collections of std/collections (the trees, heaps, tries and graphs
13
- # next to `List`, `Map` and `Set`) are written as recursive enums, with no loop,
14
- # no mutable field and no mutable std type (`Slice`, `Map`, `Set`, `Buffer`, `Array`) in
15
- # a structure or its algorithms. Every operation is a method that matches on the enum
16
- # and recurses; results are threaded through accumulators; every update returns a new
17
- # value that shares its unchanged subtrees. Sequences come back as std's cons list,
18
- # `List`. Plum types are global by name, so each type and variant name here is unique
19
- # in std (`AvlBranch`, `RbBranch`, `WbBranch`).
20
- #
21
- # AvlTree is a persistent ordered map kept as an AVL tree (the two subtrees of every
22
- # node differ in height by at most one, so the height stays under 1.44 * log2(n + 2)).
23
- # `insert` and `remove` rebuild the O(log n) nodes on the path to the key and share
24
- # everything else; the old tree stays as it was.
25
- # Keys are ordered by `before(a, b)` ("a belongs before b", strictly), stored in the
26
- # wrapper: `AvlTree.by(|a, b| a > b)` keeps keys descending, `AvlTree.ints()` ascending.
27
- # `get`/`has`/`insert`/`remove`/`min`/`max` are O(log n); `length` is O(1). Recursion
28
- # follows one path (stack O(log n)), except `entries`, which is O(log n) deep too.
29
- struct AvlTree[K, V](root: AvlBranch[K, V], size: Int, before: fn(K, K) -> Bool) =
30
-
31
- # The empty tree ordered by `before`.
32
- fun by(before: fn(K, K) -> Bool) -> AvlTree[K, V] =
33
- leaf: AvlBranch[K, V] := AvlLeaf
34
- AvlTree(root: leaf, size: 0, before: before)
35
-
36
- # The empty tree of `Int` keys in ascending order.
37
- fun ints() -> AvlTree[Int, V] =
38
- leaf: AvlBranch[Int, V] := AvlLeaf
39
- AvlTree(root: leaf, size: 0, before: |a, b| a < b)
40
-
41
- fun length(self) -> Int = self.size
42
-
43
- fun isEmpty(self) -> Bool = self.size == 0
44
-
45
- # The number of nodes on the longest root-to-leaf path (0 when empty).
46
- fun height(self) -> Int = self.root.height()
47
-
48
- # The value stored for `k`, or None.
49
- fun get(self, k: K) -> Option[V] = self.root.get(k, self.before)
50
-
51
- fun has(self, k: K) -> Bool = self.get(k).isSome()
52
-
53
- # A tree with `k` mapped to `v`, replacing the value of an existing `k`.
54
- fun insert(self, k: K, v: V) -> AvlTree[K, V] =
55
- root := self.root.insert(k, v, self.before)
56
- if self.has(k)
57
- AvlTree(root: root, size: self.size, before: self.before)
58
- else
59
- AvlTree(root: root, size: self.size + 1, before: self.before)
60
-
61
- # A tree without `k`; the same tree when `k` is absent.
62
- fun remove(self, k: K) -> AvlTree[K, V] =
63
- if !self.has(k)
64
- self
65
- else
66
- AvlTree(root: self.root.remove(k, self.before), size: self.size - 1, before: self.before)
67
-
68
- # The entry with the smallest key, or None if empty.
69
- fun min(self) -> Option[Pair[K, V]] = self.root.min()
70
-
71
- # The entry with the largest key, or None if empty.
72
- fun max(self) -> Option[Pair[K, V]] = self.root.max()
73
-
74
- # Every key with its value, in ascending key order (`e.first`, `e.second`).
75
- fun entries(self) -> List[Pair[K, V]] =
76
- nil: List[Pair[K, V]] := Nil
77
- self.root.collect(nil)
78
-
79
- # Every key, in ascending order.
80
- fun keys(self) -> List[K] = self.entries().map(|e| e.first)
81
-
82
- # Every value, in ascending key order.
83
- fun values(self) -> List[V] = self.entries().map(|e| e.second)
84
-
85
- # The entries in key order: `[1: one, 2: two]`.
86
- fun toStr(self) -> Str = "[" + self.entries().join(", ") + "]"
87
-
88
- # The nodes of an `AvlTree`: `AvlLeaf`, or a key and value with the subtree of
89
- # smaller keys on the left, larger on the right, and the node's height cached.
90
- enum AvlBranch[K, V] =
91
- | AvlLeaf
92
- | AvlNode(key: K, value: V, height: Int, left: AvlBranch[K, V], right: AvlBranch[K, V])
93
-
94
- fun isEmpty(self) -> Bool = match self
95
- AvlLeaf => true
96
- AvlNode(_, _, _, _, _) => false
97
-
98
- fun height(self) -> Int = match self
99
- AvlLeaf => 0
100
- AvlNode(_, _, h, _, _) => h
101
-
102
- # Left height minus right height.
103
- fun skew(self) -> Int = match self
104
- AvlLeaf => 0
105
- AvlNode(_, _, _, l, r) => l.height() - r.height()
106
-
107
- # Tail recursive: one comparison per level.
108
- fun get(self, k: K, before: fn(K, K) -> Bool) -> Option[V] = match self
109
- AvlLeaf => None
110
- AvlNode(nk, nv, _, l, r) =>
111
- if before(k, nk)
112
- l.get(k, before)
113
- else if before(nk, k)
114
- r.get(k, before)
115
- else
116
- Some(nv)
117
-
118
- # A node over `l` and `r` with its height computed (no rebalancing).
119
- fun join(k: K, v: V, l: AvlBranch[K, V], r: AvlBranch[K, V]) -> AvlBranch[K, V] =
120
- AvlNode(key: k, value: v, height: l.height().max(r.height()) + 1, left: l, right: r)
121
-
122
- # The left child lifted to the root: `(a x b) y c` becomes `a x (b y c)`.
123
- fun rotateRight(self) -> AvlBranch[K, V] = match self
124
- AvlNode(k, v, _, AvlNode(lk, lv, _, ll, lr), r) => AvlBranch.join(lk, lv, ll, AvlBranch.join(k, v, lr, r))
125
- _ => self
126
-
127
- # The right child lifted to the root: `a x (b y c)` becomes `(a x b) y c`.
128
- fun rotateLeft(self) -> AvlBranch[K, V] = match self
129
- AvlNode(k, v, _, l, AvlNode(rk, rv, _, rl, rr)) => AvlBranch.join(rk, rv, AvlBranch.join(k, v, l, rl), rr)
130
- _ => self
131
-
132
- # `join`, restoring balance when one side is two taller than the other (after one
133
- # insert or remove below). Left-left and right-right take one rotation; left-right
134
- # and right-left first rotate the child the other way.
135
- fun balance(k: K, v: V, l: AvlBranch[K, V], r: AvlBranch[K, V]) -> AvlBranch[K, V] =
136
- if l.height() > r.height() + 1
137
- if l.skew() < 0
138
- AvlBranch.join(k, v, l.rotateLeft(), r).rotateRight()
139
- else
140
- AvlBranch.join(k, v, l, r).rotateRight()
141
- else if r.height() > l.height() + 1
142
- if r.skew() > 0
143
- AvlBranch.join(k, v, l, r.rotateRight()).rotateLeft()
144
- else
145
- AvlBranch.join(k, v, l, r).rotateLeft()
146
- else
147
- AvlBranch.join(k, v, l, r)
148
-
149
- fun insert(self, k: K, v: V, before: fn(K, K) -> Bool) -> AvlBranch[K, V] = match self
150
- AvlLeaf => AvlNode(key: k, value: v, height: 1, left: self, right: self)
151
- AvlNode(nk, nv, h, l, r) =>
152
- if before(k, nk)
153
- AvlBranch.balance(nk, nv, l.insert(k, v, before), r)
154
- else if before(nk, k)
155
- AvlBranch.balance(nk, nv, l, r.insert(k, v, before))
156
- else
157
- AvlNode(key: nk, value: v, height: h, left: l, right: r)
158
-
159
- fun remove(self, k: K, before: fn(K, K) -> Bool) -> AvlBranch[K, V] = match self
160
- AvlLeaf => self
161
- AvlNode(nk, nv, _, l, r) =>
162
- if before(k, nk)
163
- AvlBranch.balance(nk, nv, l.remove(k, before), r)
164
- else if before(nk, k)
165
- AvlBranch.balance(nk, nv, l, r.remove(k, before))
166
- else
167
- match l
168
- AvlLeaf => r
169
- AvlNode(_, _, _, _, _) =>
170
- match r.min()
171
- None => l
172
- # Two children: the successor (the right subtree's minimum) takes its place.
173
- Some(s) => AvlBranch.balance(s.first, s.second, l, r.removeMin())
174
-
175
- fun removeMin(self) -> AvlBranch[K, V] = match self
176
- AvlLeaf => self
177
- AvlNode(_, _, _, AvlLeaf, r) => r
178
- AvlNode(nk, nv, _, l, r) => AvlBranch.balance(nk, nv, l.removeMin(), r)
179
-
180
- fun min(self) -> Option[Pair[K, V]] = match self
181
- AvlLeaf => None
182
- AvlNode(nk, nv, _, AvlLeaf, _) => Some(Pair(first: nk, second: nv))
183
- AvlNode(_, _, _, l, _) => l.min()
184
-
185
- fun max(self) -> Option[Pair[K, V]] = match self
186
- AvlLeaf => None
187
- AvlNode(nk, nv, _, _, AvlLeaf) => Some(Pair(first: nk, second: nv))
188
- AvlNode(_, _, _, _, r) => r.max()
189
-
190
- # The entries in key order, in front of `acc`: right subtree first, so each entry is
191
- # consed onto the ones after it.
192
- fun collect(self, acc: List[Pair[K, V]]) -> List[Pair[K, V]] = match self
193
- AvlLeaf => acc
194
- AvlNode(nk, nv, _, l, r) => l.collect(Cons(head: Pair(first: nk, second: nv), tail: r.collect(acc)))
195
-
196
- # ---------------------------------------------------------------------------
197
- # Test helpers. Tests may use loops, `mut` fields and std's `Map` as the
198
- # reference model; the structure above may not.
199
- # ---------------------------------------------------------------------------
200
-
201
- fun avlInts() -> AvlTree[Int, Int] =
202
- t: AvlTree[Int, Int] := AvlTree.ints()
203
- t
204
-
205
- # Inserts each key `k` with value `k * 10`, in order.
206
- fun avlOf(keys: List[Int]) -> AvlTree[Int, Int] =
207
- keys.fold(avlInts(), |t, k| t.insert(k, k * 10))
208
-
209
- # The tree's shape, keys only: `((1)2(3))`.
210
- fun avlShape(t: AvlBranch[Int, Int]) -> Str = match t
211
- AvlLeaf => ""
212
- AvlNode(k, _, _, l, r) => "({avlShape(l)}{k}{avlShape(r)})"
213
-
214
- # The height of `t` if every cached height is right and the subtrees of every node
215
- # differ in height by at most one, else -1.
216
- fun avlCheckedHeight(t: AvlBranch[Int, Int]) -> Int = match t
217
- AvlLeaf => 0
218
- AvlNode(_, _, h, l, r) =>
219
- hl := avlCheckedHeight(l)
220
- hr := avlCheckedHeight(r)
221
- if hl < 0 || hr < 0 || hl - hr > 1 || hr - hl > 1 || h != hl.max(hr) + 1
222
- -1
223
- else
224
- h
225
-
226
- # True when the keys of `ks` are strictly ascending.
227
- fun avlAscending(ks: List[Int]) -> Bool = match ks
228
- Cons(a, Cons(b, rest)) =>
229
- if a >= b
230
- false
231
- else
232
- avlAscending(Cons(head: b, tail: rest))
233
- _ => true
234
-
235
- # The AVL invariants: balanced, heights cached right, keys strictly ascending in
236
- # order, and `length` matching the node count.
237
- fun avlValid(t: AvlTree[Int, Int]) -> Bool =
238
- ks := t.keys()
239
- avlCheckedHeight(t.root) >= 0 && ks.length() == t.length() && avlAscending(ks)
240
-
241
- # Inserts `lo` to `hi - 1` (value = key), as a tail call.
242
- fun avlRange(t: AvlTree[Int, Int], lo: Int, hi: Int) -> AvlTree[Int, Int] =
243
- if lo >= hi
244
- t
245
- else
246
- avlRange(t.insert(lo, lo), lo + 1, hi)
247
-
248
- # The state of the random-operations test: the tree, the generator and the model.
249
- struct AvlTestRun(mut t: AvlTree[Int, Int], mut x: Int, mut present: Map[Int, Int])
250
-
251
- test "an empty tree"
252
- t := avlInts()
253
- assert t.length() == 0
254
- assert t.isEmpty()
255
- assert t.height() == 0
256
- assert t.get(1).isNone()
257
- assert t.has(1) == false
258
- assert t.min().isNone()
259
- assert t.max().isNone()
260
- assert t.keys().isEmpty()
261
- assert t.toStr() == "[]"
262
- assert t.remove(1).length() == 0
263
-
264
- test "insert, get and has"
265
- t := avlOf([5, 3, 8, 1])
266
- assert t.length() == 4
267
- assert t.get(3)! == 30
268
- assert t.get(8)! == 80
269
- assert t.get(4).isNone()
270
- assert t.has(1)
271
- assert t.has(2) == false
272
-
273
- test "insert replaces the value of an existing key"
274
- t := avlOf([1, 2, 3]).insert(2, 99)
275
- assert t.length() == 3
276
- assert t.get(2)! == 99
277
- assert t.toStr() == "[1: 10, 2: 99, 3: 30]"
278
-
279
- test "a tree of other value types"
280
- t: AvlTree[Int, Str] := AvlTree.ints()
281
- u := t.insert(2, "b").insert(1, "a")
282
- assert u.size == 2
283
- assert u.toStr() == "[1: a, 2: b]"
284
-
285
- test "min, max, entries, keys and values are in key order"
286
- t := avlOf([7, 2, 9, 4, 1])
287
- assert t.min()!.first == 1
288
- assert t.min()!.second == 10
289
- assert t.max()!.first == 9
290
- assert t.keys().toStr() == "[1,2,4,7,9]"
291
- assert t.values().toStr() == "[10,20,40,70,90]"
292
- es := t.entries()
293
- assert es.length() == 5
294
- assert es.at(2).first == 4 && es.at(2).second == 40
295
- assert t.toStr() == "[1: 10, 2: 20, 4: 40, 7: 70, 9: 90]"
296
-
297
- test "insert rotations: left-left, right-right, left-right, right-left"
298
- ll := avlOf([3, 2, 1])
299
- assert avlShape(ll.root) == "((1)2(3))"
300
- assert ll.height() == 2
301
- rr := avlOf([1, 2, 3])
302
- assert avlShape(rr.root) == "((1)2(3))"
303
- lr := avlOf([3, 1, 2])
304
- assert avlShape(lr.root) == "((1)2(3))"
305
- rl := avlOf([1, 3, 2])
306
- assert avlShape(rl.root) == "((1)2(3))"
307
- assert rl.height() == 2
308
-
309
- test "remove rotations: left-left, right-right, left-right, right-left"
310
- ll := avlOf([3, 2, 4, 1]).remove(4)
311
- assert avlShape(ll.root) == "((1)2(3))"
312
- rr := avlOf([2, 1, 3, 4]).remove(1)
313
- assert avlShape(rr.root) == "((2)3(4))"
314
- lr := avlOf([3, 1, 4, 2]).remove(4)
315
- assert avlShape(lr.root) == "((1)2(3))"
316
- rl := avlOf([2, 1, 4, 3]).remove(1)
317
- assert avlShape(rl.root) == "((2)3(4))"
318
- even := avlOf([2, 1, 4, 3, 5]).remove(1)
319
- assert avlShape(even.root) == "((2(3))4(5))"
320
- assert even.height() == 3 && avlValid(even)
321
-
322
- test "remove a leaf, a one-child node, a two-child node and missing keys"
323
- t := avlOf([4, 2, 6, 1, 3, 5, 7, 8])
324
- a := t.remove(1)
325
- assert a.keys().toStr() == "[2,3,4,5,6,7,8]"
326
- b := a.remove(7)
327
- assert b.keys().toStr() == "[2,3,4,5,6,8]"
328
- assert b.get(8)! == 80
329
- c := b.remove(4)
330
- assert c.keys().toStr() == "[2,3,5,6,8]"
331
- assert c.has(4) == false
332
- assert c.get(5)! == 50
333
- assert avlValid(a) && avlValid(b) && avlValid(c)
334
- d := c.remove(42)
335
- assert d.length() == 5
336
- assert d.toStr() == c.toStr()
337
- e := c.remove(2).remove(3).remove(5).remove(6).remove(8)
338
- assert e.isEmpty()
339
- assert e.height() == 0
340
-
341
- test "old versions are unchanged after insert and remove"
342
- t := avlOf([1, 2, 3, 4, 5])
343
- u := t.insert(6, 60).insert(3, 0)
344
- v := t.remove(2).remove(4)
345
- assert t.toStr() == "[1: 10, 2: 20, 3: 30, 4: 40, 5: 50]"
346
- assert t.length() == 5
347
- assert avlShape(t.root) == "((1)2((3)4(5)))"
348
- assert u.toStr() == "[1: 10, 2: 20, 3: 0, 4: 40, 5: 50, 6: 60]"
349
- assert v.keys().toStr() == "[1,3,5]"
350
- assert avlValid(t) && avlValid(u) && avlValid(v)
351
-
352
- test "10,000 ascending keys stay balanced and sorted"
353
- n := 10000
354
- t := avlRange(avlInts(), 0, n)
355
- assert t.length() == n
356
- assert Float(t.height()) <= 1.44 * n.log2() + 2.0
357
- assert t.keys().equals(avlRange(avlInts(), 0, n).keys())
358
- assert t.keys().at(n - 1) == n - 1
359
- assert avlValid(t)
360
- assert t.min()!.first == 0
361
- assert t.max()!.first == n - 1
362
-
363
- test "invariants hold through pseudo-random inserts and removes"
364
- run := AvlTestRun(t: avlInts(), x: 12345, present: Map.empty())
365
- for i := range 3000
366
- run.x = {run.x * 1103515245 + 12345} % 2147483648
367
- k := run.x % 500
368
- if {run.x / 1000} % 3 == 0
369
- run.t = run.t.remove(k)
370
- run.present = run.present.remove(k)
371
- else
372
- run.t = run.t.insert(k, i)
373
- run.present = run.present.with(k, i)
374
- if i % 50 == 0
375
- assert avlValid(run.t)
376
- assert avlValid(run.t)
377
- assert run.t.length() == run.present.length()
378
- for k := range run.present.keys()
379
- assert run.t.get(k)! == run.present.get(k)!
380
-
381
- test "a custom order: longest string first"
382
- t: AvlTree[Str, Int] := AvlTree.by(|a, b| a.length() > b.length())
383
- u := t.insert("ab", 2).insert("abcd", 4).insert("a", 1).insert("xy", 22)
384
- assert u.length() == 3
385
- assert u.get("zz")! == 22
386
- assert u.min()!.first == "abcd"
387
- assert u.max()!.first == "a"
std/collections/BPlusTree.plum CHANGED
@@ -10,7 +10,7 @@ import std/math/Vec2
10
10
  import std/collections/List
11
11
  import std/Slice
12
12
 
13
- # `BPlusTree`, written functionally (see std/collections/AvlTree
13
+ # `BPlusTree`, written functionally (see docs/std.md
14
14
  # for the rules these persistent collections follow): a persistent B+ tree, an ordered map from `K` to `V`,
15
15
  # ordered by `before(a, b)` (strictly less; keys are equal when neither is before the
16
16
  # other). Values live only in the leaves (`BpLeaf`); inner nodes (`BpInner`) hold
std/collections/BTree.plum CHANGED
@@ -10,7 +10,7 @@ import std/Array
10
10
  import std/math/Vec2
11
11
  import std/collections/List
12
12
 
13
- # `BTree`, written functionally (see std/collections/AvlTree
13
+ # `BTree`, written functionally (see docs/std.md
14
14
  # for the rules these persistent collections follow): a persistent B-tree, an ordered map from `K` to `V`
15
15
  # with minimum degree `t` (t >= 2, default 16). Every node but the root holds t - 1 to
16
16
  # 2t - 1 keys, a branch has one more child than keys, and all leaves sit at the same
std/collections/Bvh.plum CHANGED
@@ -12,7 +12,7 @@ import std/Slice
12
12
  import std/collections/Set
13
13
 
14
14
  # `Bvh`, written functionally (see
15
- # std/collections/AvlTree for the rules these persistent collections follow): a bounding volume
15
+ # docs/std.md for the rules these persistent collections follow): a bounding volume
16
16
  # hierarchy, a balanced binary tree of axis-aligned boxes each carrying a value `V`, for
17
17
  # broad-phase collision and ray casts. `Bvh.build(items)` makes the whole tree from a
18
18
  # `List` of (box, value) pairs at once; nothing changes it afterwards, so a `Bvh` can
std/collections/FenwickTree.plum CHANGED
@@ -6,7 +6,7 @@ import std/collections/List
6
6
  import std/Slice
7
7
 
8
8
  # `FenwickTree`, written functionally (see
9
- # std/collections/AvlTree for the rules these persistent collections follow): a persistent
9
+ # docs/std.md for the rules these persistent collections follow): a persistent
10
10
  # prefix-sum tree over `n` Ints, indices 0 to n - 1, for prefix and range sums while
11
11
  # single elements change.
12
12
  #
std/collections/Graph.plum CHANGED
@@ -4,9 +4,9 @@ import std/Int
4
4
  import std/Str
5
5
  import std/Option
6
6
  import std/collections/List
7
- import std/collections/AvlTree
7
+ import std/collections/Set
8
8
 
9
- # A graph written functionally (see std/collections/AvlTree for the rules
9
+ # A graph written functionally (see docs/std.md for the rules
10
10
  # these persistent collections follow): a persistent directed graph, a chain of vertices, each holding its
11
11
  # outgoing edges as a `List[Int]` of neighbour ids, newest first.
12
12
  # `Graph.ofSize(n)` builds vertices 0 to n - 1 with no edges. Finding a vertex is O(V).
@@ -14,8 +14,7 @@ import std/collections/AvlTree
14
14
  # Every walk along the chain is a tail call, and `addEdge` keeps the vertices it
15
15
  # passes reversed in an accumulator and puts them back with a second tail call, so all
16
16
  # of it runs in constant stack: a chain of 200,000 vertices is fine. `dfs` threads its
17
- # visited set (an `AvlTree`), its stack and its result through a tail call instead of
17
+ # visited set (a persistent `Set`), its stack and its result through a tail call.
18
- # mutating a `Set`.
19
18
  enum Graph =
20
19
  | NoVertex
21
20
  | Vertex(id: Int, edges: List[Int], rest: Graph)
@@ -78,18 +77,18 @@ enum Graph =
78
77
  if !self.hasVertex(start)
79
78
  none
80
79
  else
81
- seen: AvlTree[Int, Bool] := AvlTree.ints()
80
+ seen: Set[Int] := Set.empty()
82
81
  self.walk(Cons(head: start, tail: none), seen, none)
83
82
 
84
83
  # One step of the depth-first walk: pop `stack`; an unseen vertex is added to
85
84
  # `order` and its neighbours pushed in front of the rest.
86
- fun walk(self, stack: List[Int], seen: AvlTree[Int, Bool], order: List[Int]) -> List[Int] = match stack
85
+ fun walk(self, stack: List[Int], seen: Set[Int], order: List[Int]) -> List[Int] = match stack
87
86
  Nil => order.reverse()
88
87
  Cons(v, rest) =>
89
88
  if seen.has(v)
90
89
  self.walk(rest, seen, order)
91
90
  else
92
- self.walk(self.neighbours(v).append(rest), seen.insert(v, true), Cons(head: v, tail: order))
91
+ self.walk(self.neighbours(v).append(rest), seen.add(v), Cons(head: v, tail: order))
93
92
 
94
93
  # One line per vertex: `Vertex 0 -> 2, 1`, or `Vertex 3 -> None` with no edges.
95
94
  fun toStr(self) -> Str =
std/collections/Hamt.plum CHANGED
@@ -7,7 +7,7 @@ import std/Option
7
7
  import std/collections/List
8
8
  import std/collections/Map
9
9
 
10
- # `Hamt`, written functionally (see std/collections/AvlTree
10
+ # `Hamt`, written functionally (see docs/std.md
11
11
  # for the rules these persistent collections follow): a persistent hash map, a hash array mapped trie. Each key's
12
12
  # 64-bit hash (avalanched as `Hamt` and `Map` do) is read 5 bits at a time from the low
13
13
  # end, one 5-bit slot per level, so a lookup visits at most 13 branches.
std/collections/IntervalTree.plum CHANGED
@@ -7,7 +7,7 @@ import std/Option
7
7
  import std/collections/List
8
8
  import std/Slice
9
9
 
10
- # `IntervalTree`, written functionally (see std/collections/AvlTree
10
+ # `IntervalTree`, written functionally (see docs/std.md
11
11
  # for the rules these persistent collections follow): a persistent interval tree over closed Int intervals
12
12
  # `[lo, hi]`, each with a value. It is an AVL tree ordered by `lo` (then `hi`) whose every
13
13
  # node also caches the largest `hi` in its subtree (`maxHi`), so a query skips each
std/collections/KdTree.plum CHANGED
@@ -10,7 +10,7 @@ import std/Slice
10
10
  import std/collections/List
11
11
 
12
12
  # `KdTree`, written functionally (see
13
- # std/collections/AvlTree for the rules these persistent collections follow): a persistent 2-d
13
+ # docs/std.md for the rules these persistent collections follow): a persistent 2-d
14
14
  # tree, values at `Vec2` points, split on x at even depths and on y at odd ones. Every
15
15
  # point in a node's left subtree has its split coordinate <= the node's, every point in
16
16
  # the right subtree >= it. `KdTree.build(entries)` makes a balanced tree (each node is
std/collections/LeftistHeap.plum CHANGED
@@ -7,7 +7,7 @@ import std/Pair
7
7
  import std/collections/List
8
8
  import std/Slice
9
9
 
10
- # `LeftistHeap`, written functionally (see std/collections/AvlTree
10
+ # `LeftistHeap`, written functionally (see docs/std.md
11
11
  # for the rules these persistent collections follow): a persistent mergeable MIN-heap kept as a leftist tree, a
12
12
  # binary tree in heap order (no element is before its parent) where every node's left
13
13
  # child has a rank (the length of its rightmost path to an empty tree) at least that of
std/collections/Map.plum CHANGED
@@ -30,8 +30,9 @@ import std/collections/List
30
30
  # `entries`, `fold`, `each` and `toStr` all go in ascending key order.
31
31
  #
32
32
  # Costs: `get`, `has`, `with`, `remove`, `update`, `min`, `max`, the neighbour lookups,
33
- # `entryAt` and `indexOf` are O(log n); `length` and `isEmpty` O(1); `keys`, `values`,
33
+ # `entryAt`, `indexOf` and `rank` are O(log n); `length` and `isEmpty` O(1); `keys`, `values`,
34
- # `entries`, `fold`, `each`, `map`, `filter`, `==` and `toStr` O(n); `split` O(log n);
34
+ # `entries`, `fold`, `each`, `map`, `filter`, `==` and `toStr` O(n); `split`, `join`, `from`,
35
+ # `until` and `range` O(log n); `foldRange` O(log n) plus the entries it visits;
35
36
  # `union`, `intersection` and `difference` O(m log(n / m + 1)) for sizes m <= n;
36
37
  # `fromSlice` O(n) on keys already strictly ascending, else O(n log n).
37
38
  # Stack: every walk is O(log n) deep (lookups are tail calls), so a 1,000,000-entry map is
@@ -39,10 +40,11 @@ import std/collections/List
39
40
  #
40
41
  # Very similar structures: all four below are balanced binary search trees that give the
41
42
  # same ordered-map operations at the same O(log n) costs, and differ only in how they keep
42
- # the tree balanced. Map is the one std uses; reach for another only to study it.
43
+ # the tree balanced. Map is the only one in std: it used to hold one file for each
44
+ # (WeightBalancedTree, AvlTree, RedBlackTree, Treap), and their operations that Map lacked
45
+ # (`rank`, `range`, `join`) are here now.
43
- # - weight-balanced tree: the very structure Map is (it was ported from std's
46
+ # - weight-balanced tree: the very structure Map is; balances on subtree sizes, which
44
- # WeightBalancedTree); balances on subtree sizes, which is what gives O(1) `length`
45
- # and O(log n) `entryAt`/`indexOf` for free.
47
+ # is what gives O(1) `length` and O(log n) `entryAt`/`indexOf`/`rank` for free.
46
48
  # - AVL tree: balances on subtree heights (the two sides differ by at most 1). Slightly
47
49
  # shallower, so lookups compare a little less; it stores a height, not a size, so
48
50
  # `length` and positional lookups need an extra field.
@@ -286,6 +288,45 @@ enum Map[K, V] =
286
288
  c := k.compare(nk)
287
289
  if c < 0 then l.indexFrom(k, n) else if c > 0 then r.indexFrom(k, n + l.length() + 1) else Some(n + l.length())
288
290
 
291
+ # The number of keys before `k`, whether `k` is present or not: the position `k` has, or
292
+ # would have, in key order (`indexOf(k)` when it is present).
293
+ fun rank(self, k: K) -> Int = self.rankFrom(k, 0)
294
+
295
+ fun rankFrom(self, k: K, n: Int) -> Int = match self
296
+ MapTip => n
297
+ MapBin(_, nk, _, l, r) =>
298
+ c := k.compare(nk)
299
+ if c < 0 then l.rankFrom(k, n) else if c > 0 then r.rankFrom(k, n + l.length() + 1) else n + l.length()
300
+
301
+ # The entries with keys at or after `lo`, sharing nodes with this map. O(log n).
302
+ fun from(self, lo: K) -> Map[K, V] = match self
303
+ MapTip => self
304
+ MapBin(_, nk, nv, l, r) =>
305
+ c := nk.compare(lo)
306
+ if c < 0 then r.from(lo) else if c == 0 then r.insertMin(nk, nv) else Map.link(nk, nv, l.from(lo), r)
307
+
308
+ # The entries with keys before `hi`. O(log n).
309
+ fun until(self, hi: K) -> Map[K, V] = match self
310
+ MapTip => self
311
+ MapBin(_, nk, nv, l, r) =>
312
+ if nk.compare(hi) >= 0 then l.until(hi) else Map.link(nk, nv, l, r.until(hi))
313
+
314
+ # The entries with `lo <= key < hi` (half open, so adjacent ranges don't overlap); empty
315
+ # when `hi` is not after `lo`. O(log n).
316
+ fun range(self, lo: K, hi: K) -> Map[K, V] = self.from(lo).until(hi)
317
+
318
+ # `fold` over the entries with `lo <= key < hi` only, in key order, without building
319
+ # their map: O(log n) plus the entries visited.
320
+ fun foldRange[A](self, lo: K, hi: K, acc: A, f: fn(A, K, V) -> A) -> A = match self
321
+ MapTip => acc
322
+ MapBin(_, k, v, l, r) =>
323
+ if k.compare(lo) < 0
324
+ r.foldRange(lo, hi, acc, f)
325
+ else if k.compare(hi) >= 0
326
+ l.foldRange(lo, hi, acc, f)
327
+ else
328
+ r.foldRange(lo, hi, f(l.foldRange(lo, hi, acc, f), k, v), f)
329
+
289
330
  # The entries with keys before `k` (`first`) and after `k` (`second`); an entry for `k`
290
331
  # itself is in neither (read it with `get`).
291
332
  fun split(self, k: K) -> Pair[Map[K, V], Map[K, V]] =
@@ -294,6 +335,19 @@ enum Map[K, V] =
294
335
 
295
336
  # ---- combining ----
296
337
 
338
+ # Every entry of `self` followed by every entry of `other`, the inverse of `split`:
339
+ # every key of `self` must come before every key of `other` (it crashes otherwise; for
340
+ # maps that overlap use `union`). O(log n).
341
+ fun join(self, other: Map[K, V]) -> Map[K, V] =
342
+ ordered := match self.max()
343
+ None => true
344
+ Some(a) => match other.min()
345
+ None => true
346
+ Some(b) => a.first.compare(b.first) < 0
347
+ if !ordered
348
+ crash "Map.join: the keys of the left map must all come before the keys of the right one"
349
+ Map.merge(self, other)
350
+
297
351
  # Every entry of either map; for a key in both, the value from `self` (left-biased).
298
352
  fun union(self, other: Map[K, V]) -> Map[K, V] = match other
299
353
  MapTip => self
@@ -671,6 +725,10 @@ struct MapTestWord(text: Str) =
671
725
 
672
726
  fun toStr(self) -> Str = self.text
673
727
 
728
+ # A key type that orders Ints largest first.
729
+ struct MapTestDesc(n: Int) =
730
+ fun compare(self, o: MapTestDesc) -> Int = o.n.compare(self.n)
731
+
674
732
  test "an empty map"
675
733
  m: Map[Int, Int] := Map.empty()
676
734
  assert m.isEmpty() && m.length() == 0 && m.height() == 0
@@ -688,6 +746,23 @@ test "an empty map"
688
746
  assert m == Map[Int, Int]()
689
747
  assert mapValid(m)
690
748
 
749
+ test "one entry"
750
+ m := Map.single(7, "seven")
751
+ assert m.length() == 1 && !m.isEmpty() && m.height() == 1
752
+ assert m.get(7)! == "seven" && m.get(8).isNone()
753
+ assert m.min()!.first == 7 && m.max()!.first == 7 && m.entryAt(0)!.second == "seven"
754
+ assert m.toStr() == "[7 => seven]" && m == Map[Int, Str]().with(7, "seven")
755
+ assert m.remove(7).isEmpty() && m.removeMin().isEmpty() && m.removeMax().isEmpty()
756
+ assert m.rank(7) == 0 && m.rank(8) == 1 && m.range(7, 8) == m && m.range(8, 9).isEmpty()
757
+
758
+ test "a key type's compare is the order: largest first"
759
+ m := [1, 5, 3, 9, 7].fold(Map[MapTestDesc, Int](), |acc, n| acc.with(MapTestDesc(n: n), n * 10))
760
+ assert m.keys().map(|k| k.n).toStr() == "[9,7,5,3,1]"
761
+ assert m.min()!.first.n == 9 && m.max()!.first.n == 1 && m.entryAt(1)!.second == 70
762
+ assert m.rank(MapTestDesc(n: 4)) == 3 && m.get(MapTestDesc(n: 3))! == 30
763
+ assert m.remove(MapTestDesc(n: 7)).keys().map(|k| k.n).toStr() == "[9,5,3,1]"
764
+ assert m.range(MapTestDesc(n: 7), MapTestDesc(n: 1)).keys().map(|k| k.n).toStr() == "[7,5,3]"
765
+
691
766
  test "with, get, has, getOr and set"
692
767
  m := Map[Str, Int]().with("b", 2).with("a", 1).set("c", 3)
693
768
  assert m.length() == 3
@@ -785,6 +860,66 @@ test "entryAt and indexOf count positions in key order"
785
860
  for i := range 5
786
861
  assert m.indexOf(m.entryAt(i)!.first)! == i
787
862
 
863
+ test "rank counts the keys before k, present or not"
864
+ m := [10 => 1, 20 => 2, 30 => 3, 40 => 4, 50 => 5]
865
+ assert m.rank(10) == 0 && m.rank(30) == 2 && m.rank(50) == 4
866
+ assert m.rank(5) == 0 && m.rank(35) == 3 && m.rank(99) == 5
867
+ for i := range 5
868
+ assert m.rank(m.entryAt(i)!.first) == i
869
+ e: Map[Int, Int] := Map.empty()
870
+ assert e.rank(7) == 0
871
+ w := [MapTestWord(text: "pear") => 1, MapTestWord(text: "apple") => 2, MapTestWord(text: "zucchini") => 3, MapTestWord(text: "fig") => 4]
872
+ assert w.rank(MapTestWord(text: "kiwi")) == 1 && w.entryAt(1)!.first.text == "pear"
873
+ big := mapRemoveFrom(mapRange(Map.empty(), 0, 10000), 0, 10000, 2)
874
+ assert big.rank(5001) == 2500 && big.rank(5000) == 2500 && big.rank(-1) == 0 && big.rank(10000) == 5000
875
+
876
+ test "from, until and range: lo <= key < hi, sharing the map, staying balanced"
877
+ m := mapRange(Map.empty(), 1, 9)
878
+ assert m.range(3, 6).keys().toStr() == "[3,4,5]"
879
+ assert m.range(0, 100).length() == 8 && m.range(0, 100) == m
880
+ assert m.range(5, 5).isEmpty() && m.range(6, 3).isEmpty() && m.range(9, 20).isEmpty()
881
+ assert m.from(6).keys().toStr() == "[6,7,8]" && m.from(0) == m && m.from(9).isEmpty()
882
+ assert m.until(3).keys().toStr() == "[1,2]" && m.until(100) == m && m.until(1).isEmpty()
883
+ assert mapValid(m.range(2, 7)) && m.range(2, 7).get(4)! == 8
884
+ assert m.length() == 8
885
+ odd := [1 => 0, 3 => 0, 5 => 0, 7 => 0]
886
+ assert odd.range(2, 6).keys().toStr() == "[3,5]" && odd.from(4).keys().toStr() == "[5,7]" && odd.until(4).keys().toStr() == "[1,3]"
887
+
888
+ test "range and foldRange agree with a filter over pseudo-random maps"
889
+ for seed := range 1.to(10)
890
+ m := mapRandom(seed, 200, 400, 0)
891
+ x := mapLcg(seed * 31)
892
+ lo := x % 450 - 25
893
+ hi := {x / 450} % 450 - 25
894
+ r := m.range(lo, hi)
895
+ assert mapValid(r) && mapValid(m.from(lo)) && mapValid(m.until(hi))
896
+ assert r.keys().toStr() == mapKeysWhere(400, |k| m.has(k) && k >= lo && k < hi)
897
+ assert m.from(lo).keys().toStr() == mapKeysWhere(400, |k| m.has(k) && k >= lo)
898
+ assert m.until(hi).keys().toStr() == mapKeysWhere(400, |k| m.has(k) && k < hi)
899
+ assert r.all(|k, v| v == m.get(k)!)
900
+ assert m.foldRange(lo, hi, 0, |a, k, v| a + 1) == r.length()
901
+ assert m.foldRange(lo, hi, "", |a, k, v| "{a}{k}={v};") == r.fold("", |a, k, v| "{a}{k}={v};")
902
+ assert m.rank(lo) + r.length() + {m.length() - m.rank(hi.max(lo))} == m.length()
903
+ m := mapRange(Map.empty(), 0, 1000)
904
+ assert m.foldRange(10, 20, 0, |a, k, v| a + v) == 290
905
+ assert m.foldRange(20, 10, 0, |a, k, v| a + v) == 0 && m.foldRange(-5, 1, 7, |a, k, v| a + k) == 7
906
+
907
+ test "join puts two ordered maps back together, the inverse of split"
908
+ t := mapRange(Map.empty(), 1, 10)
909
+ p := t.split(5)
910
+ j := p.first.join(p.second)
911
+ assert j.keys().toStr() == "[1,2,3,4,6,7,8,9]" && mapValid(j)
912
+ e: Map[Int, Int] := Map.empty()
913
+ assert e.join(t) == t && t.join(e) == t && e.join(e).isEmpty()
914
+ assert [1 => 1, 2 => 2].join([10 => 10, 20 => 20]).keys().toStr() == "[1,2,10,20]"
915
+ big := mapRange(Map.empty(), 0, 5000)
916
+ one := big.until(3).join(big.from(4990))
917
+ assert one.length() == 13 && mapValid(one)
918
+ for cut := range [1, 7, 2500, 4999]
919
+ back := big.until(cut).join(big.from(cut))
920
+ assert back == big && mapValid(back)
921
+ assert t.length() == 9
922
+
788
923
  test "split leaves out the key and keeps both halves valid"
789
924
  t := mapRange(Map.empty(), 1, 10)
790
925
  p := t.split(4)
std/collections/PairingHeap.plum CHANGED
@@ -7,7 +7,7 @@ import std/Pair
7
7
  import std/collections/List
8
8
  import std/Slice
9
9
 
10
- # `PairingHeap`, written functionally (see std/collections/AvlTree
10
+ # `PairingHeap`, written functionally (see docs/std.md
11
11
  # for the rules these persistent collections follow): a persistent mergeable MIN-heap kept as a pairing heap, a
12
12
  # tree in heap order (no element is before its parent) whose nodes keep their children in
13
13
  # a `List`. `push` and `merge` are O(1): the root that comes later becomes the
std/collections/Quadtree.plum CHANGED
@@ -11,7 +11,7 @@ import std/Slice
11
11
  import std/collections/List
12
12
 
13
13
  # `Quadtree`, written functionally (see
14
- # std/collections/AvlTree for the rules these persistent collections follow): a persistent
14
+ # docs/std.md for the rules these persistent collections follow): a persistent
15
15
  # point-region quadtree, values at `Vec2` points inside a fixed `bounds` box. A leaf
16
16
  # holds up to `capacity` entries as a cons list (newest first); one more splits it into
17
17
  # four quarters at its center, down to `maxDepth` levels, where leaves just grow (so
std/collections/RadixTree.plum CHANGED
@@ -9,7 +9,7 @@ import std/Slice
9
9
  import std/collections/Map
10
10
  import std/collections/Trie
11
11
 
12
- # `RadixTree`, written functionally (see std/collections/AvlTree
12
+ # `RadixTree`, written functionally (see docs/std.md
13
13
  # for the rules these persistent collections follow): a persistent map from `Str` keys to values, a radix
14
14
  # tree (compressed trie) where each edge is labelled with a non-empty run of key bytes,
15
15
  # so a chain of single-child nodes becomes one edge. Each node holds an optional value
std/collections/RedBlackTree.plum DELETED
@@ -1,497 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Str
5
- import std/Option
6
- import std/Pair
7
- import std/collections/List
8
- import std/collections/Map
9
- import std/Slice
10
-
11
- # A red-black tree written functionally (see std/collections/AvlTree for
12
- # the rules these persistent collections follow): a persistent ordered map kept as a red-black tree. Every
13
- # node is red or black, the root is black, a red node never has a red child, and every
14
- # path from a node down to a leaf passes the same number of black nodes, so the height
15
- # stays under 2 * log2(n + 1). `insert` and `remove` rebuild the O(log n) nodes on the
16
- # path to the key and share everything else; the old tree stays as it was. Insert
17
- # rebalances with Okasaki's four rotations; remove uses Kahrs's persistent deletion
18
- # (`balLeft`, `balRight` and `fuse`).
19
- # Keys are ordered by `before(a, b)` ("a belongs before b", strictly), stored in the
20
- # wrapper: `RedBlackTree.by(|a, b| a > b)` keeps keys descending, `RedBlackTree.ints()`
21
- # ascending. `entries`, `keys` and `values` return a `List`.
22
- # `get`, `min` and `max` are tail-recursive methods on the enum, cascades of pattern
23
- # tests are `match` arms (with small helpers where a cascade fell through), `collect`
24
- # conses onto an accumulator, and `toStr` joins with `List.join`.
25
- # `get`/`has`/`insert`/`remove`/`min`/`max` are O(log n); `length` is O(1). Recursion
26
- # follows one path, so the stack depth is O(log n); `entries` is O(log n) deep too.
27
- struct RedBlackTree[K, V](root: RbBranch[K, V], size: Int, before: fn(K, K) -> Bool) =
28
-
29
- # The empty tree ordered by `before`.
30
- fun by(before: fn(K, K) -> Bool) -> RedBlackTree[K, V] =
31
- leaf: RbBranch[K, V] := RbLeaf
32
- RedBlackTree(root: leaf, size: 0, before: before)
33
-
34
- # The empty tree of `Int` keys in ascending order.
35
- fun ints() -> RedBlackTree[Int, V] =
36
- leaf: RbBranch[Int, V] := RbLeaf
37
- RedBlackTree(root: leaf, size: 0, before: |a, b| a < b)
38
-
39
- fun length(self) -> Int = self.size
40
-
41
- fun isEmpty(self) -> Bool = self.size == 0
42
-
43
- # The number of nodes on the longest root-to-leaf path (0 when empty).
44
- fun height(self) -> Int = self.root.height()
45
-
46
- # The value stored for `k`, or None.
47
- fun get(self, k: K) -> Option[V] = self.root.get(k, self.before)
48
-
49
- fun has(self, k: K) -> Bool = self.get(k).isSome()
50
-
51
- # A tree with `k` mapped to `v`, replacing the value of an existing `k`.
52
- fun insert(self, k: K, v: V) -> RedBlackTree[K, V] =
53
- root := self.root.ins(k, v, self.before).blacken()
54
- if self.has(k)
55
- RedBlackTree(root: root, size: self.size, before: self.before)
56
- else
57
- RedBlackTree(root: root, size: self.size + 1, before: self.before)
58
-
59
- # A tree without `k`; the same tree when `k` is absent.
60
- fun remove(self, k: K) -> RedBlackTree[K, V] =
61
- if !self.has(k)
62
- self
63
- else
64
- RedBlackTree(root: self.root.del(k, self.before).blacken(), size: self.size - 1, before: self.before)
65
-
66
- # The entry with the smallest key, or None if empty.
67
- fun min(self) -> Option[Pair[K, V]] = self.root.min()
68
-
69
- # The entry with the largest key, or None if empty.
70
- fun max(self) -> Option[Pair[K, V]] = self.root.max()
71
-
72
- # Every key with its value, in ascending key order (`e.first`, `e.second`).
73
- fun entries(self) -> List[Pair[K, V]] =
74
- nil: List[Pair[K, V]] := Nil
75
- self.root.collect(nil)
76
-
77
- # Every key, in ascending order.
78
- fun keys(self) -> List[K] = self.entries().map(|e| e.first)
79
-
80
- # Every value, in ascending key order.
81
- fun values(self) -> List[V] = self.entries().map(|e| e.second)
82
-
83
- # The entries in key order: `[1: one, 2: two]`.
84
- fun toStr(self) -> Str = "[" + self.entries().join(", ") + "]"
85
-
86
- # The nodes of a `RedBlackTree`: `RbLeaf` (black), or a red or black node with its
87
- # key and value, the subtree of smaller keys on the left and larger on the right. The
88
- # functions follow Kahrs, "Red-black trees with types" (2001).
89
- enum RbBranch[K, V] =
90
- | RbLeaf
91
- | RbNode(red: Bool, key: K, value: V, left: RbBranch[K, V], right: RbBranch[K, V])
92
-
93
- fun isEmpty(self) -> Bool = match self
94
- RbLeaf => true
95
- RbNode(_, _, _, _, _) => false
96
-
97
- fun isRed(self) -> Bool = match self
98
- RbNode(true, _, _, _, _) => true
99
- _ => false
100
-
101
- # A black node (not a leaf).
102
- fun isBlackNode(self) -> Bool = match self
103
- RbNode(false, _, _, _, _) => true
104
- _ => false
105
-
106
- fun height(self) -> Int = match self
107
- RbLeaf => 0
108
- RbNode(_, _, _, l, r) => l.height().max(r.height()) + 1
109
-
110
- # Tail recursive: one comparison per level.
111
- fun get(self, k: K, before: fn(K, K) -> Bool) -> Option[V] = match self
112
- RbLeaf => None
113
- RbNode(_, nk, nv, l, r) =>
114
- if before(k, nk)
115
- l.get(k, before)
116
- else if before(nk, k)
117
- r.get(k, before)
118
- else
119
- Some(nv)
120
-
121
- fun min(self) -> Option[Pair[K, V]] = match self
122
- RbLeaf => None
123
- RbNode(_, nk, nv, RbLeaf, _) => Some(Pair(first: nk, second: nv))
124
- RbNode(_, _, _, l, _) => l.min()
125
-
126
- fun max(self) -> Option[Pair[K, V]] = match self
127
- RbLeaf => None
128
- RbNode(_, nk, nv, _, RbLeaf) => Some(Pair(first: nk, second: nv))
129
- RbNode(_, _, _, _, r) => r.max()
130
-
131
- fun red(l: RbBranch[K, V], k: K, v: V, r: RbBranch[K, V]) -> RbBranch[K, V] =
132
- RbNode(red: true, key: k, value: v, left: l, right: r)
133
-
134
- fun black(l: RbBranch[K, V], k: K, v: V, r: RbBranch[K, V]) -> RbBranch[K, V] =
135
- RbNode(red: false, key: k, value: v, left: l, right: r)
136
-
137
- # The node painted black (a leaf stays a leaf).
138
- fun blacken(self) -> RbBranch[K, V] = match self
139
- RbNode(true, k, v, l, r) => RbBranch.black(l, k, v, r)
140
- _ => self
141
-
142
- # A black node painted red, lowering its black height by one. Only called on a
143
- # black node; anything else means the tree's invariants were broken.
144
- fun redden(self) -> RbBranch[K, V] = match self
145
- RbNode(false, k, v, l, r) => RbBranch.red(l, k, v, r)
146
- _ => self.broken()
147
-
148
- fun broken(self) -> RbBranch[K, V] =
149
- crash "RedBlackTree: invariant broken"
150
-
151
- # A black node over `l` and `r`, rotated and recoloured when either child is red
152
- # with a red child (Okasaki's four cases; when both children are red they are just
153
- # turned black under a red root, as in Kahrs). This half handles a red `l`.
154
- fun balance(l: RbBranch[K, V], k: K, v: V, r: RbBranch[K, V]) -> RbBranch[K, V] =
155
- if l.isRed() && r.isRed()
156
- RbBranch.red(l.blacken(), k, v, r.blacken())
157
- else
158
- match l
159
- RbNode(true, lk, lv, RbNode(true, xk, xv, a1, a2), b) => RbBranch.red(RbBranch.black(a1, xk, xv, a2), lk, lv, RbBranch.black(b, k, v, r))
160
- RbNode(true, lk, lv, a, RbNode(true, yk, yv, b1, b2)) => RbBranch.red(RbBranch.black(a, lk, lv, b1), yk, yv, RbBranch.black(b2, k, v, r))
161
- _ => RbBranch.balanceRight(l, k, v, r)
162
-
163
- # The second half of `balance`: a red `r` with a red child.
164
- fun balanceRight(l: RbBranch[K, V], k: K, v: V, r: RbBranch[K, V]) -> RbBranch[K, V] = match r
165
- RbNode(true, rk, rv, c, RbNode(true, zk, zv, d1, d2)) => RbBranch.red(RbBranch.black(l, k, v, c), rk, rv, RbBranch.black(d1, zk, zv, d2))
166
- RbNode(true, rk, rv, RbNode(true, yk, yv, c1, c2), d) => RbBranch.red(RbBranch.black(l, k, v, c1), yk, yv, RbBranch.black(c2, rk, rv, d))
167
- _ => RbBranch.black(l, k, v, r)
168
-
169
- # Inserts below this node; the result may be a red root with a red child, which
170
- # the caller's `balance` (or `blacken` at the top) repairs.
171
- fun ins(self, k: K, v: V, before: fn(K, K) -> Bool) -> RbBranch[K, V] = match self
172
- RbLeaf => RbBranch.red(self, k, v, self)
173
- RbNode(isRed, nk, nv, l, r) =>
174
- if before(k, nk)
175
- if isRed
176
- RbBranch.red(l.ins(k, v, before), nk, nv, r)
177
- else
178
- RbBranch.balance(l.ins(k, v, before), nk, nv, r)
179
- else if before(nk, k)
180
- if isRed
181
- RbBranch.red(l, nk, nv, r.ins(k, v, before))
182
- else
183
- RbBranch.balance(l, nk, nv, r.ins(k, v, before))
184
- else
185
- RbNode(red: isRed, key: nk, value: v, left: l, right: r)
186
-
187
- # Removes `k` below this node. Removing from a black subtree lowers its black height
188
- # by one, which `balLeft`/`balRight` make up for.
189
- fun del(self, k: K, before: fn(K, K) -> Bool) -> RbBranch[K, V] = match self
190
- RbLeaf => self
191
- RbNode(_, nk, nv, l, r) =>
192
- if before(k, nk)
193
- if l.isBlackNode()
194
- RbBranch.balLeft(l.del(k, before), nk, nv, r)
195
- else
196
- RbBranch.red(l.del(k, before), nk, nv, r)
197
- else if before(nk, k)
198
- if r.isBlackNode()
199
- RbBranch.balRight(l, nk, nv, r.del(k, before))
200
- else
201
- RbBranch.red(l, nk, nv, r.del(k, before))
202
- else
203
- RbBranch.fuse(l, r)
204
-
205
- # A node over `l` and `r` where `l`'s black height is one less than `r`'s.
206
- fun balLeft(l: RbBranch[K, V], k: K, v: V, r: RbBranch[K, V]) -> RbBranch[K, V] = match l
207
- RbNode(true, lk, lv, a, b) => RbBranch.red(RbBranch.black(a, lk, lv, b), k, v, r)
208
- _ =>
209
- match r
210
- RbNode(false, _, _, _, _) => RbBranch.balance(l, k, v, r.redden())
211
- RbNode(true, rk, rv, RbNode(false, bk, bv, b1, b2), c) => RbBranch.red(RbBranch.black(l, k, v, b1), bk, bv, RbBranch.balance(b2, rk, rv, c.redden()))
212
- _ => l.broken()
213
-
214
- # A node over `l` and `r` where `r`'s black height is one less than `l`'s.
215
- fun balRight(l: RbBranch[K, V], k: K, v: V, r: RbBranch[K, V]) -> RbBranch[K, V] = match r
216
- RbNode(true, rk, rv, a, b) => RbBranch.red(l, k, v, RbBranch.black(a, rk, rv, b))
217
- _ =>
218
- match l
219
- RbNode(false, _, _, _, _) => RbBranch.balance(l.redden(), k, v, r)
220
- RbNode(true, lk, lv, a, RbNode(false, bk, bv, b1, b2)) => RbBranch.red(RbBranch.balance(a.redden(), lk, lv, b1), bk, bv, RbBranch.black(b2, k, v, r))
221
- _ => l.broken()
222
-
223
- # The two subtrees of a removed node, of equal black height, joined into one (every
224
- # key of `a` is before every key of `b`).
225
- fun fuse(a: RbBranch[K, V], b: RbBranch[K, V]) -> RbBranch[K, V] = match a
226
- RbLeaf => b
227
- RbNode(true, ak, av, al, ar) =>
228
- match b
229
- RbLeaf => a
230
- RbNode(true, bk, bv, bl, br) => RbBranch.fuseReds(al, ak, av, RbBranch.fuse(ar, bl), bk, bv, br)
231
- RbNode(_, _, _, _, _) => RbBranch.red(al, ak, av, RbBranch.fuse(ar, b))
232
- RbNode(_, ak, av, al, ar) =>
233
- match b
234
- RbLeaf => a
235
- RbNode(true, bk, bv, bl, br) => RbBranch.red(RbBranch.fuse(a, bl), bk, bv, br)
236
- RbNode(_, bk, bv, bl, br) => RbBranch.fuseBlacks(al, ak, av, RbBranch.fuse(ar, bl), bk, bv, br)
237
-
238
- # `fuse` of two red nodes, given `m`, the fused inner subtrees `ar` and `bl`.
239
- fun fuseReds(al: RbBranch[K, V], ak: K, av: V, m: RbBranch[K, V], bk: K, bv: V, br: RbBranch[K, V]) -> RbBranch[K, V] = match m
240
- RbNode(true, mk, mv, ml, mr) => RbBranch.red(RbBranch.red(al, ak, av, ml), mk, mv, RbBranch.red(mr, bk, bv, br))
241
- _ => RbBranch.red(al, ak, av, RbBranch.red(m, bk, bv, br))
242
-
243
- # `fuse` of two black nodes, given `m`, the fused inner subtrees `ar` and `bl`.
244
- fun fuseBlacks(al: RbBranch[K, V], ak: K, av: V, m: RbBranch[K, V], bk: K, bv: V, br: RbBranch[K, V]) -> RbBranch[K, V] = match m
245
- RbNode(true, mk, mv, ml, mr) => RbBranch.red(RbBranch.black(al, ak, av, ml), mk, mv, RbBranch.black(mr, bk, bv, br))
246
- _ => RbBranch.balLeft(al, ak, av, RbBranch.black(m, bk, bv, br))
247
-
248
- # The entries in key order, in front of `acc`: right subtree first, so each entry is
249
- # consed onto the ones after it.
250
- fun collect(self, acc: List[Pair[K, V]]) -> List[Pair[K, V]] = match self
251
- RbLeaf => acc
252
- RbNode(_, nk, nv, l, r) => l.collect(Cons(head: Pair(first: nk, second: nv), tail: r.collect(acc)))
253
-
254
- # ---------------------------------------------------------------------------
255
- # Test helpers. Tests may use loops, `mut` fields and std's `Map` as the
256
- # reference model; the structure above may not.
257
- # ---------------------------------------------------------------------------
258
-
259
- fun rbInts() -> RedBlackTree[Int, Int] =
260
- t: RedBlackTree[Int, Int] := RedBlackTree.ints()
261
- t
262
-
263
- # Inserts each key `k` with value `k * 10`, in order.
264
- fun rbOf(keys: List[Int]) -> RedBlackTree[Int, Int] =
265
- keys.fold(rbInts(), |t, k| t.insert(k, k * 10))
266
-
267
- # The black height of `t` (leaves count as one) when no red node has a red child and
268
- # every path has the same number of black nodes, else -1.
269
- fun rbBlackHeight(t: RbBranch[Int, Int]) -> Int = match t
270
- RbLeaf => 1
271
- RbNode(isRed, _, _, l, r) =>
272
- if isRed && {l.isRed() || r.isRed()}
273
- -1
274
- else
275
- hl := rbBlackHeight(l)
276
- hr := rbBlackHeight(r)
277
- if hl < 0 || hl != hr
278
- -1
279
- else if isRed
280
- hl
281
- else
282
- hl + 1
283
-
284
- # True when the keys of `ks` are strictly ascending.
285
- fun rbAscending(ks: List[Int]) -> Bool = match ks
286
- Cons(a, Cons(b, rest)) =>
287
- if a >= b
288
- false
289
- else
290
- rbAscending(Cons(head: b, tail: rest))
291
- _ => true
292
-
293
- # The red-black invariants: a black root, no red-red, equal black heights, keys
294
- # strictly ascending in order, and `length` matching the node count.
295
- fun rbValid(t: RedBlackTree[Int, Int]) -> Bool =
296
- if t.root.isRed() || rbBlackHeight(t.root) < 0
297
- false
298
- else
299
- ks := t.keys()
300
- ks.length() == t.length() && rbAscending(ks)
301
-
302
- # Inserts `lo` to `hi - 1` (value = key), as a tail call.
303
- fun rbRange(t: RedBlackTree[Int, Int], lo: Int, hi: Int) -> RedBlackTree[Int, Int] =
304
- if lo >= hi
305
- t
306
- else
307
- rbRange(t.insert(lo, lo), lo + 1, hi)
308
-
309
- # Removes `i`, `i - step`, ... down to 0, as a tail call.
310
- fun rbRemoveDown(t: RedBlackTree[Int, Int], i: Int, step: Int) -> RedBlackTree[Int, Int] =
311
- if i < 0
312
- t
313
- else
314
- rbRemoveDown(t.remove(i), i - step, step)
315
-
316
- # The number of keys `i` in `lo` to `hi - 1` whose value is not `i`.
317
- fun rbBadRange(t: RedBlackTree[Int, Int], lo: Int, hi: Int, bad: Int) -> Int =
318
- if lo >= hi
319
- bad
320
- else if t.get(lo).unwrapOr(-1) == lo
321
- rbBadRange(t, lo + 1, hi, bad)
322
- else
323
- rbBadRange(t, lo + 1, hi, bad + 1)
324
-
325
- # Removes each key of `ks` in turn; false as soon as a tree on the way is invalid.
326
- fun rbRemoveAllValid(t: RedBlackTree[Int, Int], ks: List[Int]) -> Bool = match ks
327
- Nil => t.isEmpty() && t.root.isEmpty()
328
- Cons(k, rest) =>
329
- u := t.remove(k)
330
- if !rbValid(u)
331
- false
332
- else
333
- rbRemoveAllValid(u, rest)
334
-
335
- # The state of the random-operations test: the tree, the generator and the model.
336
- struct RbTestRun(mut t: RedBlackTree[Int, Int], mut x: Int, mut m: Map[Int, Int])
337
-
338
- test "an empty tree"
339
- t := rbInts()
340
- assert t.isEmpty()
341
- assert t.length() == 0
342
- assert t.height() == 0
343
- assert t.get(1).isNone()
344
- assert t.has(1) == false
345
- assert t.min().isNone()
346
- assert t.max().isNone()
347
- assert t.entries().isEmpty()
348
- assert t.toStr() == "[]"
349
- assert t.remove(1).isEmpty()
350
- assert rbValid(t)
351
-
352
- test "one element"
353
- t := rbInts().insert(7, 70)
354
- assert t.length() == 1
355
- assert t.height() == 1
356
- assert t.get(7)! == 70
357
- assert t.min()!.first == 7 && t.max()!.first == 7
358
- assert t.toStr() == "[7: 70]"
359
- assert rbValid(t)
360
- assert t.remove(7).isEmpty()
361
- assert t.remove(8).length() == 1
362
-
363
- test "insert, get and has"
364
- t := rbOf([5, 3, 8, 1, 4])
365
- assert t.length() == 5
366
- assert t.get(3)! == 30
367
- assert t.get(8)! == 80
368
- assert t.get(7).isNone()
369
- assert t.has(1)
370
- assert t.has(2) == false
371
- assert rbValid(t)
372
-
373
- test "insert replaces the value of an existing key"
374
- t := rbOf([1, 2, 3]).insert(2, 99)
375
- assert t.length() == 3
376
- assert t.get(2)! == 99
377
- assert t.toStr() == "[1: 10, 2: 99, 3: 30]"
378
- assert rbValid(t)
379
- dup := rbOf([4, 4, 4, 2, 2])
380
- assert dup.length() == 2
381
- assert rbValid(dup)
382
-
383
- test "min, max, entries, keys, values and toStr are in key order"
384
- t := rbOf([4, 2, 9, 7, 1])
385
- assert t.min()!.first == 1
386
- assert t.min()!.second == 10
387
- assert t.max()!.first == 9
388
- assert t.keys().toStr() == "[1,2,4,7,9]"
389
- assert t.values().toStr() == "[10,20,40,70,90]"
390
- assert t.entries().length() == 5
391
- assert t.entries().at(2).first == 4
392
- assert rbOf([2, 1]).toStr() == "[1: 10, 2: 20]"
393
-
394
- test "three ascending inserts rotate the middle key to a black root"
395
- t := rbOf([1, 2, 3])
396
- match t.root
397
- RbNode(isRed, k, _, l, r) =>
398
- assert isRed == false
399
- assert k == 2
400
- assert l.isBlackNode()
401
- assert r.isBlackNode()
402
- RbLeaf =>
403
- assert false
404
- assert rbValid(rbOf([3, 2, 1]))
405
- assert rbValid(rbOf([1, 3, 2]))
406
- assert rbValid(rbOf([3, 1, 2]))
407
-
408
- test "the invariant checker rejects a red-red pair and unequal black heights"
409
- e: RbBranch[Int, Int] := RbLeaf
410
- redRed := RbBranch.black(RbBranch.red(RbBranch.red(e, 1, 10, e), 2, 20, e), 3, 30, e)
411
- assert rbBlackHeight(redRed) == -1
412
- uneven := RbBranch.black(RbBranch.black(e, 1, 10, e), 2, 20, e)
413
- assert rbBlackHeight(uneven) == -1
414
- fine := RbBranch.black(RbBranch.red(e, 1, 10, e), 2, 20, e)
415
- assert rbBlackHeight(fine) == 2
416
- unordered := RedBlackTree(root: RbBranch.black(e, 5, 50, RbBranch.red(e, 1, 10, e)), size: 2, before: |a, b| a < b)
417
- assert rbValid(unordered) == false
418
-
419
- test "remove a leaf, an inner node, the root, missing keys and everything"
420
- t := rbOf([50, 30, 70, 20, 40, 60, 80, 10, 35, 45, 65])
421
- a := t.remove(10)
422
- assert a.has(10) == false
423
- assert a.length() == 10
424
- assert rbValid(a)
425
- b := t.remove(30)
426
- assert b.keys().toStr() == "[10,20,35,40,45,50,60,65,70,80]"
427
- assert rbValid(b)
428
- c := t.remove(50)
429
- assert c.has(50) == false
430
- assert c.length() == 10
431
- assert rbValid(c)
432
- d := t.remove(99)
433
- assert d.length() == 11
434
- assert rbValid(d)
435
- assert rbRemoveAllValid(t, t.keys())
436
- assert rbRemoveAllValid(t, t.keys().reverse())
437
-
438
- test "old versions are unchanged after insert and remove"
439
- t1 := rbOf([1, 2, 3, 4, 5])
440
- t2 := t1.insert(6, 60)
441
- t3 := t2.remove(1).insert(3, 0)
442
- assert t1.keys().toStr() == "[1,2,3,4,5]"
443
- assert t1.get(3)! == 30
444
- assert t2.keys().toStr() == "[1,2,3,4,5,6]"
445
- assert t2.get(3)! == 30
446
- assert t3.keys().toStr() == "[2,3,4,5,6]"
447
- assert t3.get(3)! == 0
448
- assert rbValid(t1) && rbValid(t2) && rbValid(t3)
449
- t4 := t3.remove(2).remove(4).remove(6)
450
- assert t4.keys().toStr() == "[3,5]"
451
- assert t3.toStr() == "[2: 20, 3: 0, 4: 40, 5: 50, 6: 60]"
452
- assert t1.toStr() == "[1: 10, 2: 20, 3: 30, 4: 40, 5: 50]"
453
-
454
- test "10,000 ascending keys stay balanced; removing half keeps it valid"
455
- n := 10000
456
- t := rbRange(rbInts(), 0, n)
457
- assert t.length() == n
458
- assert rbValid(t)
459
- assert t.height() <= 28
460
- assert t.min()!.first == 0
461
- assert t.max()!.first == n - 1
462
- assert rbBadRange(t, 0, n, 0) == 0
463
- u := rbRemoveDown(t, n - 1, 2)
464
- assert u.length() == 5000
465
- assert rbValid(u)
466
- assert u.has(9998)
467
- assert u.has(9999) == false
468
- assert t.length() == n && t.has(9999)
469
-
470
- test "invariants hold through pseudo-random inserts and removes"
471
- run := RbTestRun(t: rbInts(), x: 12345, m: Map.empty())
472
- for i := range 4000
473
- run.x = {run.x * 1103515245 + 12345} % 2147483648
474
- k := run.x % 500
475
- if run.x % 3 == 0
476
- run.t = run.t.remove(k)
477
- run.m = run.m.remove(k)
478
- else
479
- run.t = run.t.insert(k, i)
480
- run.m = run.m.with(k, i)
481
- assert rbValid(run.t)
482
- assert rbValid(run.t)
483
- assert run.t.length() == run.m.length()
484
- es := run.m.entries()
485
- bad := 0.until(es.length()).fold(0, |b, j| if run.t.get(es.at(j).first)! != es.at(j).second then b + 1 else b)
486
- assert bad == 0
487
-
488
- test "a custom order: longest Str first"
489
- t: RedBlackTree[Str, Int] := RedBlackTree.by(|a, b| a.length() > b.length())
490
- u := t.insert("pear", 1).insert("apple", 2).insert("zucchini", 3).insert("fig", 4)
491
- assert u.keys().toStr() == "[zucchini,apple,pear,fig]"
492
- assert u.min()!.first == "zucchini"
493
- assert u.get("fig")! == 4
494
- assert u.get("bar")! == 4
495
- assert u.remove("pear").keys().toStr() == "[zucchini,apple,fig]"
496
- assert u.insert("kiwi", 9).get("pear")! == 9
497
- assert t.isEmpty()
std/collections/RoseTree.plum CHANGED
@@ -7,7 +7,7 @@ import std/Option
7
7
  import std/collections/List
8
8
  import std/ref
9
9
 
10
- # A rose tree written functionally (see std/collections/AvlTree for the
10
+ # A rose tree written functionally (see docs/std.md for the
11
11
  # rules these persistent collections follow): a persistent tree in which a node has any number of children,
12
12
  # kept in left-child, right-sibling form. A node holds its value, its first child and
13
13
  # its next sibling, so any number of children needs only two links per node. Every
std/collections/SegmentTree.plum CHANGED
@@ -9,7 +9,7 @@ import std/collections/List
9
9
  import std/Slice
10
10
 
11
11
  # `SegmentTree`, written functionally (see
12
- # std/collections/AvlTree for the rules these persistent collections follow): a persistent segment
12
+ # docs/std.md for the rules these persistent collections follow): a persistent segment
13
13
  # tree over a fixed-length sequence of `T`, answering "combine of elements [lo, hi)" while
14
14
  # single elements change. `combine` must be associative and `identity` its neutral
15
15
  # element, so one type covers sums, minimums, maximums, string concatenation and so on;
std/collections/Set.plum CHANGED
@@ -68,6 +68,28 @@ struct Set[T](map: Map[T, Bool]) =
68
68
  # The `i`-th smallest member (from 0), or None out of range.
69
69
  fun at(self, i: Int) -> Option[T] = self.map.entryAt(i).map(|e| e.first)
70
70
 
71
+ # The position of `v` in ascending order (from 0), or None when it is not a member.
72
+ fun indexOf(self, v: T) -> Option[Int] = self.map.indexOf(v)
73
+
74
+ # The number of members before `v`, whether `v` is a member or not.
75
+ fun rank(self, v: T) -> Int = self.map.rank(v)
76
+
77
+ # The members at or after `lo`; the members before `hi`; the members with
78
+ # `lo <= x < hi`. Each O(log n).
79
+ fun from(self, lo: T) -> Set[T] = Set(map: self.map.from(lo))
80
+
81
+ fun until(self, hi: T) -> Set[T] = Set(map: self.map.until(hi))
82
+
83
+ fun range(self, lo: T, hi: T) -> Set[T] = Set(map: self.map.range(lo, hi))
84
+
85
+ # `fold` over the members with `lo <= x < hi` only, without building their set.
86
+ fun foldRange[A](self, lo: T, hi: T, acc: A, f: fn(A, T) -> A) -> A =
87
+ self.map.foldRange(lo, hi, acc, |a, k, v| f(a, k))
88
+
89
+ # The members of `self` followed by the members of `o`: every member of `self` must be
90
+ # before every member of `o` (it crashes otherwise; use `union` for sets that overlap).
91
+ fun join(self, o: Set[T]) -> Set[T] = Set(map: self.map.join(o.map))
92
+
71
93
  # The members before `v` (`first`) and after `v` (`second`).
72
94
  fun split(self, v: T) -> Pair[Set[T], Set[T]] =
73
95
  p := self.map.split(v)
@@ -165,6 +187,23 @@ test "order: min, max, neighbours, at, split, removeMin, removeMax"
165
187
  p := s.split(25)
166
188
  assert p.first.toStr() == "[10, 20]" && p.second.toStr() == "[30, 40]"
167
189
 
190
+ test "rank, indexOf, from, until, range, foldRange and join"
191
+ s := Set.fromList([40, 10, 30, 20, 50])
192
+ assert s.rank(10) == 0 && s.rank(35) == 3 && s.rank(99) == 5
193
+ assert s.indexOf(30)! == 2 && s.indexOf(35).isNone()
194
+ assert s.from(30).toStr() == "[30, 40, 50]" && s.until(30).toStr() == "[10, 20]"
195
+ assert s.range(20, 50).toStr() == "[20, 30, 40]" && s.range(50, 20).isEmpty() && s.range(11, 20).isEmpty()
196
+ assert s.foldRange(15, 45, 0, |acc, x| acc + x) == 90
197
+ assert s.until(30).join(s.from(30)) == s && s.until(25).join(s.from(45)).toStr() == "[10, 20, 50]"
198
+ for seed := range 1.to(6)
199
+ a := setRandom(seed, 150, 300, Set.empty())
200
+ lo := seed * 37
201
+ hi := seed * 41 + 20
202
+ assert a.range(lo, hi).toSlice().toStr() == setWhere(300, |x| a.has(x) && x >= lo && x < hi)
203
+ assert a.foldRange(lo, hi, 0, |n, x| n + 1) == a.range(lo, hi).length()
204
+ assert a.rank(lo) == a.until(lo).length()
205
+ assert s.length() == 5
206
+
168
207
  test "union, intersection, difference and isSubsetOf agree with a filter"
169
208
  for seed := range 1.to(10)
170
209
  a := setRandom(seed, 200, 300, Set.empty())
std/collections/Treap.plum DELETED
@@ -1,643 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Str
5
- import std/Option
6
- import std/Pair
7
- import std/math/Random
8
- import std/collections/List
9
- import std/Slice
10
- import std/collections/Map
11
-
12
- # `Treap`, written functionally (see std/collections/AvlTree
13
- # for the rules these persistent collections follow): a persistent ordered map kept as a treap, a binary
14
- # search tree on keys that is also a max-heap on random priorities, so its shape is
15
- # that of a tree built by inserting the keys in random order and its expected height
16
- # is O(log n). Every update returns a new treap that rebuilds the O(log n) nodes it
17
- # touches and shares the rest; the old one stays as it was.
18
- # Keys are ordered by `before(a, b)` ("a belongs before b", strictly), stored in the
19
- # wrapper: `Treap.by(|a, b| a > b)`, `Treap.ints()`, `Treap.seeded(before, seed)`.
20
- # Priorities are deterministic, as in the twin: each new key draws one from a seeded
21
- # `std/math/Random` (xorshift64*, an immutable value) held in the wrapper, and `insert`
22
- # returns a treap carrying the next generator, so the same inserts from the same seed
23
- # give the same tree. Replacing an existing key draws nothing.
24
- # Built on `split(k)` and `join(other)`; `union`, `intersection` and `difference` are
25
- # expected O(m log(n / m + 1)) for sizes m <= n, and `range(lo, hi)` is O(log n).
26
- # `get`/`has`/`insert`/`remove`/`min`/`max` are expected O(log n); `length` is O(1)
27
- # (sizes are cached in the nodes).
28
- # Same API as the twin, except `entries`/`keys`/`values` return a `List`. The
29
- # twin's `while` walks (`get`, `min`, `max`) are tail calls here, its `collect` into a
30
- # `Slice` conses onto an accumulator, the `v = fv` in `union` is an `if` value, and `toStr`
31
- # joins a `List` with `List.join`.
32
- # Stack: `get`/`min`/`max` run in constant stack; everything else recurses along paths
33
- # of the tree, O(log n) deep expected (`entries` too).
34
- struct Treap[K, V](root: TreapNode[K, V], before: fn(K, K) -> Bool, rng: Random) =
35
-
36
- # The empty treap ordered by `before`, with a fixed priority seed.
37
- fun by(before: fn(K, K) -> Bool) -> Treap[K, V] =
38
- Treap.seeded(before, 0x2545F4914F6CDD1D)
39
-
40
- # The empty treap of `Int` keys in ascending order, with a fixed priority seed.
41
- fun ints() -> Treap[Int, V] =
42
- leaf: TreapNode[Int, V] := TreapLeaf
43
- Treap(root: leaf, before: |a, b| a < b, rng: Random.seeded(0x2545F4914F6CDD1D))
44
-
45
- # The empty treap ordered by `before`, drawing priorities from `seed`.
46
- fun seeded(before: fn(K, K) -> Bool, seed: Int) -> Treap[K, V] =
47
- leaf: TreapNode[K, V] := TreapLeaf
48
- Treap(root: leaf, before: before, rng: Random.seeded(seed))
49
-
50
- # The same order and generator over another root.
51
- fun withRoot(self, root: TreapNode[K, V]) -> Treap[K, V] =
52
- Treap(root: root, before: self.before, rng: self.rng)
53
-
54
- fun length(self) -> Int =
55
- self.root.size()
56
-
57
- fun isEmpty(self) -> Bool =
58
- self.root.size() == 0
59
-
60
- # The number of nodes on the longest root-to-leaf path (0 when empty).
61
- fun height(self) -> Int =
62
- self.root.height()
63
-
64
- # The value stored for `k`, or None.
65
- fun get(self, k: K) -> Option[V] =
66
- self.root.get(k, self.before)
67
-
68
- fun has(self, k: K) -> Bool =
69
- self.get(k).isSome()
70
-
71
- # A treap with `k` mapped to `v`, replacing the value of an existing `k` (which
72
- # keeps its priority, so the shape stays the same and no priority is drawn). A new
73
- # key draws a priority, and the result carries the advanced generator.
74
- fun insert(self, k: K, v: V) -> Treap[K, V] =
75
- if self.has(k)
76
- self.withRoot(self.root.replace(k, v, self.before))
77
- else
78
- d := self.rng.nextInt()
79
- Treap(root: self.root.insert(k, v, d.value, self.before), before: self.before, rng: d.rng)
80
-
81
- # A treap without `k`; the same treap when `k` is absent.
82
- fun remove(self, k: K) -> Treap[K, V] =
83
- if !self.has(k) then self else self.withRoot(self.root.remove(k, self.before))
84
-
85
- # The entry with the smallest key, or None if empty.
86
- fun min(self) -> Option[Pair[K, V]] =
87
- self.root.min()
88
-
89
- # The entry with the largest key, or None if empty.
90
- fun max(self) -> Option[Pair[K, V]] =
91
- self.root.max()
92
-
93
- # Two treaps: the keys before `k`, and the keys equal to or after `k`.
94
- fun split(self, k: K) -> Pair[Treap[K, V], Treap[K, V]] =
95
- parts := self.root.split(k, self.before)
96
- Pair(first: self.withRoot(parts.less), second: self.withRoot(TreapNode.join(parts.found, parts.greater)))
97
-
98
- # True when every key of `self` comes before every key of `other` (or one is empty).
99
- fun allBefore(self, other: Treap[K, V]) -> Bool = match self.max()
100
- None => true
101
- Some(a) => match other.min()
102
- None => true
103
- Some(b) => self.before(a.first, b.first)
104
-
105
- # Every entry of `self` followed by every entry of `other`. Every key of `self`
106
- # must come before every key of `other` (crashes otherwise); for overlapping
107
- # maps use `union`.
108
- fun join(self, other: Treap[K, V]) -> Treap[K, V] =
109
- if !self.allBefore(other)
110
- crash "Treap.join: the keys of the left treap must all come before the keys of the right one"
111
- self.withRoot(TreapNode.join(self.root, other.root))
112
-
113
- # The entries of both treaps; for a key in both, `self`'s value wins.
114
- fun union(self, other: Treap[K, V]) -> Treap[K, V] =
115
- self.withRoot(TreapNode.union(self.root, other.root, self.before, true))
116
-
117
- # The entries of `self` whose key is also in `other`.
118
- fun intersection(self, other: Treap[K, V]) -> Treap[K, V] =
119
- self.withRoot(self.root.intersection(other.root, self.before))
120
-
121
- # The entries of `self` whose key is not in `other`.
122
- fun difference(self, other: Treap[K, V]) -> Treap[K, V] =
123
- self.withRoot(self.root.difference(other.root, self.before))
124
-
125
- # The entries with `lo <= key < hi` (half-open, so adjacent ranges don't
126
- # overlap), as a treap sharing nodes with this one.
127
- fun range(self, lo: K, hi: K) -> Treap[K, V] =
128
- self.split(lo).second.split(hi).first
129
-
130
- # Every key with its value, in ascending key order (`e.first`, `e.second`).
131
- fun entries(self) -> List[Pair[K, V]] =
132
- none: List[Pair[K, V]] := Nil
133
- self.root.collect(none)
134
-
135
- # Every key, in ascending order.
136
- fun keys(self) -> List[K] =
137
- self.entries().map(|e| e.first)
138
-
139
- # Every value, in ascending key order.
140
- fun values(self) -> List[V] =
141
- self.entries().map(|e| e.second)
142
-
143
- # The entries in key order: `[1: one, 2: two]`.
144
- fun toStr(self) -> Str =
145
- "[" + self.entries().join(", ") + "]"
146
-
147
- # The three parts of a treap split at a key: the keys before it, the node holding
148
- # the key itself (a single node, or `TreapLeaf` when absent), and the keys after it.
149
- struct TreapParts[K, V](less: TreapNode[K, V], found: TreapNode[K, V], greater: TreapNode[K, V])
150
-
151
- # The nodes of a `Treap`: `TreapLeaf`, or a key and value with its priority, the
152
- # size of the subtree it roots, the smaller keys on the left and the larger on the
153
- # right. A node's priority is at least that of each child.
154
- enum TreapNode[K, V] =
155
- | TreapLeaf
156
- | TreapBranch(key: K, value: V, prio: Int, size: Int, left: TreapNode[K, V], right: TreapNode[K, V])
157
-
158
- fun isEmpty(self) -> Bool = match self
159
- TreapLeaf => true
160
- TreapBranch(_, _, _, _, _, _) => false
161
-
162
- fun size(self) -> Int = match self
163
- TreapLeaf => 0
164
- TreapBranch(_, _, _, s, _, _) => s
165
-
166
- fun height(self) -> Int = match self
167
- TreapLeaf => 0
168
- TreapBranch(_, _, _, _, l, r) => l.height().max(r.height()) + 1
169
-
170
- # Tail recursive: one comparison per level.
171
- fun get(self, k: K, before: fn(K, K) -> Bool) -> Option[V] = match self
172
- TreapLeaf => None
173
- TreapBranch(nk, nv, _, _, l, r) =>
174
- if before(k, nk)
175
- l.get(k, before)
176
- else if before(nk, k)
177
- r.get(k, before)
178
- else
179
- Some(nv)
180
-
181
- fun min(self) -> Option[Pair[K, V]] = match self
182
- TreapLeaf => None
183
- TreapBranch(nk, nv, _, _, TreapLeaf, _) => Some(Pair(first: nk, second: nv))
184
- TreapBranch(_, _, _, _, l, _) => l.min()
185
-
186
- fun max(self) -> Option[Pair[K, V]] = match self
187
- TreapLeaf => None
188
- TreapBranch(nk, nv, _, _, _, TreapLeaf) => Some(Pair(first: nk, second: nv))
189
- TreapBranch(_, _, _, _, _, r) => r.max()
190
-
191
- # The value of this node, or `v` when it is a leaf.
192
- fun valueOr(self, v: V) -> V = match self
193
- TreapLeaf => v
194
- TreapBranch(_, nv, _, _, _, _) => nv
195
-
196
- # A node over `l` and `r` with its size computed.
197
- fun make(k: K, v: V, p: Int, l: TreapNode[K, V], r: TreapNode[K, V]) -> TreapNode[K, V] =
198
- TreapBranch(key: k, value: v, prio: p, size: l.size() + r.size() + 1, left: l, right: r)
199
-
200
- # Splits at `k` into the keys before it, its own node (children dropped), and
201
- # the keys after it.
202
- fun split(self, k: K, before: fn(K, K) -> Bool) -> TreapParts[K, V] = match self
203
- TreapLeaf => TreapParts(less: self, found: self, greater: self)
204
- TreapBranch(nk, nv, p, _, l, r) =>
205
- if before(k, nk)
206
- parts := l.split(k, before)
207
- TreapParts(less: parts.less, found: parts.found, greater: TreapNode.make(nk, nv, p, parts.greater, r))
208
- else if before(nk, k)
209
- parts := r.split(k, before)
210
- TreapParts(less: TreapNode.make(nk, nv, p, l, parts.less), found: parts.found, greater: parts.greater)
211
- else
212
- leaf: TreapNode[K, V] := TreapLeaf
213
- TreapParts(less: l, found: TreapNode.make(nk, nv, p, leaf, leaf), greater: r)
214
-
215
- # `a` followed by `b`, where every key of `a` comes before every key of `b`: the
216
- # root with the higher priority stays on top.
217
- fun join(a: TreapNode[K, V], b: TreapNode[K, V]) -> TreapNode[K, V] = match a
218
- TreapLeaf => b
219
- TreapBranch(ak, av, ap, _, al, ar) => match b
220
- TreapLeaf => a
221
- TreapBranch(bk, bv, bp, _, bl, br) =>
222
- if ap >= bp
223
- TreapNode.make(ak, av, ap, al, TreapNode.join(ar, b))
224
- else
225
- TreapNode.make(bk, bv, bp, TreapNode.join(a, bl), br)
226
-
227
- # Inserts a key known to be absent, with priority `p`: it goes down until its
228
- # priority beats the node's, then splits that subtree around itself.
229
- fun insert(self, k: K, v: V, p: Int, before: fn(K, K) -> Bool) -> TreapNode[K, V] = match self
230
- TreapLeaf => TreapNode.make(k, v, p, self, self)
231
- TreapBranch(nk, nv, np, _, l, r) =>
232
- if p > np
233
- parts := self.split(k, before)
234
- TreapNode.make(k, v, p, parts.less, parts.greater)
235
- else if before(k, nk)
236
- TreapNode.make(nk, nv, np, l.insert(k, v, p, before), r)
237
- else
238
- TreapNode.make(nk, nv, np, l, r.insert(k, v, p, before))
239
-
240
- # Replaces the value of a key known to be present.
241
- fun replace(self, k: K, v: V, before: fn(K, K) -> Bool) -> TreapNode[K, V] = match self
242
- TreapLeaf => self
243
- TreapBranch(nk, nv, np, s, l, r) =>
244
- if before(k, nk)
245
- TreapBranch(key: nk, value: nv, prio: np, size: s, left: l.replace(k, v, before), right: r)
246
- else if before(nk, k)
247
- TreapBranch(key: nk, value: nv, prio: np, size: s, left: l, right: r.replace(k, v, before))
248
- else
249
- TreapBranch(key: nk, value: v, prio: np, size: s, left: l, right: r)
250
-
251
- # Removes a key: its node is replaced by the join of its children.
252
- fun remove(self, k: K, before: fn(K, K) -> Bool) -> TreapNode[K, V] = match self
253
- TreapLeaf => self
254
- TreapBranch(nk, nv, np, _, l, r) =>
255
- if before(k, nk)
256
- TreapNode.make(nk, nv, np, l.remove(k, before), r)
257
- else if before(nk, k)
258
- TreapNode.make(nk, nv, np, l, r.remove(k, before))
259
- else
260
- TreapNode.join(l, r)
261
-
262
- # The keys of both; the higher-priority root stays on top and splits the other
263
- # tree. For a key in both, the value from the `self` side wins (`aIsSelf` says
264
- # which side `a` is).
265
- fun union(a: TreapNode[K, V], b: TreapNode[K, V], before: fn(K, K) -> Bool, aIsSelf: Bool) -> TreapNode[K, V] = match a
266
- TreapLeaf => b
267
- TreapBranch(ak, av, ap, _, al, ar) => match b
268
- TreapLeaf => a
269
- TreapBranch(_, _, bp, _, _, _) =>
270
- if ap < bp
271
- TreapNode.union(b, a, before, !aIsSelf)
272
- else
273
- parts := b.split(ak, before)
274
- l := TreapNode.union(al, parts.less, before, aIsSelf)
275
- r := TreapNode.union(ar, parts.greater, before, aIsSelf)
276
- v := if aIsSelf then av else parts.found.valueOr(av)
277
- TreapNode.make(ak, v, ap, l, r)
278
-
279
- # The nodes of `self` whose key is in `other`.
280
- fun intersection(self, other: TreapNode[K, V], before: fn(K, K) -> Bool) -> TreapNode[K, V] = match self
281
- TreapLeaf => self
282
- TreapBranch(k, v, p, _, l, r) =>
283
- if other.isEmpty()
284
- other
285
- else
286
- parts := other.split(k, before)
287
- il := l.intersection(parts.less, before)
288
- ir := r.intersection(parts.greater, before)
289
- if parts.found.isEmpty() then TreapNode.join(il, ir) else TreapNode.make(k, v, p, il, ir)
290
-
291
- # The nodes of `self` whose key is not in `other`.
292
- fun difference(self, other: TreapNode[K, V], before: fn(K, K) -> Bool) -> TreapNode[K, V] = match self
293
- TreapLeaf => self
294
- TreapBranch(k, v, p, _, l, r) =>
295
- if other.isEmpty()
296
- self
297
- else
298
- parts := other.split(k, before)
299
- dl := l.difference(parts.less, before)
300
- dr := r.difference(parts.greater, before)
301
- if parts.found.isEmpty() then TreapNode.make(k, v, p, dl, dr) else TreapNode.join(dl, dr)
302
-
303
- # The entries in key order, in front of `acc`: right subtree first, so each entry is
304
- # consed onto the ones after it.
305
- fun collect(self, acc: List[Pair[K, V]]) -> List[Pair[K, V]] = match self
306
- TreapLeaf => acc
307
- TreapBranch(nk, nv, _, _, l, r) => l.collect(Cons(head: Pair(first: nk, second: nv), tail: r.collect(acc)))
308
-
309
- # ---------------------------------------------------------------------------
310
- # Test helpers. Tests may use loops, `mut` fields and std's `Map` as the
311
- # reference model; the structure above may not.
312
- # ---------------------------------------------------------------------------
313
-
314
- # The treap and generator state a randomized test threads from step to step.
315
- struct TreapSim(mut t: Treap[Int, Int], mut x: Int)
316
-
317
- fun treapInts() -> Treap[Int, Int] =
318
- t: Treap[Int, Int] := Treap.ints()
319
- t
320
-
321
- # Inserts each key `k` with value `k * 10`, in order.
322
- fun treapOf(keys: List[Int]) -> Treap[Int, Int] =
323
- keys.fold(treapInts(), |t, k| t.insert(k, k * 10))
324
-
325
- # Inserts `lo` to `hi - 1` (value = key), as a tail call.
326
- fun treapRange(t: Treap[Int, Int], lo: Int, hi: Int) -> Treap[Int, Int] =
327
- if lo >= hi then t else treapRange(t.insert(lo, lo), lo + 1, hi)
328
-
329
- # Removes `lo`, `lo + step`, ... below `hi`, as a tail call.
330
- fun treapRemoveEvery(t: Treap[Int, Int], lo: Int, hi: Int, step: Int) -> Treap[Int, Int] =
331
- if lo >= hi then t else treapRemoveEvery(t.remove(lo), lo + step, hi, step)
332
-
333
- # `lo` to `hi - 1` as a cons list, built from the top down (tail recursive).
334
- fun treapUpTo(lo: Int, hi: Int, acc: List[Int]) -> List[Int] =
335
- if hi <= lo then acc else treapUpTo(lo, hi - 1, Cons(head: hi - 1, tail: acc))
336
-
337
- # The tree's shape, keys only: `((1)2(3))`.
338
- fun treapShape(t: TreapNode[Int, Int]) -> Str = match t
339
- TreapLeaf => ""
340
- TreapBranch(k, _, _, _, l, r) => "({treapShape(l)}{k}{treapShape(r)})"
341
-
342
- # The root's key and priority, or None when empty.
343
- fun treapTop(t: TreapNode[Int, Int]) -> Option[Pair[Int, Int]] = match t
344
- TreapLeaf => None
345
- TreapBranch(k, _, p, _, _, _) => Some(Pair(first: k, second: p))
346
-
347
- # The size of `t` if its keys lie strictly between `lo` and `hi`, its priorities
348
- # are at most `maxPrio` and each node's priority bounds its children's, keys
349
- # are in BST order and every cached size is right; else -1.
350
- fun treapCheckedSize(t: TreapNode[Int, Int], lo: Int, hi: Int, maxPrio: Int) -> Int = match t
351
- TreapLeaf => 0
352
- TreapBranch(k, _, p, s, l, r) =>
353
- if k <= lo || k >= hi || p > maxPrio
354
- -1
355
- else
356
- sl := treapCheckedSize(l, lo, k, p)
357
- sr := treapCheckedSize(r, k, hi, p)
358
- if sl < 0 || sr < 0 || s != sl + sr + 1 then -1 else s
359
-
360
- # The treap invariants: BST order on keys, heap order on priorities, sizes cached.
361
- fun treapValid(t: Treap[Int, Int]) -> Bool =
362
- treapCheckedSize(t.root, -4611686018427387904, 4611686018427387904, 0x7FFFFFFFFFFFFFFF) == t.length()
363
-
364
- # The keys of a brute-force model, sorted, in the same text form as `keys().toStr()`.
365
- fun treapModelKeys(m: Map[Int, Int]) -> Str =
366
- m.keys().sort(|a, b| a < b).toStr()
367
-
368
- # A brute-force model: a persistent `Map` in a `mut` field, so a loop can update it.
369
- struct TreapModel(mut m: Map[Int, Int])
370
-
371
- # A pseudo-random treap of keys below `bound` (from an LCG seeded by `seed`),
372
- # mirrored into `model`, each value `k * 10 + tag`.
373
- fun treapRandom(seed: Int, count: Int, bound: Int, tag: Int, model: TreapModel) -> Treap[Int, Int] =
374
- s := TreapSim(t: treapInts(), x: seed)
375
- for i := range count
376
- s.x = {s.x * 1103515245 + 12345} % 2147483648
377
- k := {s.x / 7} % bound
378
- s.t = s.t.insert(k, k * 10 + tag)
379
- model.m = model.m.with(k, k * 10 + tag)
380
- s.t
381
-
382
- test "an empty treap"
383
- t := treapInts()
384
- assert t.length() == 0
385
- assert t.isEmpty()
386
- assert t.height() == 0
387
- assert t.get(1).isNone()
388
- assert t.has(1) == false
389
- assert t.min().isNone()
390
- assert t.max().isNone()
391
- assert t.keys().isEmpty()
392
- assert t.toStr() == "[]"
393
- assert t.remove(1).length() == 0
394
- assert t.split(3).first.isEmpty() && t.split(3).second.isEmpty()
395
- assert t.union(t).isEmpty() && t.intersection(t).isEmpty() && t.difference(t).isEmpty()
396
- assert t.range(0, 10).isEmpty()
397
- assert treapValid(t)
398
-
399
- test "one element"
400
- t := treapInts().insert(7, 70)
401
- assert t.length() == 1 && t.height() == 1
402
- assert t.get(7)! == 70
403
- assert t.min()!.first == 7 && t.max()!.first == 7
404
- assert t.toStr() == "[7: 70]"
405
- assert t.remove(7).isEmpty()
406
- assert t.remove(8).length() == 1
407
- assert treapValid(t)
408
-
409
- test "insert, get and has"
410
- t := treapOf([5, 3, 8, 1])
411
- assert t.length() == 4
412
- assert t.get(3)! == 30
413
- assert t.get(8)! == 80
414
- assert t.get(4).isNone()
415
- assert t.has(1)
416
- assert t.has(2) == false
417
- assert treapValid(t)
418
-
419
- test "insert replaces the value of an existing key and keeps the shape"
420
- t := treapOf([1, 2, 3, 4, 5])
421
- u := t.insert(2, 99)
422
- assert u.length() == 5
423
- assert u.get(2)! == 99
424
- assert u.toStr() == "[1: 10, 2: 99, 3: 30, 4: 40, 5: 50]"
425
- assert u.height() == t.height()
426
- assert treapShape(u.root) == treapShape(t.root)
427
- assert treapValid(u)
428
-
429
- test "min, max, entries, keys and values are in key order"
430
- t := treapOf([7, 2, 9, 4, 1])
431
- assert t.min()!.first == 1
432
- assert t.min()!.second == 10
433
- assert t.max()!.first == 9
434
- assert t.max()!.second == 90
435
- assert t.keys().toStr() == "[1,2,4,7,9]"
436
- assert t.values().toStr() == "[10,20,40,70,90]"
437
- es := t.entries()
438
- assert es.length() == 5
439
- assert es.at(2).first == 4 && es.at(2).second == 40
440
- assert t.toStr() == "[1: 10, 2: 20, 4: 40, 7: 70, 9: 90]"
441
-
442
- test "remove a key, every key, and a missing key"
443
- t := treapOf([4, 2, 6, 1, 3, 5, 7])
444
- a := t.remove(4)
445
- assert a.keys().toStr() == "[1,2,3,5,6,7]"
446
- assert a.has(4) == false
447
- assert a.get(5)! == 50
448
- assert treapValid(a)
449
- b := a.remove(42)
450
- assert b.length() == 6
451
- assert b.toStr() == a.toStr()
452
- c := a.remove(1).remove(2).remove(3).remove(5).remove(6).remove(7)
453
- assert c.isEmpty()
454
- assert c.height() == 0
455
-
456
- test "the same inserts from the same seed give the same tree; priorities are drawn per new key"
457
- a := treapOf([3, 1, 4, 1, 5, 9, 2, 6])
458
- b := treapOf([3, 1, 4, 1, 5, 9, 2, 6])
459
- assert a.height() == b.height()
460
- assert treapShape(a.root) == treapShape(b.root)
461
- assert a.root.split(4, |x, y| x < y).less.size() == b.root.split(4, |x, y| x < y).less.size()
462
- ta := treapTop(a.root)
463
- tb := treapTop(b.root)
464
- assert ta.isSome() && tb.isSome()
465
- assert ta!.first == tb!.first && ta!.second == tb!.second
466
- c: Treap[Int, Int] := Treap.seeded(|x, y| x < y, 7)
467
- d: Treap[Int, Int] := Treap.seeded(|x, y| x < y, 7)
468
- assert c.insert(1, 1).rng.seed == d.insert(1, 1).rng.seed
469
- assert c.insert(1, 1).rng.seed != c.rng.seed
470
- # The generator is threaded through the values: `c` itself never advances.
471
- assert c.insert(2, 2).rng.seed == c.insert(1, 1).rng.seed
472
- # Replacing an existing key draws nothing.
473
- e := c.insert(1, 1)
474
- assert e.insert(1, 2).rng.seed == e.rng.seed
475
-
476
- test "split puts keys before k on the left and k and after on the right"
477
- t := treapOf([1, 3, 5, 7, 9])
478
- s := t.split(5)
479
- assert s.first.keys().toStr() == "[1,3]"
480
- assert s.second.keys().toStr() == "[5,7,9]"
481
- assert treapValid(s.first) && treapValid(s.second)
482
- m := t.split(6)
483
- assert m.first.keys().toStr() == "[1,3,5]"
484
- assert m.second.keys().toStr() == "[7,9]"
485
- assert t.split(0).first.isEmpty()
486
- assert t.split(0).second.length() == 5
487
- assert t.split(10).first.length() == 5
488
- assert t.split(10).second.isEmpty()
489
- assert t.length() == 5
490
-
491
- test "join puts two ordered treaps back together"
492
- t := treapOf([1, 3, 5, 7, 9])
493
- s := t.split(5)
494
- j := s.first.join(s.second)
495
- assert j.toStr() == t.toStr()
496
- assert treapValid(j)
497
- assert treapInts().join(t).toStr() == t.toStr()
498
- assert t.join(treapInts()).toStr() == t.toStr()
499
- assert treapOf([1, 2]).join(treapOf([10, 20])).keys().toStr() == "[1,2,10,20]"
500
- assert treapOf([1, 5]).allBefore(treapOf([3])) == false
501
-
502
- test "union, intersection and difference on small maps"
503
- a := treapOf([1, 2, 3, 4]).insert(2, 0)
504
- b := treapOf([3, 4, 5, 6]).insert(3, 7)
505
- u := a.union(b)
506
- assert u.toStr() == "[1: 10, 2: 0, 3: 30, 4: 40, 5: 50, 6: 60]"
507
- assert b.union(a).get(3)! == 7
508
- assert b.union(a).get(2)! == 0
509
- i := a.intersection(b)
510
- assert i.toStr() == "[3: 30, 4: 40]"
511
- assert b.intersection(a).toStr() == "[3: 7, 4: 40]"
512
- d := a.difference(b)
513
- assert d.toStr() == "[1: 10, 2: 0]"
514
- assert b.difference(a).keys().toStr() == "[5,6]"
515
- assert treapValid(u) && treapValid(i) && treapValid(d)
516
- assert a.toStr() == "[1: 10, 2: 0, 3: 30, 4: 40]"
517
- assert b.toStr() == "[3: 7, 4: 40, 5: 50, 6: 60]"
518
-
519
- test "range keeps lo <= key < hi"
520
- t := treapOf([1, 2, 3, 4, 5, 6, 7, 8])
521
- assert t.range(3, 6).keys().toStr() == "[3,4,5]"
522
- assert t.range(0, 100).length() == 8
523
- assert t.range(5, 5).isEmpty()
524
- assert t.range(6, 3).isEmpty()
525
- assert t.range(9, 20).isEmpty()
526
- assert treapValid(t.range(2, 7))
527
- assert t.length() == 8
528
-
529
- test "old versions are unchanged after insert, remove, split and set operations"
530
- t := treapOf([1, 2, 3, 4, 5])
531
- shape := treapShape(t.root)
532
- u := t.insert(6, 60).insert(3, 0)
533
- v := t.remove(2).remove(4)
534
- w := t.split(3)
535
- x := t.union(treapOf([9])).difference(treapOf([1]))
536
- y := t.range(2, 4).join(treapOf([7]))
537
- assert t.toStr() == "[1: 10, 2: 20, 3: 30, 4: 40, 5: 50]"
538
- assert t.length() == 5
539
- assert treapShape(t.root) == shape
540
- assert u.toStr() == "[1: 10, 2: 20, 3: 0, 4: 40, 5: 50, 6: 60]"
541
- assert v.keys().toStr() == "[1,3,5]"
542
- assert w.first.keys().toStr() == "[1,2]"
543
- assert x.keys().toStr() == "[2,3,4,5,9]"
544
- assert y.keys().toStr() == "[2,3,7]"
545
- assert treapValid(t) && treapValid(u) && treapValid(v) && treapValid(y)
546
-
547
- test "invariants hold through pseudo-random inserts and removes"
548
- s := TreapSim(t: treapInts(), x: 12345)
549
- model := TreapModel(m: Map.empty())
550
- for i := range 3000
551
- s.x = {s.x * 1103515245 + 12345} % 2147483648
552
- k := s.x % 500
553
- if {s.x / 1000} % 3 == 0
554
- s.t = s.t.remove(k)
555
- model.m = model.m.remove(k)
556
- else
557
- s.t = s.t.insert(k, i)
558
- model.m = model.m.with(k, i)
559
- if i % 50 == 0
560
- assert treapValid(s.t)
561
- present := model.m
562
- t := s.t
563
- assert treapValid(t)
564
- assert t.length() == present.length()
565
- for k := range present.keys()
566
- assert t.get(k)! == present.get(k)!
567
- assert t.keys().toStr() == treapModelKeys(present)
568
-
569
- test "set operations match a brute-force model on random maps"
570
- for seed := range 1.until(6)
571
- maModel := TreapModel(m: Map.empty())
572
- mbModel := TreapModel(m: Map.empty())
573
- a := treapRandom(seed, 300, 400, 1, maModel)
574
- b := treapRandom(seed * 7919, 200, 400, 2, mbModel)
575
- ma := maModel.m
576
- mb := mbModel.m
577
- u := a.union(b)
578
- i := a.intersection(b)
579
- d := a.difference(b)
580
- assert treapValid(u) && treapValid(i) && treapValid(d)
581
- muModel := TreapModel(m: Map.empty())
582
- miModel := TreapModel(m: Map.empty())
583
- mdModel := TreapModel(m: Map.empty())
584
- for k := range mb.keys()
585
- muModel.m = muModel.m.with(k, mb.get(k)!)
586
- for k := range ma.keys()
587
- muModel.m = muModel.m.with(k, ma.get(k)!)
588
- if mb.has(k)
589
- miModel.m = miModel.m.with(k, ma.get(k)!)
590
- else
591
- mdModel.m = mdModel.m.with(k, ma.get(k)!)
592
- mu := muModel.m
593
- mi := miModel.m
594
- md := mdModel.m
595
- assert u.length() == mu.length() && i.length() == mi.length() && d.length() == md.length()
596
- for k := range mu.keys()
597
- assert u.get(k)! == mu.get(k)!
598
- for k := range mi.keys()
599
- assert i.get(k)! == mi.get(k)!
600
- for k := range md.keys()
601
- assert d.get(k)! == md.get(k)!
602
- r := a.range(100, 250)
603
- ks := ma.keys()
604
- n := 0.until(ks.length()).fold(0, |n, j|
605
- k := ks.at(j)
606
- if k >= 100 && k < 250
607
- assert r.get(k)! == ma.get(k)!
608
- n + 1
609
- else
610
- n
611
- )
612
- assert r.length() == n && treapValid(r)
613
-
614
- test "10,000 ascending keys stay shallow, sorted and valid"
615
- n := 10000
616
- t := treapRange(treapInts(), 0, n)
617
- assert t.length() == n
618
- assert t.height() < 60
619
- assert t.keys().equals(treapUpTo(0, n, Nil))
620
- assert treapValid(t)
621
- assert t.min()!.first == 0
622
- assert t.max()!.first == n - 1
623
- halves := t.split(n / 2)
624
- assert halves.first.length() == n / 2
625
- assert halves.second.min()!.first == n / 2
626
- assert halves.second.join(halves.first.range(0, 0)).length() == n / 2
627
- assert t.difference(t).isEmpty()
628
- assert t.range(0, n).union(treapInts()).length() == n
629
- odd := treapRemoveEvery(t, 0, n, 2)
630
- assert odd.length() == n / 2
631
- assert t.intersection(odd).length() == n / 2
632
- assert t.difference(odd).union(odd).length() == n
633
- assert treapValid(odd)
634
- assert t.length() == n
635
-
636
- test "a custom order: largest key first"
637
- t: Treap[Int, Str] := Treap.by(|a, b| a > b)
638
- u := t.insert(1, "one").insert(3, "three").insert(2, "two")
639
- assert u.keys().toStr() == "[3,2,1]"
640
- assert u.min()!.first == 3
641
- assert u.split(2).first.keys().toStr() == "[3]"
642
- assert u.range(3, 1).keys().toStr() == "[3,2]"
643
- assert u.toStr() == "[3: three, 2: two, 1: one]"
std/collections/Trie.plum CHANGED
@@ -8,7 +8,7 @@ import std/collections/List
8
8
  import std/Slice
9
9
  import std/collections/Map
10
10
 
11
- # `Trie`, written functionally (see std/collections/AvlTree
11
+ # `Trie`, written functionally (see docs/std.md
12
12
  # for the rules these persistent collections follow): a persistent map from `Str` keys to values, a trie
13
13
  # with one node per byte of the key (a key is its UTF-8 bytes, so keys sort by byte,
14
14
  # which for UTF-8 is code point order). Each node holds an optional value and its
std/collections/UnionFind.plum CHANGED
@@ -5,33 +5,33 @@ import std/Float
5
5
  import std/Option
6
6
  import std/collections/List
7
7
  import std/Slice
8
- import std/collections/AvlTree
8
+ import std/collections/Map
9
9
 
10
- # A union-find written functionally (see std/collections/AvlTree for the
10
+ # A union-find written functionally (see docs/std.md for the
11
11
  # rules these persistent collections follow): a PERSISTENT disjoint-set forest over the ids 0 to n - 1.
12
12
  # `union` returns a new forest and the old one is unchanged, so after
13
13
  # `b := a.union(0, 1)` only `b` sees the union.
14
14
  #
15
15
  # An imperative union-find keeps parents and sizes in two mutable arrays and compresses
16
- # every path `find` walks. Here they are two `AvlTree[Int, Int]`s, `parent` (every id)
16
+ # every path `find` walks. Here they are two persistent `Map[Int, Int]`s, `parent` (every id)
17
17
  # and `sizes` (read only at roots), and there is no path compression: it would mean
18
18
  # mutating the forest on a read, or returning a new forest from every `find`. Union by
19
19
  # size alone keeps every tree at most log2(n) + 1 deep (a root's depth grows only when
20
20
  # its tree is merged into one at least as big, which at least doubles its size), so
21
- # `find` takes O(log n) steps of an O(log n) AVL lookup: `find`, `connected` and
21
+ # `find` takes O(log n) steps of an O(log n) map lookup: `find`, `connected` and
22
22
  # `sizeOf` are O(log^2 n), and `union` is two finds plus two O(log n) inserts,
23
23
  # O(log^2 n). `ofSize(n)` is O(n log n); `length`, `isEmpty` and `componentCount` are
24
24
  # O(1). `union` reports nothing back: whether it joined two components is
25
25
  # `!connected(a, b)` before the call (or a drop in `componentCount`).
26
26
  #
27
27
  # Stack: `find` walks parent links with a tail call, `ofSize` fills with a tail call,
28
- # and the AVL trees recurse O(log n) deep, so the stack stays O(log n). Ids out of
28
+ # and the maps recurse O(log n) deep, so the stack stays O(log n). Ids out of
29
29
  # range crash.
30
- struct UnionFind(parent: AvlTree[Int, Int], sizes: AvlTree[Int, Int], n: Int, count: Int) =
30
+ struct UnionFind(parent: Map[Int, Int], sizes: Map[Int, Int], n: Int, count: Int) =
31
31
 
32
32
  # n ids, each alone in its own component.
33
33
  fun ofSize(n: Int) -> UnionFind =
34
- empty: AvlTree[Int, Int] := AvlTree.ints()
34
+ empty: Map[Int, Int] := Map.empty()
35
35
  UnionFind.fill(UnionFind(parent: empty, sizes: empty, n: n, count: n), 0)
36
36
 
37
37
  # `uf` with ids `i` to `n - 1` added as their own roots of size 1.
@@ -39,7 +39,7 @@ struct UnionFind(parent: AvlTree[Int, Int], sizes: AvlTree[Int, Int], n: Int, co
39
39
  if i >= uf.n
40
40
  uf
41
41
  else
42
- UnionFind.fill(UnionFind(parent: uf.parent.insert(i, i), sizes: uf.sizes.insert(i, 1), n: uf.n, count: uf.count), i + 1)
42
+ UnionFind.fill(UnionFind(parent: uf.parent.with(i, i), sizes: uf.sizes.with(i, 1), n: uf.n, count: uf.count), i + 1)
43
43
 
44
44
  # The number of ids.
45
45
  fun length(self) -> Int = self.n
@@ -69,7 +69,7 @@ struct UnionFind(parent: AvlTree[Int, Int], sizes: AvlTree[Int, Int], n: Int, co
69
69
 
70
70
  # Root `small` hung under root `big`, whose tree now holds `total` ids.
71
71
  fun link(self, small: Int, big: Int, total: Int) -> UnionFind =
72
- UnionFind(parent: self.parent.insert(small, big), sizes: self.sizes.insert(big, total), n: self.n, count: self.count - 1)
72
+ UnionFind(parent: self.parent.with(small, big), sizes: self.sizes.with(big, total), n: self.n, count: self.count - 1)
73
73
 
74
74
  fun connected(self, a: Int, b: Int) -> Bool = self.find(a) == self.find(b)
75
75
 
@@ -272,7 +272,7 @@ test "the checker rejects a broken forest"
272
272
  assert ufValid(uf)
273
273
  wrongCount := UnionFind(parent: uf.parent, sizes: uf.sizes, n: 4, count: 4)
274
274
  assert ufValid(wrongCount) == false
275
- wrongSize := UnionFind(parent: uf.parent, sizes: uf.sizes.insert(uf.find(0), 5), n: 4, count: 3)
275
+ wrongSize := UnionFind(parent: uf.parent, sizes: uf.sizes.with(uf.find(0), 5), n: 4, count: 3)
276
276
  assert ufValid(wrongSize) == false
277
- outOfRange := UnionFind(parent: uf.parent.insert(2, 9), sizes: uf.sizes, n: 4, count: 3)
277
+ outOfRange := UnionFind(parent: uf.parent.with(2, 9), sizes: uf.sizes, n: 4, count: 3)
278
278
  assert ufValid(outOfRange) == false
std/collections/WeightBalancedTree.plum DELETED
@@ -1,699 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Str
5
- import std/Option
6
- import std/Pair
7
- import std/collections/List
8
- import std/Slice
9
- import std/collections/Map
10
-
11
- # A weight-balanced tree written functionally (see std/collections/AvlTree
12
- # for the rules these persistent collections follow): a persistent ordered map kept as a weight-balanced tree
13
- # (Adams 1993, as in Haskell's `Data.Map`). Every node stores the size of its subtree,
14
- # and neither subtree of a node holds more than 3 times as many entries as the other
15
- # (delta = 3; a rotation is double when the inner grandchild holds at least ratio = 2
16
- # times as many as the outer one), so the height stays O(log n).
17
- # Every update returns a new tree that rebuilds only the O(log n) nodes on its path and
18
- # shares every other subtree with the old one, which stays as it was. Keys are ordered by
19
- # `before(a, b)` ("a belongs before b", strictly), stored in the wrapper:
20
- # `WeightBalancedTree.by(|a, b| a > b)` keeps keys descending, `WeightBalancedTree.ints()`
21
- # ascending.
22
- # `get`/`has`/`insert`/`remove`/`min`/`max` are O(log n) and `length` is O(1). The stored
23
- # sizes make it an order-statistics tree: `rank(k)` (how many keys are before `k`) and
24
- # `at(i)` (the i-th smallest entry) are O(log n), and `split`, `union`, `intersection` and
25
- # `difference` split and re-join whole subtrees: O(m log(n / m + 1)) for trees of sizes
26
- # m <= n. The two trees of a set operation must use the same order.
27
- #
28
- # `entries`, `keys` and `values` return a `List`. Lookups (`get`, `min`, `max`, `rank`,
29
- # `at`) are tail calls, with `rank` and `at` threading their counter through an
30
- # argument; `collect` conses onto an accumulator; `toStr` joins with `List.join` instead of
31
- # a `Buffer`.
32
- # Stack depth: lookups are tail calls (constant stack); updates, `cut`, `link`, `merge`
33
- # and the set operations recurse along one path per level, so O(log n); `collect` is
34
- # O(log n) deep too (the right subtree's walk is the only non-tail call per level).
35
- struct WeightBalancedTree[K, V](root: WbBranch[K, V], before: fn(K, K) -> Bool) =
36
-
37
- # The empty tree ordered by `before`.
38
- fun by(before: fn(K, K) -> Bool) -> WeightBalancedTree[K, V] =
39
- leaf: WbBranch[K, V] := WbLeaf
40
- WeightBalancedTree(root: leaf, before: before)
41
-
42
- # The empty tree of `Int` keys in ascending order.
43
- fun ints() -> WeightBalancedTree[Int, V] =
44
- leaf: WbBranch[Int, V] := WbLeaf
45
- WeightBalancedTree(root: leaf, before: |a, b| a < b)
46
-
47
- # The same order over another root.
48
- fun over(self, root: WbBranch[K, V]) -> WeightBalancedTree[K, V] =
49
- WeightBalancedTree(root: root, before: self.before)
50
-
51
- fun length(self) -> Int = self.root.size()
52
-
53
- fun isEmpty(self) -> Bool = self.root.size() == 0
54
-
55
- # The number of nodes on the longest root-to-leaf path (0 when empty).
56
- fun height(self) -> Int = self.root.height()
57
-
58
- # The value stored for `k`, or None.
59
- fun get(self, k: K) -> Option[V] = self.root.get(k, self.before)
60
-
61
- fun has(self, k: K) -> Bool = self.get(k).isSome()
62
-
63
- # A tree with `k` mapped to `v`, replacing the value of an existing `k`.
64
- fun insert(self, k: K, v: V) -> WeightBalancedTree[K, V] =
65
- self.over(self.root.ins(k, v, self.before))
66
-
67
- # A tree without `k`; the same tree when `k` is absent.
68
- fun remove(self, k: K) -> WeightBalancedTree[K, V] =
69
- if !self.has(k)
70
- self
71
- else
72
- self.over(self.root.del(k, self.before))
73
-
74
- # The entry with the smallest key, or None if empty.
75
- fun min(self) -> Option[Pair[K, V]] = self.root.min()
76
-
77
- # The entry with the largest key, or None if empty.
78
- fun max(self) -> Option[Pair[K, V]] = self.root.max()
79
-
80
- # How many keys are before `k` (whether or not `k` is in the tree), so a
81
- # present `k` is the entry `at(rank(k))`.
82
- fun rank(self, k: K) -> Int = self.root.rankFrom(k, 0, self.before)
83
-
84
- # The entry with the `i`-th smallest key (from 0), or None when `i` is out of range.
85
- fun at(self, i: Int) -> Option[Pair[K, V]] =
86
- if i < 0 || i >= self.length()
87
- None
88
- else
89
- self.root.at(i)
90
-
91
- # The entries with keys before `k` (`first`) and after `k` (`second`); an
92
- # entry for `k` itself is in neither (read it with `get`).
93
- fun split(self, k: K) -> Pair[WeightBalancedTree[K, V], WeightBalancedTree[K, V]] =
94
- c := self.root.cut(k, self.before)
95
- Pair(first: self.over(c.below), second: self.over(c.above))
96
-
97
- # Every entry of either tree; for a key in both, the value from `self`.
98
- fun union(self, other: WeightBalancedTree[K, V]) -> WeightBalancedTree[K, V] =
99
- self.over(WbBranch.union(self.root, other.root, self.before))
100
-
101
- # The entries of `self` whose keys are also in `other` (with `self`'s values).
102
- fun intersection(self, other: WeightBalancedTree[K, V]) -> WeightBalancedTree[K, V] =
103
- self.over(WbBranch.intersection(self.root, other.root, self.before))
104
-
105
- # The entries of `self` whose keys are not in `other`.
106
- fun difference(self, other: WeightBalancedTree[K, V]) -> WeightBalancedTree[K, V] =
107
- self.over(WbBranch.difference(self.root, other.root, self.before))
108
-
109
- # Every key with its value, in ascending key order (`e.first`, `e.second`).
110
- fun entries(self) -> List[Pair[K, V]] =
111
- nil: List[Pair[K, V]] := Nil
112
- self.root.collect(nil)
113
-
114
- # Every key, in ascending order.
115
- fun keys(self) -> List[K] = self.entries().map(|e| e.first)
116
-
117
- # Every value, in ascending key order.
118
- fun values(self) -> List[V] = self.entries().map(|e| e.second)
119
-
120
- # The entries in key order: `[1: one, 2: two]`.
121
- fun toStr(self) -> Str = "[" + self.entries().join(", ") + "]"
122
-
123
- # A subtree cut at a key: the entries before it, its value if present, and the
124
- # entries after it.
125
- struct WbCut[K, V](below: WbBranch[K, V], found: Option[V], above: WbBranch[K, V])
126
-
127
- # The nodes of a `WeightBalancedTree`: `WbLeaf`, or a key and value with the
128
- # subtree of smaller keys on the left, larger on the right, and the number of
129
- # entries in the whole subtree cached.
130
- enum WbBranch[K, V] =
131
- | WbLeaf
132
- | WbNode(size: Int, key: K, value: V, left: WbBranch[K, V], right: WbBranch[K, V])
133
-
134
- # A side may hold at most `Delta` times the other's entries.
135
- Delta = 3
136
- # A rotation is double when the inner grandchild holds at least `Ratio` times
137
- # the outer grandchild's entries.
138
- Ratio = 2
139
-
140
- fun isEmpty(self) -> Bool = match self
141
- WbLeaf => true
142
- WbNode(_, _, _, _, _) => false
143
-
144
- fun size(self) -> Int = match self
145
- WbLeaf => 0
146
- WbNode(n, _, _, _, _) => n
147
-
148
- fun height(self) -> Int = match self
149
- WbLeaf => 0
150
- WbNode(_, _, _, l, r) => l.height().max(r.height()) + 1
151
-
152
- # Tail recursive: one comparison per level.
153
- fun get(self, k: K, before: fn(K, K) -> Bool) -> Option[V] = match self
154
- WbLeaf => None
155
- WbNode(_, nk, nv, l, r) =>
156
- if before(k, nk)
157
- l.get(k, before)
158
- else if before(nk, k)
159
- r.get(k, before)
160
- else
161
- Some(nv)
162
-
163
- # `n` plus the number of keys here before `k`. Tail recursive.
164
- fun rankFrom(self, k: K, n: Int, before: fn(K, K) -> Bool) -> Int = match self
165
- WbLeaf => n
166
- WbNode(_, nk, _, l, r) =>
167
- if before(k, nk)
168
- l.rankFrom(k, n, before)
169
- else if before(nk, k)
170
- r.rankFrom(k, n + l.size() + 1, before)
171
- else
172
- n + l.size()
173
-
174
- # The entry with the `i`-th smallest key here, or None. Tail recursive.
175
- fun at(self, i: Int) -> Option[Pair[K, V]] = match self
176
- WbLeaf => None
177
- WbNode(_, nk, nv, l, r) =>
178
- sl := l.size()
179
- if i < sl
180
- l.at(i)
181
- else if i == sl
182
- Some(Pair(first: nk, second: nv))
183
- else
184
- r.at(i - sl - 1)
185
-
186
- # A node over `l` and `r` with its size computed (no rebalancing).
187
- fun bin(k: K, v: V, l: WbBranch[K, V], r: WbBranch[K, V]) -> WbBranch[K, V] =
188
- WbNode(size: l.size() + r.size() + 1, key: k, value: v, left: l, right: r)
189
-
190
- # `bin`, rotating when one side has grown past `Delta` times the other (after
191
- # one insert or remove below, or one `link`/`merge` step).
192
- fun balance(k: K, v: V, l: WbBranch[K, V], r: WbBranch[K, V]) -> WbBranch[K, V] =
193
- sl := l.size()
194
- sr := r.size()
195
- if sl + sr <= 1
196
- WbBranch.bin(k, v, l, r)
197
- else if sr > WbBranch.Delta * sl
198
- WbBranch.rotateLeft(k, v, l, r)
199
- else if sl > WbBranch.Delta * sr
200
- WbBranch.rotateRight(k, v, l, r)
201
- else
202
- WbBranch.bin(k, v, l, r)
203
-
204
- # `k` over `l` and a too-heavy `r`: a single rotation lifts `r`, a double one
205
- # lifts `r`'s left child.
206
- fun rotateLeft(k: K, v: V, l: WbBranch[K, V], r: WbBranch[K, V]) -> WbBranch[K, V] = match r
207
- WbNode(_, rk, rv, rl, rr) =>
208
- if rl.size() < WbBranch.Ratio * rr.size()
209
- WbBranch.bin(rk, rv, WbBranch.bin(k, v, l, rl), rr)
210
- else
211
- match rl
212
- WbNode(_, mk, mv, ml, mr) => WbBranch.bin(mk, mv, WbBranch.bin(k, v, l, ml), WbBranch.bin(rk, rv, mr, rr))
213
- WbLeaf => WbBranch.bin(k, v, l, r)
214
- WbLeaf => WbBranch.bin(k, v, l, r)
215
-
216
- # `k` over a too-heavy `l` and `r`: the mirror of `rotateLeft`.
217
- fun rotateRight(k: K, v: V, l: WbBranch[K, V], r: WbBranch[K, V]) -> WbBranch[K, V] = match l
218
- WbNode(_, lk, lv, ll, lr) =>
219
- if lr.size() < WbBranch.Ratio * ll.size()
220
- WbBranch.bin(lk, lv, ll, WbBranch.bin(k, v, lr, r))
221
- else
222
- match lr
223
- WbNode(_, mk, mv, ml, mr) => WbBranch.bin(mk, mv, WbBranch.bin(lk, lv, ll, ml), WbBranch.bin(k, v, mr, r))
224
- WbLeaf => WbBranch.bin(k, v, l, r)
225
- WbLeaf => WbBranch.bin(k, v, l, r)
226
-
227
- fun ins(self, k: K, v: V, before: fn(K, K) -> Bool) -> WbBranch[K, V] = match self
228
- WbLeaf => WbBranch.bin(k, v, self, self)
229
- WbNode(n, nk, nv, l, r) =>
230
- if before(k, nk)
231
- WbBranch.balance(nk, nv, l.ins(k, v, before), r)
232
- else if before(nk, k)
233
- WbBranch.balance(nk, nv, l, r.ins(k, v, before))
234
- else
235
- WbNode(size: n, key: nk, value: v, left: l, right: r)
236
-
237
- fun del(self, k: K, before: fn(K, K) -> Bool) -> WbBranch[K, V] = match self
238
- WbLeaf => self
239
- WbNode(_, nk, nv, l, r) =>
240
- if before(k, nk)
241
- WbBranch.balance(nk, nv, l.del(k, before), r)
242
- else if before(nk, k)
243
- WbBranch.balance(nk, nv, l, r.del(k, before))
244
- else
245
- WbBranch.glue(l, r)
246
-
247
- # Tail recursive down the left spine.
248
- fun min(self) -> Option[Pair[K, V]] = match self
249
- WbLeaf => None
250
- WbNode(_, nk, nv, WbLeaf, _) => Some(Pair(first: nk, second: nv))
251
- WbNode(_, _, _, l, _) => l.min()
252
-
253
- # Tail recursive down the right spine.
254
- fun max(self) -> Option[Pair[K, V]] = match self
255
- WbLeaf => None
256
- WbNode(_, nk, nv, _, WbLeaf) => Some(Pair(first: nk, second: nv))
257
- WbNode(_, _, _, _, r) => r.max()
258
-
259
- fun removeMin(self) -> WbBranch[K, V] = match self
260
- WbLeaf => self
261
- WbNode(_, _, _, WbLeaf, r) => r
262
- WbNode(_, nk, nv, l, r) => WbBranch.balance(nk, nv, l.removeMin(), r)
263
-
264
- fun removeMax(self) -> WbBranch[K, V] = match self
265
- WbLeaf => self
266
- WbNode(_, _, _, l, WbLeaf) => l
267
- WbNode(_, nk, nv, l, r) => WbBranch.balance(nk, nv, l, r.removeMax())
268
-
269
- # `l` and `r` joined, where every key of `l` is before every key of `r` and the
270
- # two are balanced against each other: the larger side gives up its end entry
271
- # as the new root.
272
- fun glue(l: WbBranch[K, V], r: WbBranch[K, V]) -> WbBranch[K, V] =
273
- if l.isEmpty()
274
- r
275
- else if r.isEmpty()
276
- l
277
- else if l.size() > r.size()
278
- m := l.max()!
279
- WbBranch.balance(m.first, m.second, l.removeMax(), r)
280
- else
281
- m := r.min()!
282
- WbBranch.balance(m.first, m.second, l, r.removeMin())
283
-
284
- # `l` and `r` joined, where every key of `l` is before every key of `r`, of any sizes.
285
- fun merge(l: WbBranch[K, V], r: WbBranch[K, V]) -> WbBranch[K, V] = match l
286
- WbLeaf => r
287
- WbNode(sl, lk, lv, ll, lr) =>
288
- match r
289
- WbLeaf => l
290
- WbNode(sr, rk, rv, rl, rr) =>
291
- if WbBranch.Delta * sl < sr
292
- WbBranch.balance(rk, rv, WbBranch.merge(l, rl), rr)
293
- else if WbBranch.Delta * sr < sl
294
- WbBranch.balance(lk, lv, ll, WbBranch.merge(lr, r))
295
- else
296
- WbBranch.glue(l, r)
297
-
298
- # `l`, then `k`, then `r`, where every key of `l` is before `k` and `k` before
299
- # every key of `r`, of any sizes: descends the larger side until the two are
300
- # balanced, then joins them under `k`.
301
- fun link(k: K, v: V, l: WbBranch[K, V], r: WbBranch[K, V]) -> WbBranch[K, V] = match l
302
- WbLeaf => r.insertMin(k, v)
303
- WbNode(sl, lk, lv, ll, lr) =>
304
- match r
305
- WbLeaf => l.insertMax(k, v)
306
- WbNode(sr, rk, rv, rl, rr) =>
307
- if WbBranch.Delta * sl < sr
308
- WbBranch.balance(rk, rv, WbBranch.link(k, v, l, rl), rr)
309
- else if WbBranch.Delta * sr < sl
310
- WbBranch.balance(lk, lv, ll, WbBranch.link(k, v, lr, r))
311
- else
312
- WbBranch.bin(k, v, l, r)
313
-
314
- # Adds `k`, which is before every key here.
315
- fun insertMin(self, k: K, v: V) -> WbBranch[K, V] = match self
316
- WbLeaf => WbBranch.bin(k, v, self, self)
317
- WbNode(_, nk, nv, l, r) => WbBranch.balance(nk, nv, l.insertMin(k, v), r)
318
-
319
- # Adds `k`, which is after every key here.
320
- fun insertMax(self, k: K, v: V) -> WbBranch[K, V] = match self
321
- WbLeaf => WbBranch.bin(k, v, self, self)
322
- WbNode(_, nk, nv, l, r) => WbBranch.balance(nk, nv, l, r.insertMax(k, v))
323
-
324
- # This subtree cut at `k`.
325
- fun cut(self, k: K, before: fn(K, K) -> Bool) -> WbCut[K, V] = match self
326
- WbLeaf =>
327
- none: Option[V] := None
328
- WbCut(below: self, found: none, above: self)
329
- WbNode(_, nk, nv, l, r) =>
330
- if before(k, nk)
331
- c := l.cut(k, before)
332
- WbCut(below: c.below, found: c.found, above: WbBranch.link(nk, nv, c.above, r))
333
- else if before(nk, k)
334
- c := r.cut(k, before)
335
- WbCut(below: WbBranch.link(nk, nv, l, c.below), found: c.found, above: c.above)
336
- else
337
- WbCut(below: l, found: Some(nv), above: r)
338
-
339
- fun union(a: WbBranch[K, V], b: WbBranch[K, V], before: fn(K, K) -> Bool) -> WbBranch[K, V] = match b
340
- WbLeaf => a
341
- WbNode(_, _, _, _, _) =>
342
- match a
343
- WbLeaf => b
344
- WbNode(_, k, v, l, r) =>
345
- c := b.cut(k, before)
346
- WbBranch.link(k, v, WbBranch.union(l, c.below, before), WbBranch.union(r, c.above, before))
347
-
348
- fun intersection(a: WbBranch[K, V], b: WbBranch[K, V], before: fn(K, K) -> Bool) -> WbBranch[K, V] = match b
349
- WbLeaf => b
350
- WbNode(_, _, _, _, _) =>
351
- match a
352
- WbLeaf => a
353
- WbNode(_, k, v, l, r) =>
354
- c := b.cut(k, before)
355
- l2 := WbBranch.intersection(l, c.below, before)
356
- r2 := WbBranch.intersection(r, c.above, before)
357
- if c.found.isSome()
358
- WbBranch.link(k, v, l2, r2)
359
- else
360
- WbBranch.merge(l2, r2)
361
-
362
- fun difference(a: WbBranch[K, V], b: WbBranch[K, V], before: fn(K, K) -> Bool) -> WbBranch[K, V] = match a
363
- WbLeaf => a
364
- WbNode(_, _, _, _, _) =>
365
- match b
366
- WbLeaf => a
367
- WbNode(_, k, _, l, r) =>
368
- c := a.cut(k, before)
369
- WbBranch.merge(WbBranch.difference(c.below, l, before), WbBranch.difference(c.above, r, before))
370
-
371
- # The entries in key order, in front of `acc`: right subtree first, so each entry is
372
- # consed onto the ones after it.
373
- fun collect(self, acc: List[Pair[K, V]]) -> List[Pair[K, V]] = match self
374
- WbLeaf => acc
375
- WbNode(_, nk, nv, l, r) => l.collect(Cons(head: Pair(first: nk, second: nv), tail: r.collect(acc)))
376
-
377
- # ---------------------------------------------------------------------------
378
- # Test helpers. Tests may use loops, `mut` fields and std's `Map` as the
379
- # reference model; the structure above may not.
380
- # ---------------------------------------------------------------------------
381
-
382
- fun wbInts() -> WeightBalancedTree[Int, Int] =
383
- t: WeightBalancedTree[Int, Int] := WeightBalancedTree.ints()
384
- t
385
-
386
- # Inserts each key `k` with value `k * 10`, in order.
387
- fun wbOf(keys: List[Int]) -> WeightBalancedTree[Int, Int] =
388
- keys.fold(wbInts(), |t, k| t.insert(k, k * 10))
389
-
390
- # The size of `t` if every node's cached size is right and every node is weight
391
- # balanced (a side holds at most `Delta` times the other, unless both together
392
- # hold at most one entry), else -1.
393
- fun wbCheckedSize(t: WbBranch[Int, Int]) -> Int = match t
394
- WbLeaf => 0
395
- WbNode(n, _, _, l, r) =>
396
- sl := wbCheckedSize(l)
397
- sr := wbCheckedSize(r)
398
- if sl < 0 || sr < 0 || n != sl + sr + 1
399
- -1
400
- else if sl + sr > 1 && {sl > WbBranch.Delta * sr || sr > WbBranch.Delta * sl}
401
- -1
402
- else
403
- n
404
-
405
- # True when the keys of `ks` are strictly ascending.
406
- fun wbAscending(ks: List[Int]) -> Bool = match ks
407
- Cons(a, Cons(b, rest)) =>
408
- if a >= b
409
- false
410
- else
411
- wbAscending(Cons(head: b, tail: rest))
412
- _ => true
413
-
414
- # The weight-balanced invariants: sizes cached correctly, every node balanced,
415
- # and keys strictly ascending in order.
416
- fun wbValid(t: WeightBalancedTree[Int, Int]) -> Bool =
417
- ks := t.keys()
418
- wbCheckedSize(t.root) >= 0 && ks.length() == t.length() && wbAscending(ks)
419
-
420
- # The keys of `t` as one string, for comparing with a brute-force reference.
421
- fun wbKeysOf(t: WeightBalancedTree[Int, Int]) -> Str = t.keys().toStr()
422
-
423
- # The keys 0 to `n - 1` with `keep(k)`, ascending, as a string.
424
- fun wbKeysWhere(n: Int, keep: fn(Int) -> Bool) -> Str =
425
- nil: List[Int] := Nil
426
- wbKeysBelow(n - 1, keep, nil).toStr()
427
-
428
- fun wbKeysBelow(i: Int, keep: fn(Int) -> Bool, acc: List[Int]) -> List[Int] =
429
- if i < 0
430
- acc
431
- else if keep(i)
432
- wbKeysBelow(i - 1, keep, Cons(head: i, tail: acc))
433
- else
434
- wbKeysBelow(i - 1, keep, acc)
435
-
436
- # A tree of `count` pseudo-random keys below `bound`, from seed `seed`.
437
- fun wbRandom(seed: Int, count: Int, bound: Int) -> WeightBalancedTree[Int, Int] =
438
- wbRandomFrom(wbInts(), seed, seed, count, bound)
439
-
440
- fun wbRandomFrom(t: WeightBalancedTree[Int, Int], seed: Int, x: Int, count: Int, bound: Int) -> WeightBalancedTree[Int, Int] =
441
- if count <= 0
442
- t
443
- else
444
- y := {x * 1103515245 + 12345} % 2147483648
445
- wbRandomFrom(t.insert(y % bound, seed), seed, y, count - 1, bound)
446
-
447
- # Inserts `lo` to `hi - 1` with value `2 * key`, as a tail call.
448
- fun wbRange(t: WeightBalancedTree[Int, Int], lo: Int, hi: Int) -> WeightBalancedTree[Int, Int] =
449
- if lo >= hi
450
- t
451
- else
452
- wbRange(t.insert(lo, lo * 2), lo + 1, hi)
453
-
454
- # How many keys `i` in `lo` to `hi - 1` fail `get`, `rank` or `at`.
455
- fun wbBadFrom(t: WeightBalancedTree[Int, Int], i: Int, hi: Int, bad: Int) -> Int =
456
- if i >= hi
457
- bad
458
- else if t.get(i)! != i * 2 || t.rank(i) != i || t.at(i)!.first != i
459
- wbBadFrom(t, i + 1, hi, bad + 1)
460
- else
461
- wbBadFrom(t, i + 1, hi, bad)
462
-
463
- # Removes the even keys from `i` up to `hi - 1`.
464
- fun wbRemoveEvens(t: WeightBalancedTree[Int, Int], i: Int, hi: Int) -> WeightBalancedTree[Int, Int] =
465
- if i >= hi
466
- t
467
- else
468
- wbRemoveEvens(t.remove(i), i + 2, hi)
469
-
470
- # The state of the random-operations test: the tree, the generator and the model.
471
- struct WbTestRun(mut t: WeightBalancedTree[Int, Int], mut x: Int, mut m: Map[Int, Int])
472
-
473
- test "an empty tree"
474
- t := wbInts()
475
- assert t.isEmpty()
476
- assert t.length() == 0
477
- assert t.height() == 0
478
- assert t.get(1).isNone()
479
- assert t.has(1) == false
480
- assert t.min().isNone()
481
- assert t.max().isNone()
482
- assert t.at(0).isNone()
483
- assert t.rank(5) == 0
484
- assert t.entries().isEmpty()
485
- assert t.toStr() == "[]"
486
- assert t.remove(1).isEmpty()
487
- assert t.split(3).first.isEmpty()
488
- assert t.union(t).isEmpty()
489
- assert t.intersection(t).isEmpty()
490
- assert t.difference(t).isEmpty()
491
- assert wbValid(t)
492
-
493
- test "insert, get and has"
494
- t := wbOf([5, 3, 8, 1, 4])
495
- assert t.length() == 5
496
- assert t.get(3)! == 30
497
- assert t.get(8)! == 80
498
- assert t.get(7).isNone()
499
- assert t.has(1)
500
- assert t.has(2) == false
501
- assert wbValid(t)
502
-
503
- test "insert replaces the value of an existing key"
504
- t := wbOf([1, 2, 3]).insert(2, 99)
505
- assert t.length() == 3
506
- assert t.get(2)! == 99
507
- assert t.toStr() == "[1: 10, 2: 99, 3: 30]"
508
- assert wbValid(t)
509
-
510
- test "min, max, entries, keys, values and toStr are in key order"
511
- t := wbOf([4, 2, 9, 7, 1])
512
- assert t.min()!.first == 1
513
- assert t.min()!.second == 10
514
- assert t.max()!.first == 9
515
- assert t.keys().toStr() == "[1,2,4,7,9]"
516
- assert t.values().toStr() == "[10,20,40,70,90]"
517
- assert t.entries().at(2).first == 4
518
- assert wbOf([2, 1]).toStr() == "[1: 10, 2: 20]"
519
- assert wbOf([7]).toStr() == "[7: 70]"
520
-
521
- test "remove a leaf, an inner node, the root, missing keys and everything"
522
- t := wbOf([50, 30, 70, 20, 40, 60, 80, 10, 35, 45, 65])
523
- a := t.remove(10)
524
- assert a.has(10) == false
525
- assert a.length() == 10
526
- assert wbValid(a)
527
- b := t.remove(30)
528
- assert b.keys().toStr() == "[10,20,35,40,45,50,60,65,70,80]"
529
- assert wbValid(b)
530
- c := t.remove(50)
531
- assert c.has(50) == false
532
- assert wbValid(c)
533
- assert t.remove(99).length() == 11
534
- e := t.keys().fold(t, |acc, k|
535
- next := acc.remove(k)
536
- assert wbValid(next)
537
- next
538
- )
539
- assert e.isEmpty()
540
- assert t.length() == 11
541
-
542
- test "rank counts the keys before k, present or not"
543
- t := wbOf([10, 20, 30, 40, 50])
544
- assert t.rank(10) == 0
545
- assert t.rank(30) == 2
546
- assert t.rank(50) == 4
547
- assert t.rank(5) == 0
548
- assert t.rank(35) == 3
549
- assert t.rank(99) == 5
550
-
551
- test "at gives the i-th smallest entry, None out of range"
552
- t := wbOf([30, 10, 50, 20, 40])
553
- assert t.at(0)!.first == 10
554
- assert t.at(2)!.first == 30
555
- assert t.at(2)!.second == 300
556
- assert t.at(4)!.first == 50
557
- assert t.at(5).isNone()
558
- assert t.at(-1).isNone()
559
- for i := range 5
560
- assert t.rank(t.at(i)!.first) == i
561
-
562
- test "split leaves out the key and keeps both halves valid"
563
- t := wbOf([1, 2, 3, 4, 5, 6, 7, 8, 9])
564
- p := t.split(4)
565
- assert p.first.keys().toStr() == "[1,2,3]"
566
- assert p.second.keys().toStr() == "[5,6,7,8,9]"
567
- assert wbValid(p.first) && wbValid(p.second)
568
- q := t.split(0)
569
- assert q.first.isEmpty()
570
- assert q.second.length() == 9
571
- r := t.split(100)
572
- assert r.first.length() == 9
573
- assert r.second.isEmpty()
574
- s := wbOf([2, 4, 6]).split(5)
575
- assert s.first.keys().toStr() == "[2,4]"
576
- assert s.second.keys().toStr() == "[6]"
577
- assert t.length() == 9
578
-
579
- test "union, intersection and difference; values come from self"
580
- a := wbOf([1, 2, 3, 4, 5])
581
- b := wbOf([4, 5, 6, 7]).insert(5, 0)
582
- u := a.union(b)
583
- assert u.keys().toStr() == "[1,2,3,4,5,6,7]"
584
- assert u.get(5)! == 50
585
- assert b.union(a).get(5)! == 0
586
- i := a.intersection(b)
587
- assert i.keys().toStr() == "[4,5]"
588
- assert i.get(5)! == 50
589
- assert b.intersection(a).get(5)! == 0
590
- d := a.difference(b)
591
- assert d.keys().toStr() == "[1,2,3]"
592
- assert b.difference(a).keys().toStr() == "[6,7]"
593
- assert wbValid(u) && wbValid(i) && wbValid(d)
594
- e := wbInts()
595
- assert a.union(e).length() == 5
596
- assert e.union(a).length() == 5
597
- assert a.intersection(e).isEmpty()
598
- assert a.difference(e).length() == 5
599
- assert e.difference(a).isEmpty()
600
-
601
- test "set operations on trees of very different sizes stay balanced"
602
- big := wbRandom(7, 3000, 100000)
603
- small := wbOf([5, 500, 50000, 99999, 123456])
604
- u := big.union(small)
605
- assert wbValid(u)
606
- assert u.length() == big.length() + small.difference(big).length()
607
- assert wbValid(small.union(big))
608
- assert wbValid(big.intersection(small))
609
- assert wbValid(small.intersection(big))
610
- d := big.difference(small)
611
- assert wbValid(d)
612
- assert d.length() + big.intersection(small).length() == big.length()
613
- assert wbValid(small.difference(big))
614
-
615
- test "set operations agree with a filter over pseudo-random trees"
616
- for seed := range 1.to(20)
617
- a := wbRandom(seed, 300, 400)
618
- b := wbRandom(seed * 7919, 200, 400)
619
- u := a.union(b)
620
- i := a.intersection(b)
621
- d := a.difference(b)
622
- assert wbValid(u) && wbValid(i) && wbValid(d)
623
- assert wbKeysOf(u) == wbKeysWhere(400, |k| a.has(k) || b.has(k))
624
- assert wbKeysOf(i) == wbKeysWhere(400, |k| a.has(k) && b.has(k))
625
- assert wbKeysOf(d) == wbKeysWhere(400, |k| a.has(k) && !b.has(k))
626
- for e := range u.entries()
627
- if a.has(e.first)
628
- assert e.second == a.get(e.first)!
629
- p := a.split(200)
630
- assert wbValid(p.first) && wbValid(p.second)
631
- assert wbKeysOf(p.first) == wbKeysWhere(200, |k| a.has(k))
632
- assert p.first.length() == a.rank(200)
633
-
634
- test "old versions are unchanged after updates and set operations"
635
- t1 := wbOf([1, 2, 3, 4, 5])
636
- t2 := t1.insert(6, 60)
637
- t3 := t2.remove(1).insert(3, 0)
638
- t4 := t3.union(wbOf([9])).difference(wbOf([2]))
639
- p := t4.split(5)
640
- assert t1.keys().toStr() == "[1,2,3,4,5]"
641
- assert t1.get(3)! == 30
642
- assert t2.keys().toStr() == "[1,2,3,4,5,6]"
643
- assert t2.get(3)! == 30
644
- assert t3.keys().toStr() == "[2,3,4,5,6]"
645
- assert t3.get(3)! == 0
646
- assert t4.keys().toStr() == "[3,4,5,6,9]"
647
- assert p.first.keys().toStr() == "[3,4]"
648
- assert wbValid(t1) && wbValid(t2) && wbValid(t3) && wbValid(t4)
649
-
650
- test "10,000 ascending keys stay balanced, with ranks and positions"
651
- t := wbRange(wbInts(), 0, 10000)
652
- assert t.length() == 10000
653
- assert wbValid(t)
654
- assert t.height() <= 30
655
- assert wbBadFrom(t, 0, 10000, 0) == 0
656
- u := wbRemoveEvens(t, 0, 10000)
657
- assert u.length() == 5000
658
- assert wbValid(u)
659
- assert u.at(0)!.first == 1
660
- assert u.rank(5001) == 2500
661
- assert t.length() == 10000
662
- assert t.at(0)!.first == 0
663
-
664
- test "invariants hold through pseudo-random inserts and removes"
665
- run := WbTestRun(t: wbInts(), x: 12345, m: Map.empty())
666
- for i := range 4000
667
- run.x = {run.x * 1103515245 + 12345} % 2147483648
668
- k := run.x % 500
669
- if run.x % 3 == 0
670
- run.t = run.t.remove(k)
671
- run.m = run.m.remove(k)
672
- else
673
- run.t = run.t.insert(k, i)
674
- run.m = run.m.with(k, i)
675
- if i % 20 == 0
676
- assert wbValid(run.t)
677
- assert wbValid(run.t)
678
- assert run.t.length() == run.m.length()
679
- es := run.m.entries()
680
- bad := 0.until(es.length()).fold(0, |b, j| if run.t.get(es.at(j).first)! != es.at(j).second then b + 1 else b)
681
- assert bad == 0
682
-
683
- test "the invariant checker rejects wrong sizes and unbalanced nodes"
684
- e: WbBranch[Int, Int] := WbLeaf
685
- wrongSize := WbNode(size: 5, key: 1, value: 10, left: e, right: e)
686
- assert wbCheckedSize(wrongSize) == -1
687
- chain := WbBranch.bin(1, 10, e, WbBranch.bin(2, 20, e, WbBranch.bin(3, 30, e, e)))
688
- assert wbCheckedSize(chain) == -1
689
- assert wbCheckedSize(WbBranch.bin(2, 20, WbBranch.bin(1, 10, e, e), e)) == 2
690
- unordered := WeightBalancedTree(root: WbBranch.bin(5, 50, e, WbBranch.bin(1, 10, e, e)), before: |a, b| a < b)
691
- assert wbValid(unordered) == false
692
-
693
- test "a custom order: longest Str first"
694
- t0: WeightBalancedTree[Str, Int] := WeightBalancedTree.by(|a, b| a.length() > b.length())
695
- t := t0.insert("pear", 1).insert("apple", 2).insert("zucchini", 3).insert("fig", 4)
696
- assert t.keys().toStr() == "[zucchini,apple,pear,fig]"
697
- assert t.at(1)!.first == "apple"
698
- assert t.rank("kiwi") == 2
699
- assert t.remove("pear").keys().toStr() == "[zucchini,apple,fig]"