plum

#treesitter#compiler#wasm

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

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


a1ad85f — Peter John 2026-11-09T12:32:39+05:30
std/collections/functional/FRoseTree: move ETree out of game_enum_tree
benchmarks/scene_trees/game_enum_tree.plum CHANGED
@@ -11,7 +11,7 @@ import std/Slice
11
11
  import std/game/Vec2
12
12
  import std/game/Affine
13
13
  import std/game/Color
14
- import std/game_enum_tree/ETree
14
+ import std/collections/functional/FRoseTree
15
15
  import std/game_enum_tree/Actor
16
16
  import std/game_enum_tree/ECtx
17
17
  import std/game_enum_tree/EStage
@@ -73,12 +73,12 @@ struct Bod(vx: Float, vy: Float, moves: Bool) =
73
73
  fun group(id: Int, x: Float, y: Float, s: Float, r: Float) -> Actor[Bod] =
74
74
  Actor.turned(id, x, y, s, r, Bod(vx: 0.0, vy: 0.0, moves: false))
75
75
 
76
- fun newLeaf(rng: Rng, id: Int) -> ETree[Actor[Bod]] =
76
+ fun newLeaf(rng: Rng, id: Int) -> FRoseTree[Actor[Bod]] =
77
77
  x := rng.float(200)
78
78
  y := rng.float(200)
79
79
  vx := rng.float(100) - 50.0
80
80
  vy := rng.float(100) - 50.0
81
- etree.leaf(Actor.rect(id, x, y, 20.0, 20.0, Color.Red, Bod(vx: vx, vy: vy, moves: true)))
81
+ FRoseTree.leaf(Actor.rect(id, x, y, 20.0, 20.0, Color.Red, Bod(vx: vx, vy: vy, moves: true)))
82
82
 
83
83
  # What the workloads change besides the stage: the live ids, the random numbers, the next
84
84
  # id to give out.
@@ -89,23 +89,23 @@ fun bench(n: Int) -> Bench = Bench(live: Slice[Int](), rng: Rng(s: 12345), nextI
89
89
  # The scene, built bottom up as master builds it: each group's children first, then the
90
90
  # groups under the root. Ids: the root 0, the groups 1 to 10, the leaves from 11.
91
91
  fun build(n: Int, sc: Bench) -> EStage[Bod] =
92
- kids := Slice[Slice[ETree[Actor[Bod]]]]()
92
+ kids := Slice[Slice[FRoseTree[Actor[Bod]]]]()
93
93
  for g := range 10
94
- kids.push(Slice[ETree[Actor[Bod]]]())
94
+ kids.push(Slice[FRoseTree[Actor[Bod]]]())
95
95
  for i := range n - 11
96
96
  kids.at(i % 10).push(newLeaf(sc.rng, 11 + i))
97
97
  sc.live.push(11 + i)
98
- groups := Slice[ETree[Actor[Bod]]]()
98
+ groups := Slice[FRoseTree[Actor[Bod]]]()
99
99
  for g := range 10
100
100
  gb := group(g + 1, Float(100 + 300 * {g % 5}), Float(100 + 300 * {g / 5}), 1.0 + 0.05 * Float(g), 0.1 * Float(g))
101
- empty: ETree[Actor[Bod]] := EEmpty
101
+ empty: FRoseTree[Actor[Bod]] := FRoseEmpty
102
- groups.push(ENode(value: gb, firstChild: etree.etreeChainFrom(kids.at(g), 0), nextSibling: empty))
102
+ groups.push(FRoseNode(value: gb, firstChild: estage.echainFrom(kids.at(g), 0), nextSibling: empty))
103
- empty: ETree[Actor[Bod]] := EEmpty
103
+ empty: FRoseTree[Actor[Bod]] := FRoseEmpty
104
- root := ENode(value: group(0, 0.0, 0.0, 1.0, 0.0), firstChild: etree.etreeChainFrom(groups, 0), nextSibling: empty)
104
+ root := FRoseNode(value: group(0, 0.0, 0.0, 1.0, 0.0), firstChild: estage.echainFrom(groups, 0), nextSibling: empty)
105
105
  EStage(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
106
106
 
107
107
  # Every node's position, in preorder, folded into one number.
108
- fun hashTree(t: ETree[Actor[Bod]], h: Int) -> Int =
108
+ fun hashTree(t: FRoseTree[Actor[Bod]], h: Int) -> Int =
109
109
  t.fold(h, |r0, b|
110
110
  r := {r0 * 31 + Int(b.x * 1000.0)} % 1000000007
111
111
  {r * 31 + Int(b.y * 1000.0)} % 1000000007
@@ -171,21 +171,21 @@ fun churnsKept(stage: EStage[Bod], sc: Bench, ctx: ECtx[Bod], dt: Float, k: Int,
171
171
 
172
172
  # EStage's walk with no commands and the root's context for every body: no parent's world
173
173
  # transform is computed.
174
- fun stepFlat(t: ETree[Actor[Bod]], ctx: ECtx[Bod], dt: Float) -> ETree[Actor[Bod]] = match t
174
+ fun stepFlat(t: FRoseTree[Actor[Bod]], ctx: ECtx[Bod], dt: Float) -> FRoseTree[Actor[Bod]] = match t
175
- EEmpty => t
175
+ FRoseEmpty => t
176
- ENode(b, k, n) =>
176
+ FRoseNode(b, k, n) =>
177
177
  nb := b.kind.step(b, ctx, dt)
178
178
  if nb.dead
179
179
  stepFlat(n, ctx, dt)
180
180
  else
181
181
  k2 := if k.isEmpty() then k else stepFlat(k, ctx, dt)
182
- ENode(value: nb, firstChild: k2, nextSibling: stepFlat(n, ctx, dt))
182
+ FRoseNode(value: nb, firstChild: k2, nextSibling: stepFlat(n, ctx, dt))
183
183
 
184
184
  # EStage's walk with no commands, every body's world transform computed (and checked, so
185
185
  # it is used).
186
- fun stepEager(t: ETree[Actor[Bod]], ctx: ECtx[Bod], dt: Float) -> ETree[Actor[Bod]] = match t
186
+ fun stepEager(t: FRoseTree[Actor[Bod]], ctx: ECtx[Bod], dt: Float) -> FRoseTree[Actor[Bod]] = match t
187
- EEmpty => t
187
+ FRoseEmpty => t
188
- ENode(b, k, n) =>
188
+ FRoseNode(b, k, n) =>
189
189
  m := ctx.worldOf(b.local())
190
190
  assert m.e > -1.0e30
191
191
  cc := ctx.under(b.local(), b.opacity())
@@ -194,7 +194,7 @@ fun stepEager(t: ETree[Actor[Bod]], ctx: ECtx[Bod], dt: Float) -> ETree[Actor[Bo
194
194
  stepEager(n, ctx, dt)
195
195
  else
196
196
  k2 := if k.isEmpty() then k else stepEager(k, cc, dt)
197
- ENode(value: nb, firstChild: k2, nextSibling: stepEager(n, ctx, dt))
197
+ FRoseNode(value: nb, firstChild: k2, nextSibling: stepEager(n, ctx, dt))
198
198
 
199
199
  fun walks(stage: EStage[Bod], ctx: ECtx[Bod], dt: Float, t: Int, eager: Bool) -> EStage[Bod] =
200
200
  if t == 0
docs/benchmarks/2026-11-08-scene-trees-branch.md CHANGED
@@ -10,7 +10,7 @@ The question: the branch has in-place updates for values only one place holds (F
10
10
 
11
11
  `std/game_enum_tree` on this branch is master's, in the branch's language (no `return`, `while` or local reassignment, no inheritance):
12
12
 
13
- - **`ETree[T]`**: the same enum, `| EEmpty | ENode(value, firstChild, nextSibling)`, left child and right sibling, with the same operations (`fold`, `map`, `filter`, `append`, `appendAll`, `addChild`, `replace`, `update`, `find`, ...) and the same tests. Every walk is a recursion over the chain: `fold`, `each` and `find` are tail calls along the siblings, while the rebuilding walks recurse once per sibling, so a chain's length is bounded by the stack. The tests go up to 10,000 siblings, against master's 100,000.
13
+ - **`ETree[T]`** (since moved to std/collections/functional/FRoseTree.plum as `FRoseTree[T]`, with the variants `FRoseEmpty` and `FRoseNode`; the names below are the ones measured): the same enum, `| EEmpty | ENode(value, firstChild, nextSibling)`, left child and right sibling, with the same operations (`fold`, `map`, `filter`, `append`, `appendAll`, `addChild`, `replace`, `update`, `find`, ...) and the same tests. Every walk is a recursion over the chain: `fold`, `each` and `find` are tail calls along the siblings, while the rebuilding walks recurse once per sibling, so a chain's length is bounded by the stack. The tests go up to 10,000 siblings, against master's 100,000.
14
14
  - **`EBody`**: master's fields and copy helpers (`at`, `moveBy`, `killed`, ...). Master's subtypes (`EGroup`, `ERect`, a game's `Walker`) can't exist without inheritance, so **`EStage[T]` is generic over the body type**: any type with `key`, `gone`, `shown`, `local`, `opacity`, `hit`, `step(ctx, dt)` and `paint` will do. The tests use an enum of kinds, each holding an `EBody`. The benchmark uses one flat struct with master's `Leaf` fields plus a `moves` flag, so a moving leaf is one allocation, as on master.
15
15
  - **`ECtx[T]`** is a value: the parent's world transform and alpha, plus the command list (`out`). A body asks for its own transform with `ctx.worldOf(self.local())`. The walk makes one context per parent that has children (one multiply), from the body as the step reached it, and hands it to every child. That is master's lazy context without the cache field, and without the `retarget` mutation master uses to reuse one context. Master's `actions` dispatcher is left out, since the branch's game library has none.
16
16
  - **`EStage[T]`**: `step` applies the commands pushed before it in its own walk (killed bodies dropped unstepped, spawns on top of their parent, unstepped), then `apply`s those pushed during it. It uses the same bitsets for kill and spawn ids below 2^22, with the `Set` and `Map` for the rest. `apply`, `flatten`, `hit`, `draw`, `add`, `update`, `kill` and `find` work as on master, and the tests are master's.
docs/std.md CHANGED
@@ -120,6 +120,7 @@ Only true tail calls run in constant stack; other recursion overflows at a few t
120
120
  - **`FFenwickTree`:** 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.
121
121
  - **`FQuadtree`, `FKdTree`, `FBvh`:** spatial trees over `Vec2` and `Aabb`. Leaf buckets and query results are cons lists. Balanced builds sort with a merge sort on `List` (`FKdTree`) or pick medians with a quickselect (`FBvh`).
122
122
  - **`FUnionFind`:** a persistent parent map (two `FAvlTree`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.
123
+ - **`FRoseTree`:** a tree with any number of children per node, in left-child, right-sibling form (`FRoseEmpty`, `FRoseNode(value, firstChild, nextSibling)`). `FRoseTree.leaf(v)` and `FRoseTree.of(v, kids)` build nodes, `FRoseTree.chainOf(ns)` links a `List` of them as siblings. A value is a node with its later siblings; `fold`, `each`, `find`, `toList` and `chain` are tail calls along the siblings, while `map`, `filter`, `append` and `replace` recurse once per sibling. `filter`, `replace` and `update` return untouched subtrees as they were. std/game_enum_tree's stage is an `FRoseTree[Actor[K]]`.
123
124
  - **`FLeftistHeap`, `FPairingHeap`:** 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.
124
125
 
125
126
  ## Option and Result
examples/games/orb_run_tree.plum CHANGED
@@ -49,7 +49,7 @@ import std/game/audio
49
49
  import std/game/Anim
50
50
  import std/game/ui
51
51
  import std/game/input
52
- import std/game_enum_tree/ETree
52
+ import std/collections/functional/FRoseTree
53
53
  import std/game_enum_tree/Actor
54
54
  import std/game_enum_tree/ECtx
55
55
  import std/game_enum_tree/EStage
@@ -369,28 +369,28 @@ fun buttonLook(u: UiState) -> Int =
369
369
 
370
370
  # --- building the tree ---
371
371
 
372
- fun box(a: Actor[Kind]) -> ETree[Actor[Kind]] = etree.leaf(a)
372
+ fun box(a: Actor[Kind]) -> FRoseTree[Actor[Kind]] = FRoseTree.leaf(a)
373
373
 
374
- fun group(id: Int, kids: List[ETree[Actor[Kind]]]) -> ETree[Actor[Kind]] = etree.of(Actor.group(id, 0.0, 0.0, Box), kids)
374
+ fun group(id: Int, kids: List[FRoseTree[Actor[Kind]]]) -> FRoseTree[Actor[Kind]] = FRoseTree.of(Actor.group(id, 0.0, 0.0, Box), kids)
375
375
 
376
- fun label(id: Int, text: Str, x: Float, y: Float, size: Float, c: Color) -> ETree[Actor[Kind]] =
376
+ fun label(id: Int, text: Str, x: Float, y: Float, size: Float, c: Color) -> FRoseTree[Actor[Kind]] =
377
- etree.leaf(Actor.group(id, x, y, Label(text: text, size: size)).tint(c))
377
+ FRoseTree.leaf(Actor.group(id, x, y, Label(text: text, size: size)).tint(c))
378
378
 
379
379
  # Stars `i` and up to `StarCount`, each at its fixed spot.
380
- fun starNodes(i: Int) -> List[ETree[Actor[Kind]]] =
380
+ fun starNodes(i: Int) -> List[FRoseTree[Actor[Kind]]] =
381
381
  if i >= StarCount
382
382
  Nil
383
383
  else
384
384
  star := Actor.group(StarId + i, Float({i * 7919} % 800), Float({i * 104729} % 600), Star(i: i, clock: 0.0))
385
- Cons(head: etree.leaf(star), tail: starNodes(i + 1))
385
+ Cons(head: FRoseTree.leaf(star), tail: starNodes(i + 1))
386
386
 
387
387
  # Life icons `i` and up to `StartLives`, from the right edge going left.
388
- fun lifeNodes(i: Int, sheet: Texture) -> List[ETree[Actor[Kind]]] =
388
+ fun lifeNodes(i: Int, sheet: Texture) -> List[FRoseTree[Actor[Kind]]] =
389
389
  if i >= StartLives
390
390
  Nil
391
391
  else
392
392
  icon := Actor.group(LifeId + i, ArenaW - 40.0 - Float(i) * 36.0, 12.0, Icon(size: 32.0, col: 0, row: 0, sheet: sheet))
393
- Cons(head: etree.leaf(icon), tail: lifeNodes(i + 1, sheet))
393
+ Cons(head: FRoseTree.leaf(icon), tail: lifeNodes(i + 1, sheet))
394
394
 
395
395
  fun shipActor(x: Float, y: Float, sheet: Texture) -> Actor[Kind] =
396
396
  Actor.group(ShipId, x, y, Ship(vx: 0.0, vy: 0.0, ax: 0.0, ay: 0.0, hurt: 0.0, hurtAge: 0.0, clock: 0.0, sheet: sheet))
@@ -400,17 +400,17 @@ fun buildStage(sheet: Texture, sw: Float, sh: Float) -> EStage[Kind] =
400
400
  hud := group(HudId, Cons(
401
401
  head: label(ScoreId, "Score 0", 16.0, 12.0, 28.0, Color.White),
402
402
  tail: Cons(head: label(BestId, "Best 0", 16.0, 44.0, 20.0, Color.Yellow), tail: lifeNodes(0, sheet))))
403
- panel := etree.of(Actor.group(PanelId, 0.0, 0.0, Panel(age: 0.0)).withVisible(false), [
403
+ panel := FRoseTree.of(Actor.group(PanelId, 0.0, 0.0, Panel(age: 0.0)).withVisible(false), [
404
404
  box(Actor.rect(DimId, 0.0, 230.0, ArenaW, 170.0, Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6), Box)),
405
- etree.leaf(Actor.group(TitleId, 400.0, 268.0, Title(age: 0.0)).tint(Color.Red)),
405
+ FRoseTree.leaf(Actor.group(TitleId, 400.0, 268.0, Title(age: 0.0)).tint(Color.Red)),
406
406
  label(PromptId, "Press Enter to play again", 270.0, 300.0, 24.0, Color.White),
407
- etree.leaf(Actor.rect(RestartId, 340.0, 342.0, 120.0, 44.0, Color.White, Button(label: "Again", look: 0)))])
407
+ FRoseTree.leaf(Actor.rect(RestartId, 340.0, 342.0, 120.0, 44.0, Color.White, Button(label: "Again", look: 0)))])
408
- root := etree.of(fitted(Actor.group(RootId, 0.0, 0.0, Box), sw, sh), [
408
+ root := FRoseTree.of(fitted(Actor.group(RootId, 0.0, 0.0, Box), sw, sh), [
409
409
  box(Actor.rect(BackId, 0.0, 0.0, ArenaW, ArenaH, Color.rgb(0.07, 0.08, 0.16), Box)),
410
410
  group(StarLayer, starNodes(0)),
411
411
  group(MineLayer, Nil),
412
412
  group(OrbLayer, Nil),
413
- etree.leaf(shipActor(ArenaW / 2.0, ArenaH / 2.0, sheet)),
413
+ FRoseTree.leaf(shipActor(ArenaW / 2.0, ArenaH / 2.0, sheet)),
414
414
  hud,
415
415
  panel])
416
416
  EStage(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
@@ -512,7 +512,7 @@ struct State(
512
512
  sh := self.ship()
513
513
  sp := spawn(self.rng, sh.x, sh.y, 120.0, 40.0)
514
514
  orb := Actor.group(OrbId + i, sp.at.x, sp.at.y, Orb(vx: sp.at.vx, vy: sp.at.vy, phase: Float(i) * 0.1, clock: 0.0, sheet: self.sheet))
515
- State(..self, stage: self.stage.add(OrbLayer, etree.leaf(orb)), rng: sp.rng)
515
+ State(..self, stage: self.stage.add(OrbLayer, FRoseTree.leaf(orb)), rng: sp.rng)
516
516
 
517
517
  # Mines are added (on top of the others) until there are as many as the score asks for.
518
518
  fun growMines(self) -> State =
@@ -522,7 +522,7 @@ struct State(
522
522
  sh := self.ship()
523
523
  sp := spawn(self.rng, sh.x, sh.y, 220.0, 90.0)
524
524
  mine := Actor.group(MineId + self.mines, sp.at.x, sp.at.y, Mine(vx: sp.at.vx, vy: sp.at.vy, spin: 2.0, clock: 0.0, sheet: self.sheet))
525
- State(..self, stage: self.stage.add(MineLayer, etree.leaf(mine)), rng: sp.rng, mines: self.mines + 1)
525
+ State(..self, stage: self.stage.add(MineLayer, FRoseTree.leaf(mine)), rng: sp.rng, mines: self.mines + 1)
526
526
 
527
527
  fun touchesMine(self) -> Bool =
528
528
  self.bodiesWhere(|k| k.isMine()).fold(false, |hit, m| hit || self.touches(m, MineRadius))
std/collections/functional/FRoseTree.plum ADDED
@@ -0,0 +1,310 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Bool
5
+ import std/Str
6
+ import std/Option
7
+ import std/List
8
+
9
+ # A rose tree written functionally (see std/collections/functional/FAvlTree for the
10
+ # rules of the folder): a persistent tree in which a node has any number of children,
11
+ # kept in left-child, right-sibling form. A node holds its value, its first child and
12
+ # its next sibling, so any number of children needs only two links per node. Every
13
+ # operation returns a new tree, and the old one stays valid while something still holds
14
+ # it: keeping last tick's root is a snapshot. When nothing else holds the old tree, the
15
+ # compiler's in-place reuse (FBIP) writes the new nodes into the old ones' cells instead
16
+ # of allocating; `--no-fbip` turns that off.
17
+ #
18
+ # leaf := FRoseTree.leaf(3)
19
+ # t := FRoseTree.of(1, [FRoseTree.leaf(2), leaf]) # 1 with the children 2 and 3
20
+ # t2 := t.addChild(FRoseTree.leaf(4)) # 1 with 2, 3 and 4; `t` still has 2 and 3
21
+ #
22
+ # A value of `FRoseTree[T]` is a node together with its later siblings (a chain). A root
23
+ # has none, so a whole tree is a chain of one. The methods below work on the whole chain:
24
+ # `t.fold` folds the node, its subtree and then its later siblings and theirs, in
25
+ # preorder; `t.append(n)` puts `n` at the end of the chain. `addChild` works on the node
26
+ # itself (the first of the chain), and keeps its siblings.
27
+ #
28
+ # Every walk is a recursion over the chain. Walks that rebuild a chain (`map`, `filter`,
29
+ # `append`) recurse once per sibling, so a chain's length is bounded by the stack (tens
30
+ # of thousands of nodes); `fold`, `each`, `find`, `toList` and `chain` are tail calls on
31
+ # the siblings and run in constant stack along a chain.
32
+ #
33
+ # Siblings are kept in order: the first child comes first in every walk (std/game_enum_tree
34
+ # draws it first and hits it last). Appending a child copies the link nodes of its earlier
35
+ # siblings (their values and subtrees are shared), O(children); `appendAll` adds a batch
36
+ # for the cost of one.
37
+ #
38
+ # Nodes are referred to by what is in them (std/game_enum_tree's `Actor` has an `id`), not
39
+ # by the node itself: after an update the old node is a different, older value.
40
+ enum FRoseTree[T] =
41
+ | FRoseEmpty
42
+ | FRoseNode(value: T, firstChild: FRoseTree[T], nextSibling: FRoseTree[T])
43
+
44
+ # A node with no children.
45
+ fun leaf(v: T) -> FRoseTree[T] =
46
+ empty: FRoseTree[T] := FRoseEmpty
47
+ FRoseNode(value: v, firstChild: empty, nextSibling: empty)
48
+
49
+ # A node with the children `kids` (each with its subtree, not its siblings), in order.
50
+ fun of(v: T, kids: List[FRoseTree[T]]) -> FRoseTree[T] =
51
+ empty: FRoseTree[T] := FRoseEmpty
52
+ FRoseNode(value: v, firstChild: FRoseTree.chainOf(kids), nextSibling: empty)
53
+
54
+ # The nodes of `ns` (each with its subtree, not its siblings) linked into one chain, in
55
+ # order.
56
+ fun chainOf(ns: List[FRoseTree[T]]) -> FRoseTree[T] = match ns
57
+ Nil => FRoseEmpty
58
+ Cons(h, t) => match h
59
+ FRoseEmpty => FRoseTree.chainOf(t)
60
+ FRoseNode(v, k, _) => FRoseNode(value: v, firstChild: k, nextSibling: FRoseTree.chainOf(t))
61
+
62
+ fun isEmpty(self) -> Bool = match self
63
+ FRoseEmpty => true
64
+ FRoseNode(_, _, _) => false
65
+
66
+ # The first node's value, None for an empty tree.
67
+ fun top(self) -> Option[T] = match self
68
+ FRoseEmpty => None
69
+ FRoseNode(v, _, _) => Some(v)
70
+
71
+ # The first node's children (a chain), empty for an empty tree.
72
+ fun kids(self) -> FRoseTree[T] = match self
73
+ FRoseEmpty => self
74
+ FRoseNode(_, k, _) => k
75
+
76
+ # The siblings after the first node (a chain), empty for an empty tree.
77
+ fun rest(self) -> FRoseTree[T] = match self
78
+ FRoseEmpty => self
79
+ FRoseNode(_, _, n) => n
80
+
81
+ # The nodes of this chain, first to last, each still linked to its later siblings.
82
+ fun chain(self) -> List[FRoseTree[T]] =
83
+ nil: List[FRoseTree[T]] := Nil
84
+ self.chainOnto(nil).reverse()
85
+
86
+ # The nodes of this chain pushed onto `acc`, last on top.
87
+ fun chainOnto(self, acc: List[FRoseTree[T]]) -> List[FRoseTree[T]] = match self
88
+ FRoseEmpty => acc
89
+ FRoseNode(_, _, n) => n.chainOnto(Cons(head: self, tail: acc))
90
+
91
+ # The number of nodes in the chain and all their subtrees.
92
+ fun count(self) -> Int = self.fold(0, |a, v| a + 1)
93
+
94
+ # `f` over every value in preorder: a node, then its subtree, then its later siblings.
95
+ fun fold[A](self, acc: A, f: fn(A, T) -> A) -> A = match self
96
+ FRoseEmpty => acc
97
+ FRoseNode(v, k, n) => n.fold(k.fold(f(acc, v), f), f)
98
+
99
+ # Calls `f` on every value in preorder.
100
+ fun each(self, f: fn(T) -> Unit) =
101
+ if FRoseNode(v, k, n) := self
102
+ f(v)
103
+ k.each(f)
104
+ n.each(f)
105
+
106
+ # The values in preorder.
107
+ fun toList(self) -> List[T] =
108
+ nil: List[T] := Nil
109
+ self.fold(nil, |acc, v| Cons(head: v, tail: acc)).reverse()
110
+
111
+ # The same shape with `f` applied to every value, called in preorder.
112
+ fun map[B](self, f: fn(T) -> B) -> FRoseTree[B] = match self
113
+ FRoseEmpty => FRoseEmpty
114
+ FRoseNode(v, k, n) =>
115
+ v2 := f(v)
116
+ k2 := k.map(f)
117
+ FRoseNode(value: v2, firstChild: k2, nextSibling: n.map(f))
118
+
119
+ # The tree without the nodes whose value fails `keep`; a dropped node takes its subtree
120
+ # with it. A chain in which nothing was dropped, at any depth, is returned as it was (the
121
+ # same value), so untouched subtrees are shared.
122
+ fun filter(self, keep: fn(T) -> Bool) -> FRoseTree[T] = match self
123
+ FRoseEmpty => self
124
+ FRoseNode(v, k, n) =>
125
+ if keep(v)
126
+ k2 := k.filter(keep)
127
+ n2 := n.filter(keep)
128
+ if k2 == k && n2 == n then self else FRoseNode(value: v, firstChild: k2, nextSibling: n2)
129
+ else
130
+ n.filter(keep)
131
+
132
+ # The chain with the node `n` (and its subtree, not its siblings) added at the end.
133
+ fun append(self, n: FRoseTree[T]) -> FRoseTree[T] = self.concat(n.alone())
134
+
135
+ # The chain with the nodes of `ns` (each with its subtree, not its siblings) added at the
136
+ # end, in order. The chain's own link nodes are copied once; values and subtrees are
137
+ # shared.
138
+ fun appendAll(self, ns: List[FRoseTree[T]]) -> FRoseTree[T] = self.concat(FRoseTree.chainOf(ns))
139
+
140
+ # This chain followed by the chain `tail`: the link nodes of this one are copied, `tail`
141
+ # is shared.
142
+ fun concat(self, tail: FRoseTree[T]) -> FRoseTree[T] = match self
143
+ FRoseEmpty => tail
144
+ FRoseNode(v, k, n) => FRoseNode(value: v, firstChild: k, nextSibling: n.concat(tail))
145
+
146
+ # The first node without its later siblings (empty for an empty tree).
147
+ fun alone(self) -> FRoseTree[T] = match self
148
+ FRoseEmpty => self
149
+ FRoseNode(v, k, n) => if n.isEmpty() then self else FRoseNode(value: v, firstChild: k, nextSibling: FRoseEmpty)
150
+
151
+ # The first node with `c` added as its last child. Its later siblings are kept. An
152
+ # empty tree stays empty.
153
+ fun addChild(self, c: FRoseTree[T]) -> FRoseTree[T] = match self
154
+ FRoseEmpty => self
155
+ FRoseNode(v, k, n) => FRoseNode(value: v, firstChild: k.append(c), nextSibling: n)
156
+
157
+ # The first node with the nodes of `cs` added as its last children, in order.
158
+ fun addChildren(self, cs: List[FRoseTree[T]]) -> FRoseTree[T] = match self
159
+ FRoseEmpty => self
160
+ FRoseNode(v, k, n) => FRoseNode(value: v, firstChild: k.appendAll(cs), nextSibling: n)
161
+
162
+ # The first node with its value replaced by `v`; children and siblings are kept.
163
+ fun withValue(self, v: T) -> FRoseTree[T] = match self
164
+ FRoseEmpty => self
165
+ FRoseNode(_, k, n) => FRoseNode(value: v, firstChild: k, nextSibling: n)
166
+
167
+ # The tree with the first node, in preorder, whose value passes `pick` replaced by
168
+ # `f(node)`, where `node` is that node with its children and without its siblings; the
169
+ # result's own siblings are ignored and the original ones kept. Everything off the path
170
+ # to that node is shared: the node's later siblings, the subtrees of its earlier ones
171
+ # (only their link nodes are copied) and of its ancestors' siblings alike. With no
172
+ # match, the tree itself is returned.
173
+ fun replace(self, pick: fn(T) -> Bool, f: fn(FRoseTree[T]) -> FRoseTree[T]) -> FRoseTree[T] = match self
174
+ FRoseEmpty => self
175
+ FRoseNode(v, k, n) =>
176
+ if pick(v)
177
+ match f(self.alone())
178
+ FRoseEmpty => n
179
+ FRoseNode(v2, k2, _) => FRoseNode(value: v2, firstChild: k2, nextSibling: n)
180
+ else
181
+ k2 := k.replace(pick, f)
182
+ if k2 != k
183
+ FRoseNode(value: v, firstChild: k2, nextSibling: n)
184
+ else
185
+ n2 := n.replace(pick, f)
186
+ if n2 == n then self else FRoseNode(value: v, firstChild: k, nextSibling: n2)
187
+
188
+ # The tree with the value of the first node, in preorder, that passes `pick` replaced by
189
+ # `f(value)`. As `replace`, it shares everything off the path.
190
+ fun update(self, pick: fn(T) -> Bool, f: fn(T) -> T) -> FRoseTree[T] =
191
+ self.replace(pick, |x| x.withValue(f(x.top().unwrap())))
192
+
193
+ # The first value in preorder that passes `pick`.
194
+ fun find(self, pick: fn(T) -> Bool) -> Option[T] = match self
195
+ FRoseEmpty => None
196
+ FRoseNode(v, k, n) =>
197
+ if pick(v)
198
+ Some(v)
199
+ else
200
+ match k.find(pick)
201
+ Some(x) => Some(x)
202
+ None => n.find(pick)
203
+
204
+ # ---------------------------------------------------------------------------
205
+ # Test helpers. Tests may use loops, `mut` fields and std's mutable types; the
206
+ # structure above may not.
207
+ # ---------------------------------------------------------------------------
208
+
209
+ fun fRoseSample() -> FRoseTree[Int] =
210
+ # 1
211
+ # 2 5
212
+ # 3 4 6
213
+ FRoseTree.of(1, [
214
+ FRoseTree.of(2, [FRoseTree.leaf(3), FRoseTree.leaf(4)]),
215
+ FRoseTree.of(5, [FRoseTree.leaf(6)])])
216
+
217
+ # The tree as text: `1(2(3 4) 5(6))`.
218
+ fun fRoseShow(t: FRoseTree[Int]) -> Str = match t
219
+ FRoseEmpty => ""
220
+ FRoseNode(v, k, n) =>
221
+ me := if k.isEmpty() then "{v}" else "{v}({fRoseShow(k)})"
222
+ if n.isEmpty() then me else "{me} {fRoseShow(n)}"
223
+
224
+ # Leaves 0 to `i` - 1 in front of `acc`.
225
+ fun fRoseLeaves(i: Int, acc: List[FRoseTree[Int]]) -> List[FRoseTree[Int]] =
226
+ if i <= 0 then acc else fRoseLeaves(i - 1, Cons(head: FRoseTree.leaf(i - 1), tail: acc))
227
+
228
+ test "fold and toList visit a node, its subtree, then its later siblings"
229
+ t := fRoseSample()
230
+ assert t.fold("", |a, v| "{a}{v}") == "123456"
231
+ assert t.toList().toStr() == "[1,2,3,4,5,6]"
232
+ assert t.count() == 6
233
+ assert fRoseShow(t) == "1(2(3 4) 5(6))"
234
+ e: FRoseTree[Int] := FRoseEmpty
235
+ assert e.count() == 0
236
+ assert e.top().isNone()
237
+ assert t.kids().chain().length() == 2
238
+
239
+ test "map keeps the shape and calls f in preorder"
240
+ t := fRoseSample().map(|v| v * 10)
241
+ assert fRoseShow(t) == "10(20(30 40) 50(60))"
242
+ s := fRoseSample().map(|v| "<{v}>")
243
+ assert s.fold("", |a, v| "{a}{v}") == "<1><2><3><4><5><6>"
244
+
245
+ test "filter drops a node with its subtree and shares what it didn't touch"
246
+ t := fRoseSample()
247
+ f := t.filter(|v| v != 2)
248
+ assert fRoseShow(f) == "1(5(6))"
249
+ assert fRoseShow(t) == "1(2(3 4) 5(6))"
250
+ assert fRoseShow(t.filter(|v| v != 4)) == "1(2(3) 5(6))"
251
+ assert t.filter(|v| true) == t
252
+ g := t.filter(|v| v != 3)
253
+ assert g.kids().rest() == t.kids().rest()
254
+
255
+ test "append and addChild keep sibling order, and the old tree is unchanged"
256
+ t := FRoseTree.of(1, [FRoseTree.leaf(2)])
257
+ t2 := t.addChild(FRoseTree.leaf(3))
258
+ t3 := t2.addChild(FRoseTree.of(4, [FRoseTree.leaf(5)]))
259
+ assert fRoseShow(t) == "1(2)"
260
+ assert fRoseShow(t2) == "1(2 3)"
261
+ assert fRoseShow(t3) == "1(2 3 4(5))"
262
+ assert fRoseShow(FRoseTree.leaf(1).append(FRoseTree.leaf(2)).append(FRoseTree.leaf(3))) == "1 2 3"
263
+ e: FRoseTree[Int] := FRoseEmpty
264
+ assert fRoseShow(e.append(FRoseTree.leaf(7))) == "7"
265
+ assert fRoseShow(FRoseTree.leaf(1).addChildren([FRoseTree.leaf(2), FRoseTree.leaf(3), FRoseTree.leaf(4)])) == "1(2 3 4)"
266
+ # a node's own siblings don't come along
267
+ assert fRoseShow(FRoseTree.leaf(1).addChild(FRoseTree.leaf(8).append(FRoseTree.leaf(9)))) == "1(8)"
268
+
269
+ test "update changes one node and shares the untouched siblings and subtrees"
270
+ t := fRoseSample()
271
+ u := t.update(|v| v == 3, |v| v + 100)
272
+ assert fRoseShow(u) == "1(2(103 4) 5(6))"
273
+ assert fRoseShow(t) == "1(2(3 4) 5(6))"
274
+ # the later sibling of 3 and the later sibling of 2 are the same values, not copies
275
+ assert u.kids().kids().rest() == t.kids().kids().rest()
276
+ assert u.kids().rest() == t.kids().rest()
277
+ # an earlier sibling's link is new, but its subtree is shared
278
+ w := t.update(|v| v == 5, |v| 50)
279
+ assert fRoseShow(w) == "1(2(3 4) 50(6))"
280
+ assert w.kids() != t.kids()
281
+ assert w.kids().kids() == t.kids().kids()
282
+ assert w.kids().rest().kids() == t.kids().rest().kids()
283
+ # no match: the tree itself
284
+ assert t.update(|v| v == 99, |v| 0) == t
285
+
286
+ test "replace swaps a whole node and keeps its siblings"
287
+ t := fRoseSample()
288
+ r := t.replace(|v| v == 2, |n| n.addChild(FRoseTree.leaf(7)))
289
+ assert fRoseShow(r) == "1(2(3 4 7) 5(6))"
290
+ assert r.kids().rest() == t.kids().rest()
291
+ assert fRoseShow(t.replace(|v| v == 2, |n| FRoseTree.leaf(9))) == "1(9 5(6))"
292
+ e: FRoseTree[Int] := FRoseEmpty
293
+ assert fRoseShow(t.replace(|v| v == 5, |n| e)) == "1(2(3 4))"
294
+
295
+ test "find returns the first value in preorder"
296
+ t := fRoseSample()
297
+ assert t.find(|v| v > 2).unwrap() == 3
298
+ assert t.find(|v| v > 4).unwrap() == 5
299
+ assert t.find(|v| v > 6).isNone()
300
+
301
+ test "a sibling chain of 10,000 nodes"
302
+ nil: List[FRoseTree[Int]] := Nil
303
+ t := FRoseTree.of(-1, fRoseLeaves(10000, nil))
304
+ assert t.count() == 10001
305
+ assert t.fold(0, |a, v| a + v) == 49995000 - 1
306
+ assert t.kids().chain().length() == 10000
307
+ assert t.toList().length() == 10001
308
+ u := t.update(|v| v == 9999, |v| 0)
309
+ assert u.fold(0, |a, v| a + v) == 49995000 - 1 - 9999
310
+ assert t.filter(|v| v < 0 || v % 2 == 0).count() == 5001
std/game_enum_tree/Actor.plum CHANGED
@@ -10,7 +10,7 @@ import std/game/Affine
10
10
  import std/game/Color
11
11
  import std/game/gfx
12
12
 
13
- # One body of a persistent scene tree (`ETree[Actor[K]]` in an `EStage[K]`): what every
13
+ # One body of a persistent scene tree (`FRoseTree[Actor[K]]` in an `EStage[K]`): what every
14
14
  # body has, its id, its place in its parent (position, size, origin, scale, rotation), its
15
15
  # colour and its two flags, plus `kind: K`, the game's own payload. The stage does
16
16
  # everything these fields describe by itself: it finds bodies by `id`, drops a `dead` one
std/game_enum_tree/EBox.plum CHANGED
@@ -14,7 +14,7 @@ import std/game_enum_tree/ECtx
14
14
  # rectangle in its colour and is hit inside it; one without (a group) paints nothing and is
15
15
  # never hit. A scene with no behaviour is an `EStage[EBox]`:
16
16
  #
17
- # s := EStage.of(EBox.group(0, 0.0, 0.0)).add(0, etree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
17
+ # s := EStage.of(EBox.group(0, 0.0, 0.0)).add(0, FRoseTree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
18
18
  struct EBox() =
19
19
 
20
20
  # A group of plain actors at (x, y).
std/game_enum_tree/ECtx.plum CHANGED
@@ -4,14 +4,14 @@ import std/Int
4
4
  import std/Float
5
5
  import std/Slice
6
6
  import std/game/Affine
7
- import std/game_enum_tree/ETree
7
+ import std/collections/functional/FRoseTree
8
8
  import std/game_enum_tree/Actor
9
9
 
10
10
  # What a step changes besides the actors, applied once the step's walk is over
11
11
  # (`EStage.apply`): a new node under the actor `parent` (by id), on top of its children,
12
12
  # or the end of the actor `id` and its subtree. `K` is the stage's kind.
13
13
  enum ECmd[K] =
14
- | ESpawn(parent: Int, node: ETree[Actor[K]])
14
+ | ESpawn(parent: Int, node: FRoseTree[Actor[K]])
15
15
  | EKill(id: Int)
16
16
 
17
17
  # What the step hands each actor's kind in place of a parent link: the context of the
@@ -22,7 +22,7 @@ enum ECmd[K] =
22
22
  #
23
23
  # fun step(self, a: Actor[Kind], ctx: ECtx[Kind], dt: Float) -> Actor[Kind] = match self
24
24
  # Gun(rate) =>
25
- # ctx.out.push(ESpawn(parent: 0, node: etree.leaf(Actor.group(id, a.x, a.y, Bullet))))
25
+ # ctx.out.push(ESpawn(parent: 0, node: FRoseTree.leaf(Actor.group(id, a.x, a.y, Bullet))))
26
26
  # a
27
27
  # ..
28
28
  #
std/game_enum_tree/EStage.plum CHANGED
@@ -16,19 +16,19 @@ import std/game/Vec2
16
16
  import std/game/Affine
17
17
  import std/game/Color
18
18
  import std/game/gfx
19
- import std/game_enum_tree/ETree
19
+ import std/collections/functional/FRoseTree
20
20
  import std/game_enum_tree/Actor
21
21
  import std/game_enum_tree/EBox
22
22
  import std/game_enum_tree/ECtx
23
23
 
24
24
  # A persistent scene tree: master's std/game_enum_tree `EStage`, over actors of the kind
25
- # `K` (see std/game_enum_tree/Actor). The root is an `ETree[Actor[K]]`, a left-child,
25
+ # `K` (see std/game_enum_tree/Actor). The root is an `FRoseTree[Actor[K]]`, a left-child,
26
26
  # right-sibling tree of actors, and a stage is a value: every change returns a new stage.
27
27
  # While something holds the old stage it stays as it was, a snapshot; when nothing does,
28
28
  # the compiler reuses its cells for the new one.
29
29
  #
30
30
  # s := EStage.of(EBox.group(0, 0.0, 0.0)) # a root group, id 0
31
- # s2 := s.add(0, etree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
31
+ # s2 := s.add(0, FRoseTree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
32
32
  # ctx := ECtx[EBox]()
33
33
  # s3 := s2.step(ctx, dt) # every actor's next version, then the commands in ctx.out
34
34
  # s3.draw(io)
@@ -50,14 +50,14 @@ import std/game_enum_tree/ECtx
50
50
  # and that use would stop the compiler from writing the new node into the old one's cell.
51
51
  # A step over a stage nothing else holds therefore allocates no link nodes at all, and
52
52
  # one over a kept stage copies all of them.
53
- struct EStage[K](root: ETree[Actor[K]], camX: Float, camY: Float, camScale: Float) =
53
+ struct EStage[K](root: FRoseTree[Actor[K]], camX: Float, camY: Float, camScale: Float) =
54
54
 
55
55
  # A stage whose root is the actor `top`.
56
56
  fun of(top: Actor[K]) -> EStage[K] =
57
- EStage(root: etree.leaf(top), camX: 0.0, camY: 0.0, camScale: 1.0)
57
+ EStage(root: FRoseTree.leaf(top), camX: 0.0, camY: 0.0, camScale: 1.0)
58
58
 
59
59
  # The same camera over another tree.
60
- fun withRoot(self, r: ETree[Actor[K]]) -> EStage[K] = EStage(..self, root: r)
60
+ fun withRoot(self, r: FRoseTree[Actor[K]]) -> EStage[K] = EStage(..self, root: r)
61
61
 
62
62
  fun pan(self, x: Float, y: Float) -> EStage[K] = EStage(..self, camX: x, camY: y)
63
63
 
@@ -71,7 +71,7 @@ struct EStage[K](root: ETree[Actor[K]], camX: Float, camY: Float, camScale: Floa
71
71
 
72
72
  # The stage with `n` added as the last child of the actor `parent`; unchanged if there
73
73
  # is no such actor.
74
- fun add(self, parent: Int, n: ETree[Actor[K]]) -> EStage[K] =
74
+ fun add(self, parent: Int, n: FRoseTree[Actor[K]]) -> EStage[K] =
75
75
  self.withRoot(self.root.replace(|a| a.id == parent, |p| p.addChild(n)))
76
76
 
77
77
  # The stage with the actor `id` replaced by `f(actor)`; everything off its path is
@@ -97,7 +97,7 @@ struct EStage[K](root: ETree[Actor[K]], camX: Float, camY: Float, camScale: Floa
97
97
  fun step(self, ctx: ECtx[K], dt: Float) -> EStage[K] =
98
98
  w := EWalk.of(ctx.out)
99
99
  ctx.out.clear()
100
- empty: ETree[Actor[K]] := EEmpty
100
+ empty: FRoseTree[Actor[K]] := FRoseEmpty
101
101
  r := estep(self.root, ctx, dt, w, empty)
102
102
  s := EStage(..self, root: r).apply(ctx.out)
103
103
  ctx.out.clear()
@@ -112,7 +112,7 @@ struct EStage[K](root: ETree[Actor[K]], camX: Float, camY: Float, camScale: Floa
112
112
  self
113
113
  else
114
114
  w := EWalk.of(cmds)
115
- empty: ETree[Actor[K]] := EEmpty
115
+ empty: FRoseTree[Actor[K]] := FRoseEmpty
116
116
  EStage(..self, root: eapply(self.root, w, empty))
117
117
 
118
118
  # What `draw` would draw, in order: each shown actor with its stage transform and alpha,
@@ -154,13 +154,13 @@ struct EScan(mut top: Int, mut ok: Bool) =
154
154
  # answers are a shift and a mask, and only an actor with spawns does a hash lookup. Ids
155
155
  # below 0 or from 2^22 up make that batch use the set and the map alone.
156
156
  struct EWalk[K](
157
- kills: Set[Int], spawns: Map[Int, Slice[ETree[Actor[K]]]],
157
+ kills: Set[Int], spawns: Map[Int, Slice[FRoseTree[Actor[K]]]],
158
158
  hasKills: Bool, hasSpawns: Bool,
159
159
  bitsOk: Bool, killBits: Array[Int], spawnBits: Array[Int]) =
160
160
 
161
161
  fun of(cmds: Slice[ECmd[K]]) -> EWalk[K] =
162
162
  kills := Set[Int]()
163
- spawns: Map[Int, Slice[ETree[Actor[K]]]] := Map.empty()
163
+ spawns: Map[Int, Slice[FRoseTree[Actor[K]]]] := Map.empty()
164
164
  scan := EScan(top: 0, ok: true)
165
165
  for c := range cmds
166
166
  match c
@@ -172,7 +172,7 @@ struct EWalk[K](
172
172
  if Some(xs) := spawns.get(parent)
173
173
  xs.push(node)
174
174
  else
175
- ys := Slice[ETree[Actor[K]]]()
175
+ ys := Slice[FRoseTree[Actor[K]]]()
176
176
  ys.push(node)
177
177
  spawns.set(parent, ys)
178
178
  words := if scan.ok && cmds.length() > 0 then scan.top / 64 + 1 else 0
@@ -198,13 +198,23 @@ struct EWalk[K](
198
198
  self.kills.has(id)
199
199
 
200
200
  # The nodes to add under the actor `id`, as a chain in the order pushed (empty if none).
201
- fun spawnsUnder(self, id: Int) -> ETree[Actor[K]] =
201
+ fun spawnsUnder(self, id: Int) -> FRoseTree[Actor[K]] =
202
202
  if !self.hasSpawns || {self.bitsOk && !ewalkHas(self.spawnBits, id)}
203
- EEmpty
203
+ FRoseEmpty
204
204
  else
205
205
  match self.spawns.get(id)
206
- Some(xs) => etree.etreeChainFrom(xs, 0)
206
+ Some(xs) => echainFrom(xs, 0)
207
- None => EEmpty
207
+ None => FRoseEmpty
208
+
209
+ # The nodes of `ns` from index `i` on (each with its subtree, not its siblings), linked
210
+ # into one chain, in order: `FRoseTree.chainOf` for a `Slice`.
211
+ fun echainFrom[T](ns: Slice[FRoseTree[T]], i: Int) -> FRoseTree[T] =
212
+ if i >= ns.length()
213
+ FRoseEmpty
214
+ else
215
+ match ns.at(i)
216
+ FRoseEmpty => echainFrom(ns, i + 1)
217
+ FRoseNode(v, k, _) => FRoseNode(value: v, firstChild: k, nextSibling: echainFrom(ns, i + 1))
208
218
 
209
219
  fun ewalkSet(bits: Array[Int], id: Int) =
210
220
  w := id / 64
@@ -218,13 +228,13 @@ fun ewalkHas(bits: Array[Int], id: Int) -> Bool =
218
228
  # actors `w` kills, and followed by `extra` (the parent's spawns, unstepped). An actor with
219
229
  # children (or spawns) gets one context for them, made from its transform before its
220
230
  # step. Every kept node is rebuilt: in place when nothing else holds `t`.
221
- fun estep[K](t: ETree[Actor[K]], ctx: ECtx[K], dt: Float, w: EWalk[K], extra: ETree[Actor[K]]) -> ETree[Actor[K]] = match t
231
+ fun estep[K](t: FRoseTree[Actor[K]], ctx: ECtx[K], dt: Float, w: EWalk[K], extra: FRoseTree[Actor[K]]) -> FRoseTree[Actor[K]] = match t
222
- EEmpty => extra
232
+ FRoseEmpty => extra
223
- ENode(a, k, n) =>
233
+ FRoseNode(a, k, n) =>
224
234
  if a.dead || {w.hasKills && w.killed(a.id)}
225
235
  estep(n, ctx, dt, w, extra)
226
236
  else
227
- xs := if w.hasSpawns then w.spawnsUnder(a.id) else EEmpty
237
+ xs := if w.hasSpawns then w.spawnsUnder(a.id) else FRoseEmpty
228
238
  walkKids := !k.isEmpty() || !xs.isEmpty()
229
239
  cc := if walkKids then ctx.under(a.local(), a.opacity()) else ctx
230
240
  na := a.kind.step(a, ctx, dt)
@@ -232,22 +242,22 @@ fun estep[K](t: ETree[Actor[K]], ctx: ECtx[K], dt: Float, w: EWalk[K], extra: ET
232
242
  estep(n, ctx, dt, w, extra)
233
243
  else
234
244
  k2 := if walkKids then estep(k, cc, dt, w, xs) else k
235
- ENode(value: na, firstChild: k2, nextSibling: estep(n, ctx, dt, w, extra))
245
+ FRoseNode(value: na, firstChild: k2, nextSibling: estep(n, ctx, dt, w, extra))
236
246
 
237
247
  # The chain `t` without the actors `w` kills and followed by `extra`, with the same done
238
248
  # in every subtree: `apply`'s walk.
239
- fun eapply[K](t: ETree[Actor[K]], w: EWalk[K], extra: ETree[Actor[K]]) -> ETree[Actor[K]] = match t
249
+ fun eapply[K](t: FRoseTree[Actor[K]], w: EWalk[K], extra: FRoseTree[Actor[K]]) -> FRoseTree[Actor[K]] = match t
240
- EEmpty => extra
250
+ FRoseEmpty => extra
241
- ENode(a, k, n) =>
251
+ FRoseNode(a, k, n) =>
242
252
  if w.killed(a.id)
243
253
  eapply(n, w, extra)
244
254
  else
245
255
  xs := w.spawnsUnder(a.id)
246
256
  k2 := if k.isEmpty() && xs.isEmpty() then k else eapply(k, w, xs)
247
- ENode(value: a, firstChild: k2, nextSibling: eapply(n, w, extra))
257
+ FRoseNode(value: a, firstChild: k2, nextSibling: eapply(n, w, extra))
248
258
 
249
- fun ecollect[K](t: ETree[Actor[K]], parent: Affine, alpha: Float, out: Slice[EDrawn[K]]) =
259
+ fun ecollect[K](t: FRoseTree[Actor[K]], parent: Affine, alpha: Float, out: Slice[EDrawn[K]]) =
250
- if ENode(a, k, n) := t
260
+ if FRoseNode(a, k, n) := t
251
261
  if a.shown()
252
262
  m := parent.mul(a.local())
253
263
  al := alpha * a.opacity()
@@ -255,8 +265,8 @@ fun ecollect[K](t: ETree[Actor[K]], parent: Affine, alpha: Float, out: Slice[EDr
255
265
  ecollect(k, m, al, out)
256
266
  ecollect(n, parent, alpha, out)
257
267
 
258
- fun edraw[K](t: ETree[Actor[K]], io: Io, parent: Affine, alpha: Float) =
268
+ fun edraw[K](t: FRoseTree[Actor[K]], io: Io, parent: Affine, alpha: Float) =
259
- if ENode(a, k, n) := t
269
+ if FRoseNode(a, k, n) := t
260
270
  if a.shown()
261
271
  m := parent.mul(a.local())
262
272
  al := alpha * a.opacity()
@@ -266,9 +276,9 @@ fun edraw[K](t: ETree[Actor[K]], io: Io, parent: Affine, alpha: Float) =
266
276
 
267
277
  # The topmost shown actor under `p` (a point in the chain's parent's coordinates) that its
268
278
  # kind says is hit: later siblings first, and in each, its children before itself.
269
- fun ehit[K](t: ETree[Actor[K]], p: Vec2) -> Option[Actor[K]] = match t
279
+ fun ehit[K](t: FRoseTree[Actor[K]], p: Vec2) -> Option[Actor[K]] = match t
270
- EEmpty => None
280
+ FRoseEmpty => None
271
- ENode(a, k, n) =>
281
+ FRoseNode(a, k, n) =>
272
282
  match ehit(n, p)
273
283
  Some(found) => Some(found)
274
284
  None =>
@@ -313,12 +323,12 @@ enum TKind =
313
323
 
314
324
  fun hit(self, a: Actor[TKind], p: Vec2) -> Bool = a.hitBox(p)
315
325
 
316
- fun tdrifter(id: Int, x: Float, vx: Float, ttl: Int) -> ETree[Actor[TKind]] =
326
+ fun tdrifter(id: Int, x: Float, vx: Float, ttl: Int) -> FRoseTree[Actor[TKind]] =
317
- etree.leaf(Actor.rect(id, x, 0.0, 10.0, 10.0, Color.White, TDrifter(vx: vx, ttl: ttl)))
327
+ FRoseTree.leaf(Actor.rect(id, x, 0.0, 10.0, 10.0, Color.White, TDrifter(vx: vx, ttl: ttl)))
318
328
 
319
- fun tspawner(id: Int, next: Int) -> ETree[Actor[TKind]] = etree.leaf(Actor.group(id, 0.0, 0.0, TSpawner(next: next)))
329
+ fun tspawner(id: Int, next: Int) -> FRoseTree[Actor[TKind]] = FRoseTree.leaf(Actor.group(id, 0.0, 0.0, TSpawner(next: next)))
320
330
 
321
- fun tkiller(id: Int, target: Int) -> ETree[Actor[TKind]] = etree.leaf(Actor.group(id, 0.0, 0.0, TKiller(target: target)))
331
+ fun tkiller(id: Int, target: Int) -> FRoseTree[Actor[TKind]] = FRoseTree.leaf(Actor.group(id, 0.0, 0.0, TKiller(target: target)))
322
332
 
323
333
  fun tprobe(id: Int, x: Float, y: Float, r: Float) -> Actor[TKind] =
324
334
  Actor(
@@ -326,12 +336,12 @@ fun tprobe(id: Int, x: Float, y: Float, r: Float) -> Actor[TKind] =
326
336
  scaleX: 0.5, scaleY: 3.0, rotation: r, color: Color.White.withAlpha(0.5), visible: true, dead: false,
327
337
  kind: TProbe(seen: Affine.Identity, seenA: 0.0))
328
338
 
329
- fun trect(id: Int, x: Float, y: Float, w: Float) -> ETree[Actor[TKind]] = etree.leaf(Actor.rect(id, x, y, w, w, Color.Red, TPlain))
339
+ fun trect(id: Int, x: Float, y: Float, w: Float) -> FRoseTree[Actor[TKind]] = FRoseTree.leaf(Actor.rect(id, x, y, w, w, Color.Red, TPlain))
330
340
 
331
341
  fun tturned(id: Int, x: Float, y: Float, s: Float, r: Float) -> Actor[TKind] = Actor.turned(id, x, y, s, r, TPlain)
332
342
 
333
- fun tgroup(id: Int, x: Float, y: Float, s: Float, r: Float, kids: List[ETree[Actor[TKind]]]) -> ETree[Actor[TKind]] =
343
+ fun tgroup(id: Int, x: Float, y: Float, s: Float, r: Float, kids: List[FRoseTree[Actor[TKind]]]) -> FRoseTree[Actor[TKind]] =
334
- etree.of(tturned(id, x, y, s, r), kids)
344
+ FRoseTree.of(tturned(id, x, y, s, r), kids)
335
345
 
336
346
  fun tstage() -> EStage[TKind] = EStage.of(Actor.group(0, 0.0, 0.0, TPlain))
337
347
 
@@ -458,7 +468,7 @@ test "an actor's world transform is computed when it asks, and matches the eager
458
468
  hb := tturned(2, -20.0, 5.0, 1.5, -1.1).pivotAt(3.0, 4.0)
459
469
  p := tprobe(3, 7.0, -2.0, 2.5)
460
470
  q := tprobe(4, 1.0, 1.0, 0.0)
461
- s := tstage().add(0, etree.of(gb, [etree.of(hb, [etree.leaf(p), etree.leaf(q)])]))
471
+ s := tstage().add(0, FRoseTree.of(gb, [FRoseTree.of(hb, [FRoseTree.leaf(p), FRoseTree.leaf(q)])]))
462
472
  s1 := s.step(ECtx[TKind](), 1.0)
463
473
  assert tsameM(tseen(s1, 3), gb.local().mul(hb.local()).mul(p.local()))
464
474
  assert tnear(tseenA(s1, 3), 0.5)
@@ -470,7 +480,7 @@ test "siblings with children each give their children their own world transform"
470
480
  g2 := tturned(2, -40.0, 5.0, 0.5, -1.2)
471
481
  p1 := tprobe(3, 7.0, -2.0, 2.5)
472
482
  p2 := tprobe(4, 1.0, 9.0, 0.3)
473
- s := tstage().add(0, etree.of(g1, [etree.leaf(p1)])).add(0, etree.of(g2, [etree.leaf(p2)]))
483
+ s := tstage().add(0, FRoseTree.of(g1, [FRoseTree.leaf(p1)])).add(0, FRoseTree.of(g2, [FRoseTree.leaf(p2)]))
474
484
  s1 := s.step(ECtx[TKind](), 1.0)
475
485
  assert tsameM(tseen(s1, 3), g1.local().mul(p1.local()))
476
486
  assert tsameM(tseen(s1, 4), g2.local().mul(p2.local()))
@@ -558,7 +568,7 @@ test "the bitsets cover ids up to 2^22 - 1, and the set and map take the ids pas
558
568
  assert tids(s3.step(ctx, 1.0)) == "0,{big},{big + 1},9"
559
569
 
560
570
  test "a plain EBox stage: add, step, draw list"
561
- s := EStage.of(EBox.group(0, 0.0, 0.0)).add(0, etree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
571
+ s := EStage.of(EBox.group(0, 0.0, 0.0)).add(0, FRoseTree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
562
572
  s1 := s.step(ECtx[EBox](), 1.0)
563
573
  assert s1.count() == 2
564
574
  assert s1.flatten().at(1).m.e == 10.0
std/game_enum_tree/ETree.plum DELETED
@@ -1,317 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Bool
5
- import std/Str
6
- import std/Option
7
- import std/List
8
- import std/Slice
9
-
10
- # A persistent tree in left-child, right-sibling form: a node holds its value, its first
11
- # child and its next sibling, so any number of children needs only two links per node.
12
- # Every operation returns a new tree, and the old one stays valid while something still
13
- # holds it: keeping last tick's root is a snapshot. When nothing else holds the old tree,
14
- # the compiler's in-place reuse (FBIP) writes the new nodes into the old ones' cells
15
- # instead of allocating; `--no-fbip` turns that off.
16
- #
17
- # leaf := etree.leaf(3)
18
- # t := etree.of(1, [etree.leaf(2), leaf]) # 1 with the children 2 and 3
19
- # t2 := t.addChild(etree.leaf(4)) # 1 with 2, 3 and 4; `t` still has 2 and 3
20
- #
21
- # A value of `ETree[T]` is a node together with its later siblings (a chain). A root has
22
- # none, so a whole tree is a chain of one. The methods below work on the whole chain:
23
- # `t.fold` folds the node, its subtree and then its later siblings and theirs, in
24
- # preorder; `t.append(n)` puts `n` at the end of the chain. `addChild` works on the node
25
- # itself (the first of the chain), and keeps its siblings.
26
- #
27
- # This is master's std/game_enum_tree/ETree written without loops, `return` or local
28
- # reassignment: every walk is a recursion over the chain. Walks that rebuild a chain
29
- # (`map`, `filter`, `append`) recurse once per sibling, so a chain's length is bounded by
30
- # the stack (tens of thousands of nodes); `fold`, `each` and `find` are tail calls on the
31
- # siblings and run in constant stack along a chain.
32
- #
33
- # Siblings are kept in draw order: the first child is drawn first and hit last. Appending
34
- # a child copies the link nodes of its earlier siblings (their values and subtrees are
35
- # shared), O(children); `appendAll` adds a batch for the cost of one.
36
- #
37
- # Nodes are referred to by what is in them (std/game_enum_tree's `EBody` has an `id`), not
38
- # by the node itself: after an update the old node is a different, older value.
39
- enum ETree[T] =
40
- | EEmpty
41
- | ENode(value: T, firstChild: ETree[T], nextSibling: ETree[T])
42
-
43
- fun isEmpty(self) -> Bool = match self
44
- EEmpty => true
45
- ENode(_, _, _) => false
46
-
47
- # The first node's value, None for an empty tree.
48
- fun top(self) -> Option[T] = match self
49
- EEmpty => None
50
- ENode(v, _, _) => Some(v)
51
-
52
- # The first node's children (a chain), empty for an empty tree.
53
- fun kids(self) -> ETree[T] = match self
54
- EEmpty => self
55
- ENode(_, k, _) => k
56
-
57
- # The siblings after the first node (a chain), empty for an empty tree.
58
- fun rest(self) -> ETree[T] = match self
59
- EEmpty => self
60
- ENode(_, _, n) => n
61
-
62
- # The nodes of this chain, first to last, each still linked to its later siblings.
63
- fun chain(self) -> Slice[ETree[T]] =
64
- out := Slice[ETree[T]]()
65
- self.chainInto(out)
66
- out
67
-
68
- fun chainInto(self, out: Slice[ETree[T]]) =
69
- if ENode(_, _, n) := self
70
- out.push(self)
71
- n.chainInto(out)
72
-
73
- # The number of nodes in the chain and all their subtrees.
74
- fun count(self) -> Int = self.fold(0, |a, v| a + 1)
75
-
76
- # `f` over every value in preorder: a node, then its subtree, then its later siblings.
77
- fun fold[A](self, acc: A, f: fn(A, T) -> A) -> A = match self
78
- EEmpty => acc
79
- ENode(v, k, n) => n.fold(k.fold(f(acc, v), f), f)
80
-
81
- # Calls `f` on every value in preorder.
82
- fun each(self, f: fn(T) -> Unit) =
83
- if ENode(v, k, n) := self
84
- f(v)
85
- k.each(f)
86
- n.each(f)
87
-
88
- # The values in preorder.
89
- fun toSlice(self) -> Slice[T] =
90
- out := Slice[T]()
91
- self.pushInto(out)
92
- out
93
-
94
- fun pushInto(self, out: Slice[T]) =
95
- if ENode(v, k, n) := self
96
- out.push(v)
97
- k.pushInto(out)
98
- n.pushInto(out)
99
-
100
- # The same shape with `f` applied to every value, called in preorder.
101
- fun map[B](self, f: fn(T) -> B) -> ETree[B] = match self
102
- EEmpty => EEmpty
103
- ENode(v, k, n) =>
104
- v2 := f(v)
105
- k2 := k.map(f)
106
- ENode(value: v2, firstChild: k2, nextSibling: n.map(f))
107
-
108
- # The tree without the nodes whose value fails `keep`; a dropped node takes its subtree
109
- # with it. A chain in which nothing was dropped, at any depth, is returned as it was (the
110
- # same value), so untouched subtrees are shared.
111
- fun filter(self, keep: fn(T) -> Bool) -> ETree[T] = match self
112
- EEmpty => self
113
- ENode(v, k, n) =>
114
- if keep(v)
115
- k2 := k.filter(keep)
116
- n2 := n.filter(keep)
117
- if k2 == k && n2 == n then self else ENode(value: v, firstChild: k2, nextSibling: n2)
118
- else
119
- n.filter(keep)
120
-
121
- # The chain with the node `n` (and its subtree, not its siblings) added at the end.
122
- fun append(self, n: ETree[T]) -> ETree[T] = self.concat(n.alone())
123
-
124
- # The chain with the nodes of `ns` (each with its subtree, not its siblings) added at the
125
- # end, in order. The chain's own link nodes are copied once; values and subtrees are
126
- # shared.
127
- fun appendAll(self, ns: List[ETree[T]]) -> ETree[T] = self.concat(etreeChainOf(ns))
128
-
129
- # This chain followed by the chain `tail`: the link nodes of this one are copied, `tail`
130
- # is shared.
131
- fun concat(self, tail: ETree[T]) -> ETree[T] = match self
132
- EEmpty => tail
133
- ENode(v, k, n) => ENode(value: v, firstChild: k, nextSibling: n.concat(tail))
134
-
135
- # The first node without its later siblings (empty for an empty tree).
136
- fun alone(self) -> ETree[T] = match self
137
- EEmpty => self
138
- ENode(v, k, n) => if n.isEmpty() then self else ENode(value: v, firstChild: k, nextSibling: EEmpty)
139
-
140
- # The first node with `c` added as its last child (drawn on top of its siblings). Its
141
- # later siblings are kept. An empty tree stays empty.
142
- fun addChild(self, c: ETree[T]) -> ETree[T] = match self
143
- EEmpty => self
144
- ENode(v, k, n) => ENode(value: v, firstChild: k.append(c), nextSibling: n)
145
-
146
- # The first node with the nodes of `cs` added as its last children, in order.
147
- fun addChildren(self, cs: List[ETree[T]]) -> ETree[T] = match self
148
- EEmpty => self
149
- ENode(v, k, n) => ENode(value: v, firstChild: k.appendAll(cs), nextSibling: n)
150
-
151
- # The first node with its value replaced by `v`; children and siblings are kept.
152
- fun withValue(self, v: T) -> ETree[T] = match self
153
- EEmpty => self
154
- ENode(_, k, n) => ENode(value: v, firstChild: k, nextSibling: n)
155
-
156
- # The tree with the first node, in preorder, whose value passes `pick` replaced by
157
- # `f(node)`, where `node` is that node with its children and without its siblings; the
158
- # result's own siblings are ignored and the original ones kept. Everything off the path
159
- # to that node is shared: the node's later siblings, the subtrees of its earlier ones
160
- # (only their link nodes are copied) and of its ancestors' siblings alike. With no
161
- # match, the tree itself is returned.
162
- fun replace(self, pick: fn(T) -> Bool, f: fn(ETree[T]) -> ETree[T]) -> ETree[T] = match self
163
- EEmpty => self
164
- ENode(v, k, n) =>
165
- if pick(v)
166
- match f(self.alone())
167
- EEmpty => n
168
- ENode(v2, k2, _) => ENode(value: v2, firstChild: k2, nextSibling: n)
169
- else
170
- k2 := k.replace(pick, f)
171
- if k2 != k
172
- ENode(value: v, firstChild: k2, nextSibling: n)
173
- else
174
- n2 := n.replace(pick, f)
175
- if n2 == n then self else ENode(value: v, firstChild: k, nextSibling: n2)
176
-
177
- # The tree with the value of the first node, in preorder, that passes `pick` replaced by
178
- # `f(value)`. As `replace`, it shares everything off the path.
179
- fun update(self, pick: fn(T) -> Bool, f: fn(T) -> T) -> ETree[T] =
180
- self.replace(pick, |x| x.withValue(f(x.top().unwrap())))
181
-
182
- # The first value in preorder that passes `pick`.
183
- fun find(self, pick: fn(T) -> Bool) -> Option[T] = match self
184
- EEmpty => None
185
- ENode(v, k, n) =>
186
- if pick(v)
187
- Some(v)
188
- else
189
- match k.find(pick)
190
- Some(x) => Some(x)
191
- None => n.find(pick)
192
-
193
- # A node with no children.
194
- fun leaf[T](v: T) -> ETree[T] =
195
- empty: ETree[T] := EEmpty
196
- ENode(value: v, firstChild: empty, nextSibling: empty)
197
-
198
- # A node with the children `kids` (each with its subtree, not its siblings), in order.
199
- fun of[T](v: T, kids: List[ETree[T]]) -> ETree[T] =
200
- empty: ETree[T] := EEmpty
201
- ENode(value: v, firstChild: etreeChainOf(kids), nextSibling: empty)
202
-
203
- # The nodes of `ns` (each with its subtree, not its siblings) linked into one chain, in
204
- # order.
205
- fun etreeChainOf[T](ns: List[ETree[T]]) -> ETree[T] = match ns
206
- Nil => EEmpty
207
- Cons(h, t) => match h
208
- EEmpty => etreeChainOf(t)
209
- ENode(v, k, _) => ENode(value: v, firstChild: k, nextSibling: etreeChainOf(t))
210
-
211
- # The nodes of `ns` from index `i` on, linked into one chain, in order.
212
- fun etreeChainFrom[T](ns: Slice[ETree[T]], i: Int) -> ETree[T] =
213
- if i >= ns.length()
214
- EEmpty
215
- else
216
- match ns.at(i)
217
- EEmpty => etreeChainFrom(ns, i + 1)
218
- ENode(v, k, _) => ENode(value: v, firstChild: k, nextSibling: etreeChainFrom(ns, i + 1))
219
-
220
- # --- tests ---
221
-
222
- fun etreeSample() -> ETree[Int] =
223
- # 1
224
- # 2 5
225
- # 3 4 6
226
- of(1, [of(2, [leaf(3), leaf(4)]), of(5, [leaf(6)])])
227
-
228
- fun etreeShow(t: ETree[Int]) -> Str = match t
229
- EEmpty => ""
230
- ENode(v, k, n) =>
231
- me := if k.isEmpty() then "{v}" else "{v}({etreeShow(k)})"
232
- if n.isEmpty() then me else "{me} {etreeShow(n)}"
233
-
234
- test "fold and toSlice visit a node, its subtree, then its later siblings"
235
- t := etreeSample()
236
- assert t.fold("", |a, v| "{a}{v}") == "123456"
237
- assert t.toSlice().toStr() == "[1,2,3,4,5,6]"
238
- assert t.count() == 6
239
- assert etreeShow(t) == "1(2(3 4) 5(6))"
240
- e: ETree[Int] := EEmpty
241
- assert e.count() == 0
242
- assert e.top().isNone()
243
- assert t.kids().chain().length() == 2
244
-
245
- test "map keeps the shape and calls f in preorder"
246
- t := etreeSample().map(|v| v * 10)
247
- assert etreeShow(t) == "10(20(30 40) 50(60))"
248
- s := etreeSample().map(|v| "<{v}>")
249
- assert s.fold("", |a, v| "{a}{v}") == "<1><2><3><4><5><6>"
250
-
251
- test "filter drops a node with its subtree and shares what it didn't touch"
252
- t := etreeSample()
253
- f := t.filter(|v| v != 2)
254
- assert etreeShow(f) == "1(5(6))"
255
- assert etreeShow(t) == "1(2(3 4) 5(6))"
256
- assert etreeShow(t.filter(|v| v != 4)) == "1(2(3) 5(6))"
257
- assert t.filter(|v| true) == t
258
- g := t.filter(|v| v != 3)
259
- assert g.kids().rest() == t.kids().rest()
260
-
261
- test "append and addChild keep draw order, and the old tree is unchanged"
262
- t := of(1, [leaf(2)])
263
- t2 := t.addChild(leaf(3))
264
- t3 := t2.addChild(of(4, [leaf(5)]))
265
- assert etreeShow(t) == "1(2)"
266
- assert etreeShow(t2) == "1(2 3)"
267
- assert etreeShow(t3) == "1(2 3 4(5))"
268
- assert etreeShow(leaf(1).append(leaf(2)).append(leaf(3))) == "1 2 3"
269
- e: ETree[Int] := EEmpty
270
- assert etreeShow(e.append(leaf(7))) == "7"
271
- assert etreeShow(leaf(1).addChildren([leaf(2), leaf(3), leaf(4)])) == "1(2 3 4)"
272
- # a node's own siblings don't come along
273
- assert etreeShow(leaf(1).addChild(leaf(8).append(leaf(9)))) == "1(8)"
274
-
275
- test "update changes one node and shares the untouched siblings and subtrees"
276
- t := etreeSample()
277
- u := t.update(|v| v == 3, |v| v + 100)
278
- assert etreeShow(u) == "1(2(103 4) 5(6))"
279
- assert etreeShow(t) == "1(2(3 4) 5(6))"
280
- # the later sibling of 3 and the later sibling of 2 are the same values, not copies
281
- assert u.kids().kids().rest() == t.kids().kids().rest()
282
- assert u.kids().rest() == t.kids().rest()
283
- # an earlier sibling's link is new, but its subtree is shared
284
- w := t.update(|v| v == 5, |v| 50)
285
- assert etreeShow(w) == "1(2(3 4) 50(6))"
286
- assert w.kids() != t.kids()
287
- assert w.kids().kids() == t.kids().kids()
288
- assert w.kids().rest().kids() == t.kids().rest().kids()
289
- # no match: the tree itself
290
- assert t.update(|v| v == 99, |v| 0) == t
291
-
292
- test "replace swaps a whole node and keeps its siblings"
293
- t := etreeSample()
294
- r := t.replace(|v| v == 2, |n| n.addChild(leaf(7)))
295
- assert etreeShow(r) == "1(2(3 4 7) 5(6))"
296
- assert r.kids().rest() == t.kids().rest()
297
- assert etreeShow(t.replace(|v| v == 2, |n| leaf(9))) == "1(9 5(6))"
298
- e: ETree[Int] := EEmpty
299
- assert etreeShow(t.replace(|v| v == 5, |n| e)) == "1(2(3 4))"
300
-
301
- test "find returns the first value in preorder"
302
- t := etreeSample()
303
- assert t.find(|v| v > 2).unwrap() == 3
304
- assert t.find(|v| v > 4).unwrap() == 5
305
- assert t.find(|v| v > 6).isNone()
306
-
307
- test "a sibling chain of 10,000 nodes"
308
- kids := Slice[ETree[Int]]()
309
- for i := range 10000
310
- kids.push(leaf(i))
311
- empty: ETree[Int] := EEmpty
312
- t := ENode(value: -1, firstChild: etreeChainFrom(kids, 0), nextSibling: empty)
313
- assert t.count() == 10001
314
- assert t.fold(0, |a, v| a + v) == 49995000 - 1
315
- u := t.update(|v| v == 9999, |v| 0)
316
- assert u.fold(0, |a, v| a + v) == 49995000 - 1 - 9999
317
- assert t.filter(|v| v < 0 || v % 2 == 0).count() == 5001