plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
9b895aa
— Peter John
2026-11-10T14:23:46+05:30
Docs: the std layout (collections, encoding, math, flat game)
- docs/game.md +5 -5
- docs/std.md +7 -7
- std/collections/BPlusTree.plum +4 -4
- std/collections/Bvh.plum +2 -2
- std/collections/FenwickTree.plum +2 -2
- std/collections/KdTree.plum +3 -3
- std/collections/Quadtree.plum +1 -1
- std/collections/RadixTree.plum +4 -4
- std/collections/RedBlackTree.plum +1 -1
- std/collections/SegmentTree.plum +2 -2
- std/collections/Treap.plum +1 -1
- std/collections/Trie.plum +3 -3
- std/collections/WeightBalancedTree.plum +1 -1
docs/game.md
CHANGED
|
@@ -184,7 +184,7 @@ The host adds up the time between frames and runs one tick (`Game.update`) for e
|
|
|
184
184
|
|
|
185
185
|
The tick's `Input` (`ctx.input`) is read from the host once per frame, before the ticks. A frame's key and pointer events go to its first tick, or to the next frame's if it ran none, so a press counts once. Later ticks of the frame see what is held, with no events. Actors and rules have no `io`, so they can't read input any other way.
|
|
186
186
|
|
|
187
|
-
Keep randomness in the state `S`: a `Random` ([`std/math/Random.plum`](../std/Random.plum)) seeded once in `main` from `io.randomSeed()`, drawn from only in `update` (`r := self.rng.nextFloat()`, then keep `r.rng` in the next state). Then the same seed and the same inputs give the same game, tick for tick, and a test can play one: `game.step(io, input, 1.0 / 60.0, view)` from one seed and one list of inputs gives the same game each time. Orb Run's `same_seed_same_game` test does exactly this.
|
|
187
|
+
Keep randomness in the state `S`: a `Random` ([`std/math/Random.plum`](../std/math/Random.plum)) seeded once in `main` from `io.randomSeed()`, drawn from only in `update` (`r := self.rng.nextFloat()`, then keep `r.rng` in the next state). Then the same seed and the same inputs give the same game, tick for tick, and a test can play one: `game.step(io, input, 1.0 / 60.0, view)` from one seed and one list of inputs gives the same game each time. Orb Run's `same_seed_same_game` test does exactly this.
|
|
188
188
|
|
|
189
189
|
The maths is the same everywhere too. std's maths (`math.sin`, `math.sqrt`, ...) is Plum code built from IEEE 754 double operations, which wasm defines exactly, so every browser and the native host get the same bits; a test in [`tests/port/game/replay.plum`](../tests/port/game/replay.plum) pins some of them. The one host value a tick reads is the screen size (`ctx.view`), and a replay records it (see below).
|
|
190
190
|
|
|
@@ -246,16 +246,16 @@ If the new code has a compile error, the old game keeps running and the error ap
|
|
|
246
246
|
|
|
247
247
|
## Scenes
|
|
248
248
|
|
|
249
|
-
A game's actors live in a scene tree from [`std/game
|
|
249
|
+
A game's actors live in a scene tree from [`std/game`](../std/game): a `SceneTree[M]` ([`SceneTree.plum`](../std/game/SceneTree.plum)) is a tree of actors that lives from frame to frame, and `M` is the game's message type. It is a value like the rest of your game: every change returns a new tree, and a kept old tree stays as it was. When nothing holds the old one, the compiler writes the new one into its cells.
|
|
250
250
|
|
|
251
|
-
Each kind of actor is its own struct, with only its own fields, that `is Actor[M]` ([`Actor.plum`](../std/game/
|
|
251
|
+
Each kind of actor is its own struct, with only its own fields, that `is Actor[M]` ([`Actor.plum`](../std/game/Actor.plum)). It must say which actor it is (`key`, the id the tree finds it by) and where it is in its parent (`place`, a `Place` with a position, scale, rotation and origin). Everything else has a default that it may override:
|
|
252
252
|
|
|
253
|
-
- `step(self, ctx, dt)` returns its next version, once a tick. `ctx` ([`Ctx.plum`](../std/game/
|
|
253
|
+
- `step(self, ctx, dt)` returns its next version, once a tick. `ctx` ([`Ctx.plum`](../std/game/Ctx.plum)) has its parent's world transform and alpha, the tick's input (`ctx.input`) and the screen's size (`ctx.view`), and takes commands for after the step: `ctx.out.push(Spawn(parent, node))`, `ctx.out.push(Kill(id))`, `ctx.send(msg)`, `ctx.out.push(Restart)` and `ctx.out.push(Exit)`.
|
|
254
254
|
- `input(self, ctx, e)` returns its next version after a pointer event on it or on one of its children, before the tick's steps. `e` is in its own coordinates.
|
|
255
255
|
- `paint(self, io, m, alpha)` draws it in its own coordinates seen through `m`. `Actor.plum` has helpers for boxes, circles, lines, sprites and text (`actor.boxPaint(io, m, alpha, w, h, color)`, ...).
|
|
256
256
|
- `shown`, `gone` and `opacity`: a hidden actor isn't drawn or hit, a gone one is dropped with its subtree, and opacities multiply down the tree.
|
|
257
257
|
|
|
258
|
-
An actor the pointer can hit says so with a second trait, `Clickable` (
|
|
258
|
+
An actor the pointer can hit says so with a second trait, `Clickable` ([`Clickable.plum`](../std/game/Clickable.plum)): `struct Target(..) is Actor[Msg], Clickable =`, with `hit(self, p) -> Bool`, whether a point in its own coordinates is on it. Only a `Clickable` actor that says it is hit gets a pointer event (and its parents after it, clickable or not), and is found by `tree.hit(x, y)` and `tree.hitId(x, y)`, topmost first. The tree's pointer walk skips every other actor with one type-tag test, and computes the transform of one only when it has children (who may be clickable). A `hit` on an actor that isn't `Clickable` is a plain method the tree never calls, and nothing warns about it: if an actor gets no clicks, check its `is` list.
|
|
259
259
|
|
|
260
260
|
```plum
|
|
261
261
|
struct Target(id: Int, x: Float, y: Float) is Actor[Msg], Clickable =
|
docs/std.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# The standard library
|
|
2
2
|
|
|
3
|
-
Import what you use: `import std/Str`, `import std/Slice`, and so on. The source is in [`std/`](../std), and it is plain Plum, so it's a good place to read how things work.
|
|
3
|
+
Import what you use: `import std/Str`, `import std/Slice`, and so on. Most modules sit right under `std`; the collections are in `std/collections` (`import std/collections/List`), `Json` and `base64` in `std/encoding`, `math`, `Random`, `Aabb`, `Vec2` and `Affine` in `std/math`, and the game engine in `std/game`. A folder is not a module: each file is imported by its full path. The source is in [`std/`](../std), and it is plain Plum, so it's a good place to read how things work.
|
|
4
4
|
|
|
5
5
|
The [game engine](game.md) has its own page.
|
|
6
6
|
|
|
@@ -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
|
-
| [`
|
|
14
|
+
| [`AvlTree`, `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
|
| [`os`, `http`](#files-and-network) | files and the network |
|
|
@@ -42,7 +42,7 @@ Where wasm has the operation, std uses its instruction, compiled in line at each
|
|
|
42
42
|
|
|
43
43
|
At the edges they follow IEEE 754. `x.logb()` is the exponent of `|x|`, floor(log2(|x|)) exactly, read from the bits (a subnormal is scaled by 2^54 first): `7.999999999999999.logb()` is `2.0`, `Float.Min.logb()` is `-1074.0`, `logb` of a zero is -Infinity, of either infinity Infinity, of NaN NaN, and the sign is ignored (`Int.logb` agrees: `Int.Min.logb()` is `63.0`). `math.cbrt` is correctly rounded (no miss in a million sampled inputs over every exponent) for every Float, subnormals and `1e300` included (`cbrt(1e300)` is `1e100`): `|x|` is split into `m * 2^(3k)` from the bits, FreeBSD's `s_cbrt.c` guess gives a 23-bit root `t` of `m`, and `t * (1 + u)^(1/3)` with `u = (m - t^3) / t^3` (the residual exact but for one rounding, by Dekker's product; the binomial series to u^4) rounds to the nearest float unless the root is within about 2^-22 ulp of halfway. It keeps the sign (`cbrt(-0.0)` is `-0.0`), and NaN and the infinities pass through. `math.sin`, `math.cos` and `math.tan` are fdlibm's (FreeBSD's `s_sin.c`, `s_cos.c`, `s_tan.c`), under 1 ulp for every finite Float: against mpmath over 89k sampled inputs (every exponent, multiples of Pi/2 and the floats next to them, subnormals) at worst 0.72, 0.74 and 0.81 ulp, with 1.4%, 1.5% and 1.7% not the nearest float (the old Taylor series after a plain subtraction of multiples of 2*Pi was up to 10^22 ulp off next to the zeros, and for |x| <= 4 36%, 68% and 68% not the nearest). `x` is reduced to `n * Pi/2 + r` with `|r| <= Pi/4`: below 2^20 * Pi/2 (about 1.6e6) by Cody and Waite's subtraction with Pi/2 in three 33-bit parts, above it by multiplying the 53-bit significand by 240 bits of 2/Pi in integers (Payne and Hanek), so `sin(1e22)` is `-0.8522008497671888` and `sin(Float.Max)` is right too; then fdlibm's kernel polynomials for sin, cos and tan on `r`. A tiny `x` (below 2^-26 for `sin`, 2^-27 for `tan`) is its own `sin` and `tan`, a subnormal included, and its `cos` is `1.0`; the infinities and NaN give NaN. `math.atan` is fdlibm's `s_atan.c` bit for bit, under 1 ulp (0.70 at worst over 40k sampled inputs against mpmath): breakpoints at 7/16, 11/16, 19/16 and 39/16, then a degree-22 odd polynomial; from 2^66 up, and at the infinities, it is `±Pi/2`. `math.atan2` is fdlibm's `e_atan2.c` (1.36 ulp at worst) with C99's special cases: `atan2(±0, x)` is `±0` for `x` above zero or `+0` and `±Pi` for `x` below zero or `-0`, `atan2(y, ±0)` for a nonzero `y` is `±Pi/2`, an infinite `x` gives `±0` or `±Pi` for a finite `y` and `±Pi/4` or `±3*Pi/4` for an infinite one, an infinite `y` gives `±Pi/2`, and a NaN on either side gives NaN. `math.asin` is `atan(x / sqrt(1 - x*x))` with `(1 - x) * (1 + x)` from `|x| = 0.5` up, and `math.acos` is `2 * atan(sqrt((1 - x) / (1 + x)))`, both within 1.8 ulp (`acos` was `Pi/2 - asin(x)`, 231 ulp off near 1). `sin(-0.0)`, `tan(-0.0)`, `asin(-0.0)` and `atan(-0.0)` are `-0.0`.
|
|
44
44
|
|
|
45
|
-
`Int.toStr` prints every Int, `Int.Min` as `-9223372036854775808`. `Float.toStr` rounds to 6 fractional digits below 2^63; from 2^63 up (past Int's range, where every Float is whole) it prints the float's exact decimal value, so `1.0e20.toStr()` is `100000000000000000000.0` and `Float.Max` prints all 309 digits. `Float.hash` is the bits (`toBits`), so values in (-1, 1) don't collide in
|
|
45
|
+
`Int.toStr` prints every Int, `Int.Min` as `-9223372036854775808`. `Float.toStr` rounds to 6 fractional digits below 2^63; from 2^63 up (past Int's range, where every Float is whole) it prints the float's exact decimal value, so `1.0e20.toStr()` is `100000000000000000000.0` and `Float.Max` prints all 309 digits. `Float.hash` is the bits (`toBits`), so values in (-1, 1) don't collide in a `Hamt`; `0.0` and `-0.0`, which are `==`, both hash to 0, and every NaN hashes the same.
|
|
46
46
|
|
|
47
47
|
`compare(o)` gives -1, 0 or 1 as the receiver is below, equal to or above `o`; it is the order of `Map` keys and `Set` members. `Float.compare` is a total order: `-0.0` and `0.0` compare equal, and every NaN equals every other NaN and comes after `Infinity` (so `-Infinity < -1.0 < -0.0 == 0.0 < Infinity < NaN`). `Bool.compare` puts `false` first, `Byte.compare` is by value.
|
|
48
48
|
- `Bool`: `toStr`, `Bool.parse`, `compare`
|
|
@@ -133,11 +133,11 @@ Gone or changed from the old hash table: `set`, `remove` and `putIfAbsent` retur
|
|
|
133
133
|
- **`Deque`:** a queue you can use from both ends: `pushBack`, `pushFront`, `popBack`, `popFront`, `get`, `at` (crashes out of range)
|
|
134
134
|
- **`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`
|
|
135
135
|
|
|
136
|
-
##
|
|
136
|
+
## Persistent trees, heaps and graphs
|
|
137
137
|
|
|
138
|
-
`std/collections
|
|
138
|
+
`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`).
|
|
139
139
|
|
|
140
|
-
Plum types are global by name, so
|
|
140
|
+
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`). `std/collections/text` is their text helper (`text.join(parts, sep)` joins a `List[Str]`), which `toStr` uses instead of a `Buffer`.
|
|
141
141
|
|
|
142
142
|
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.
|
|
143
143
|
|
|
@@ -150,7 +150,7 @@ Only true tail calls run in constant stack; other recursion overflows at a few t
|
|
|
150
150
|
- **`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.
|
|
151
151
|
- **`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`).
|
|
152
152
|
- **`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.
|
|
153
|
-
- **`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/
|
|
153
|
+
- **`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).
|
|
154
154
|
- **`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.
|
|
155
155
|
|
|
156
156
|
## Option and Result
|
std/collections/BPlusTree.plum
CHANGED
|
@@ -32,7 +32,7 @@ import std/collections/text
|
|
|
32
32
|
# cannot (relinking a leaf would rebuild every leaf before it). The twin walks with a
|
|
33
33
|
# mutable iterator holding a stack; here `range(lo, hi)` is a recursion from the root
|
|
34
34
|
# that only enters the children overlapping `[lo, hi)`, and `from(lo)` / `cursor()`
|
|
35
|
-
# return
|
|
35
|
+
# return a `BpCursor`, a persistent position (the rest of the current leaf and, per
|
|
36
36
|
# level above it, the children still to visit) whose `next()` gives the entry and the
|
|
37
37
|
# cursor after it. `fromSorted` bulk-loads a sorted `List` in O(n).
|
|
38
38
|
#
|
|
@@ -229,7 +229,7 @@ struct BPlusTree[K, V](root: BpNode[K, V], size: Int, order: Int, before: fn(K,
|
|
|
229
229
|
fun toStr(self) -> Str =
|
|
230
230
|
text.bracket(self.entries().map(|e| e.toStr()), ", ")
|
|
231
231
|
|
|
232
|
-
# A node of
|
|
232
|
+
# A node of a `BPlusTree`: a leaf of entries (keys ascending), or an inner node of
|
|
233
233
|
# `kids` with one separator key between each two.
|
|
234
234
|
enum BpNode[K, V] =
|
|
235
235
|
| BpLeaf(entries: List[Pair[K, V]])
|
|
@@ -329,7 +329,7 @@ enum BpPut[K, V] =
|
|
|
329
329
|
# Two sibling nodes and the separator between them, after a borrow.
|
|
330
330
|
struct BpTrio[K, V](left: BpNode[K, V], sep: K, right: BpNode[K, V])
|
|
331
331
|
|
|
332
|
-
# A persistent position in
|
|
332
|
+
# A persistent position in a `BPlusTree`'s key order: `here` is the rest of the
|
|
333
333
|
# current leaf, `above` the children still to visit at each level above it, nearest
|
|
334
334
|
# level first. Moving on builds a new cursor; the old one still points where it did.
|
|
335
335
|
struct BpCursor[K, V](here: List[Pair[K, V]], above: List[List[BpNode[K, V]]]) =
|
|
@@ -357,7 +357,7 @@ struct BpCursor[K, V](here: List[Pair[K, V]], above: List[List[BpNode[K, V]]]) =
|
|
|
357
357
|
BpEnd => acc
|
|
358
358
|
BpAt(e, rest) => rest.takeOnto(n - 1, Cons(head: e, tail: acc))
|
|
359
359
|
|
|
360
|
-
# One step of
|
|
360
|
+
# One step of a `BpCursor`.
|
|
361
361
|
enum BpStep[K, V] =
|
|
362
362
|
| BpEnd
|
|
363
363
|
| BpAt(entry: Pair[K, V], rest: BpCursor[K, V])
|
std/collections/Bvh.plum
CHANGED
|
@@ -15,7 +15,7 @@ import std/collections/Set
|
|
|
15
15
|
# std/collections/AvlTree 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
|
-
# `List` of (box, value) pairs at once; nothing changes it afterwards, so
|
|
18
|
+
# `List` of (box, value) pairs at once; nothing changes it afterwards, so a `Bvh` can
|
|
19
19
|
# be shared freely (rebuild it when the boxes move). Same API as the twin, except that
|
|
20
20
|
# `build` takes and `overlapping` and `pairs` return a `List` instead of a `Slice`.
|
|
21
21
|
#
|
|
@@ -84,7 +84,7 @@ fun bvhGrow(c: Aabb, p: Vec2) -> Aabb =
|
|
|
84
84
|
# above the pivot, with the first two counted.
|
|
85
85
|
struct BvhParts[V](lt: List[Pair[Aabb, V]], nlt: Int, eq: List[Pair[Aabb, V]], neq: Int, gt: List[Pair[Aabb, V]])
|
|
86
86
|
|
|
87
|
-
# A node of
|
|
87
|
+
# A node of a `Bvh`: a leaf holds one box and its value, a branch holds the union
|
|
88
88
|
# of its two children's boxes.
|
|
89
89
|
enum BvhNode[V] =
|
|
90
90
|
| BvhEmpty
|
std/collections/FenwickTree.plum
CHANGED
|
@@ -15,7 +15,7 @@ import std/Slice
|
|
|
15
15
|
# around in, so it does not apply here. Instead the indices are a balanced binary tree
|
|
16
16
|
# over ranges: the root covers [0, n), a node over [lo, hi) splits at
|
|
17
17
|
# mid = lo + (hi - lo) / 2, and a branch stores only the sum of its LEFT half; a range of
|
|
18
|
-
# one element is
|
|
18
|
+
# one element is a `FenLeaf` holding that element. That is all a prefix query needs:
|
|
19
19
|
# `prefixSum(i)` walks one path, adding the left sum of every node where it turns right.
|
|
20
20
|
# A Fenwick tree is the same idea in an array: its slots are the left-half blocks of such
|
|
21
21
|
# a tree. Compared with std/collections/SegmentTree, it is a segment tree
|
|
@@ -87,7 +87,7 @@ struct FenwickTree(root: FenNode, size: Int) =
|
|
|
87
87
|
fun toList(self) -> List[Int] =
|
|
88
88
|
self.root.collect(0, self.size, Nil).values
|
|
89
89
|
|
|
90
|
-
# The nodes of
|
|
90
|
+
# The nodes of a `FenwickTree`: `FenEmpty` (only the root of an empty tree), one
|
|
91
91
|
# element, or a range split in two that keeps the sum of its left half.
|
|
92
92
|
enum FenNode =
|
|
93
93
|
| FenEmpty
|
std/collections/KdTree.plum
CHANGED
|
@@ -28,7 +28,7 @@ import std/collections/text
|
|
|
28
28
|
# `n / 2` (stable, so the same tree as the twin, O(n log^2 n)). The twin's queries are
|
|
29
29
|
# `while` loops over an explicit stack of frames; here the same stack is a `List`
|
|
30
30
|
# argument of a tail-recursive walk (`kWalk`, `radiusWalk`, `entriesWalk`,
|
|
31
|
-
# `heightWalk`) that also threads the result: the k best so far (
|
|
31
|
+
# `heightWalk`) that also threads the result: the k best so far (a `KdBest`, a
|
|
32
32
|
# sorted cons list of hits, its count and its worst distance) or an accumulator list.
|
|
33
33
|
# `insert` walks down as a tail call collecting the passed nodes (with the side not
|
|
34
34
|
# taken) in reverse, then rebuilds the path upwards with a second tail call (`under`).
|
|
@@ -154,7 +154,7 @@ struct KdTree[V](root: KdNode[V], size: Int) =
|
|
|
154
154
|
fun toStr(self) -> Str =
|
|
155
155
|
text.bracket(self.entries().map(|e| "({e.first.x}, {e.first.y}): {e.second.toStr()}"), ", ")
|
|
156
156
|
|
|
157
|
-
# The nodes of
|
|
157
|
+
# The nodes of a `KdTree`: `KdLeaf`, or an entry with the subtrees on either side of
|
|
158
158
|
# its split line. The split axis is not stored; it comes from the depth.
|
|
159
159
|
enum KdNode[V] =
|
|
160
160
|
| KdLeaf
|
|
@@ -207,7 +207,7 @@ enum KdNode[V] =
|
|
|
207
207
|
# taken, and which side was taken.
|
|
208
208
|
struct KdStep[V](point: Vec2, value: V, other: KdNode[V], wentLeft: Bool)
|
|
209
209
|
|
|
210
|
-
# A node still to visit in
|
|
210
|
+
# A node still to visit in a `KdTree` query, at `depth`, with `bound` a lower bound
|
|
211
211
|
# on the squared distance from the query point to anything below it.
|
|
212
212
|
struct KdFrame[V](node: KdNode[V], depth: Int, bound: Float)
|
|
213
213
|
|
std/collections/Quadtree.plum
CHANGED
|
@@ -90,7 +90,7 @@ struct Quadtree[V](root: QuadNode[V], bounds: Aabb, capacity: Int, maxDepth: Int
|
|
|
90
90
|
fun toStr(self) -> Str =
|
|
91
91
|
text.bracket(self.entries().map(|e| "({e.first.x}, {e.first.y}): {e.second.toStr()}"), ", ")
|
|
92
92
|
|
|
93
|
-
# The nodes of
|
|
93
|
+
# The nodes of a `Quadtree`: a leaf of entries (newest first) with their count, or
|
|
94
94
|
# four quarters (numbered as in `quadQuadrantOf`) with the total count below. A
|
|
95
95
|
# node's box is not stored; it comes from the parent's on the way down.
|
|
96
96
|
enum QuadNode[V] =
|
std/collections/RadixTree.plum
CHANGED
|
@@ -14,7 +14,7 @@ import std/collections/Trie
|
|
|
14
14
|
# for the rules these persistent collections follow): a persistent map from `Str` keys to values, a radix
|
|
15
15
|
# tree (compressed trie) where each edge is labelled with a non-empty run of key bytes,
|
|
16
16
|
# so a chain of single-child nodes becomes one edge. Each node holds an optional value
|
|
17
|
-
# and its edges as
|
|
17
|
+
# and its edges as a `RadixEdges` cons list of (label, child) sorted by the label's
|
|
18
18
|
# first byte; no two sibling labels share a first byte. Keys are UTF-8 bytes, so they
|
|
19
19
|
# sort by byte, which for UTF-8 is code point order. `insert` splits an edge where a
|
|
20
20
|
# new key leaves it; `remove` drops a node left empty and merges a node left with no
|
|
@@ -122,7 +122,7 @@ fun radixCommon(a: Str, ai: Int, b: Str, c: Int) -> Int =
|
|
|
122
122
|
else
|
|
123
123
|
c
|
|
124
124
|
|
|
125
|
-
# A node of
|
|
125
|
+
# A node of a `RadixTree`: the value of the key that ends here, if any, and the
|
|
126
126
|
# labelled edges down to the children.
|
|
127
127
|
struct RadixNode[V](value: Option[V], edges: RadixEdges[V]) =
|
|
128
128
|
|
|
@@ -268,7 +268,7 @@ struct RadixNode[V](value: Option[V], edges: RadixEdges[V]) =
|
|
|
268
268
|
None => out
|
|
269
269
|
Some(v) => Cons(head: Pair(first: key, second: v), tail: out)
|
|
270
270
|
|
|
271
|
-
# The edges of
|
|
271
|
+
# The edges of a `RadixNode`: (label, child) pairs sorted by the label's first byte,
|
|
272
272
|
# labels non-empty, no first byte twice.
|
|
273
273
|
enum RadixEdges[V] =
|
|
274
274
|
| RadixNoEdge
|
|
@@ -646,7 +646,7 @@ test "the edge list stays sorted by first byte"
|
|
|
646
646
|
assert es2.find(98).isNone()
|
|
647
647
|
assert es2.labelsStr() == "abc mx z "
|
|
648
648
|
|
|
649
|
-
test "invariants_after_random_ops: pseudo-random inserts and removes match
|
|
649
|
+
test "invariants_after_random_ops: pseudo-random inserts and removes match a Trie and a Map"
|
|
650
650
|
empty: RadixTree[Int] := RadixTree.empty()
|
|
651
651
|
emptyTrie: Trie[Int] := Trie.empty()
|
|
652
652
|
run := RadixRun(t: empty, tr: emptyTrie, s: 7, bad: 0)
|
std/collections/RedBlackTree.plum
CHANGED
|
@@ -84,7 +84,7 @@ struct RedBlackTree[K, V](root: RbBranch[K, V], size: Int, before: fn(K, K) -> B
|
|
|
84
84
|
# The entries in key order: `[1: one, 2: two]`.
|
|
85
85
|
fun toStr(self) -> Str = text.bracket(self.entries().map(|e| e.toStr()), ", ")
|
|
86
86
|
|
|
87
|
-
# The nodes of
|
|
87
|
+
# The nodes of a `RedBlackTree`: `RbLeaf` (black), or a red or black node with its
|
|
88
88
|
# key and value, the subtree of smaller keys on the left and larger on the right. The
|
|
89
89
|
# functions follow Kahrs, "Red-black trees with types" (2001).
|
|
90
90
|
enum RbBranch[K, V] =
|
std/collections/SegmentTree.plum
CHANGED
|
@@ -19,7 +19,7 @@ import std/Slice
|
|
|
19
19
|
# one is a recursive range tree: the root covers [0, n), a node over [lo, hi) with
|
|
20
20
|
# hi - lo > 1 splits at mid = lo + (hi - lo) / 2 into a left child over [lo, mid) and a
|
|
21
21
|
# right child over [mid, hi), and caches the combined value of its range; a range of one
|
|
22
|
-
# element is
|
|
22
|
+
# element is a `SegLeaf`. The ranges are not stored: every walk passes them down. `set`
|
|
23
23
|
# and `update` rebuild the O(log n) nodes on the path to the element and return a new tree
|
|
24
24
|
# that shares every other node; the old tree still answers old queries. `ofSize` shares
|
|
25
25
|
# equal-sized halves, so it builds in O(log n) nodes; `ofList` is O(n). `ofArray` is gone
|
|
@@ -86,7 +86,7 @@ struct SegmentTree[T](root: SegNode[T], size: Int, combine: fn(T, T) -> T, ident
|
|
|
86
86
|
fun toList(self) -> List[T] =
|
|
87
87
|
self.root.collect(Nil)
|
|
88
88
|
|
|
89
|
-
# The nodes of
|
|
89
|
+
# The nodes of a `SegmentTree`: `SegEmpty` (only the root of an empty tree), one
|
|
90
90
|
# element, or the combined value of a range over its two halves.
|
|
91
91
|
enum SegNode[T] =
|
|
92
92
|
| SegEmpty
|
std/collections/Treap.plum
CHANGED
|
@@ -149,7 +149,7 @@ struct Treap[K, V](root: TreapNode[K, V], before: fn(K, K) -> Bool, rng: Random)
|
|
|
149
149
|
# the key itself (a single node, or `TreapLeaf` when absent), and the keys after it.
|
|
150
150
|
struct TreapParts[K, V](less: TreapNode[K, V], found: TreapNode[K, V], greater: TreapNode[K, V])
|
|
151
151
|
|
|
152
|
-
# The nodes of
|
|
152
|
+
# The nodes of a `Treap`: `TreapLeaf`, or a key and value with its priority, the
|
|
153
153
|
# size of the subtree it roots, the smaller keys on the left and the larger on the
|
|
154
154
|
# right. A node's priority is at least that of each child.
|
|
155
155
|
enum TreapNode[K, V] =
|
std/collections/Trie.plum
CHANGED
|
@@ -13,7 +13,7 @@ import std/collections/text
|
|
|
13
13
|
# for the rules these persistent collections follow): a persistent map from `Str` keys to values, a trie
|
|
14
14
|
# with one node per byte of the key (a key is its UTF-8 bytes, so keys sort by byte,
|
|
15
15
|
# which for UTF-8 is code point order). Each node holds an optional value and its
|
|
16
|
-
# children as
|
|
16
|
+
# children as a `TrieKids` cons list of (byte, child) sorted by byte. `insert` and
|
|
17
17
|
# `remove` rebuild only the nodes on the key's path and share every other subtree, so
|
|
18
18
|
# the old trie stays as it was. `remove` prunes the branches it empties, so every node
|
|
19
19
|
# other than the root leads to at least one key. Same API as `Trie`, except that
|
|
@@ -111,7 +111,7 @@ struct Trie[V](root: TrieNode[V], size: Int) =
|
|
|
111
111
|
fun toStr(self) -> Str =
|
|
112
112
|
text.bracket(self.entries().map(|e| e.toStr()), ", ")
|
|
113
113
|
|
|
114
|
-
# A node of
|
|
114
|
+
# A node of a `Trie`: the value of the key that ends here, if any, and the
|
|
115
115
|
# children, one per next byte.
|
|
116
116
|
struct TrieNode[V](value: Option[V], kids: TrieKids[V]) =
|
|
117
117
|
|
|
@@ -208,7 +208,7 @@ struct TrieFrame[V](prefix: Str, pending: List[Int], node: TrieNode[V]) =
|
|
|
208
208
|
Nil => self.prefix
|
|
209
209
|
Cons(_, _) => self.prefix.concat(text.join(self.pending.reverse().map(|b| Str.byteToStr(b)), ""))
|
|
210
210
|
|
|
211
|
-
# The children of
|
|
211
|
+
# The children of a `TrieNode`: a list of (byte, child) sorted by byte, no byte
|
|
212
212
|
# twice.
|
|
213
213
|
enum TrieKids[V] =
|
|
214
214
|
| TrieNoKid
|
std/collections/WeightBalancedTree.plum
CHANGED
|
@@ -125,7 +125,7 @@ struct WeightBalancedTree[K, V](root: WbBranch[K, V], before: fn(K, K) -> Bool)
|
|
|
125
125
|
# entries after it.
|
|
126
126
|
struct WbCut[K, V](below: WbBranch[K, V], found: Option[V], above: WbBranch[K, V])
|
|
127
127
|
|
|
128
|
-
# The nodes of
|
|
128
|
+
# The nodes of a `WeightBalancedTree`: `WbLeaf`, or a key and value with the
|
|
129
129
|
# subtree of smaller keys on the left, larger on the right, and the number of
|
|
130
130
|
# entries in the whole subtree cached.
|
|
131
131
|
enum WbBranch[K, V] =
|