plum

#treesitter#compiler#wasm

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

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


ebc978a — Peter John 2026-11-10T12:21:39+05:30
std Map: a persistent weight-balanced tree (Data.Map), Set on top of it
benchmarks/map_snapshots/snapshots.plum ADDED
@@ -0,0 +1,37 @@
1
+ # Persistent use of `Map`: 100 rounds of 1,000 updates to a 100,000-entry map, keeping the
2
+ # map after every round, then reading every snapshot. Each snapshot shares all but the
3
+ # O(log n) nodes per update with the next one, so keeping all 100 costs about as much as
4
+ # the updates. (With the old mutable hash table each snapshot was a full copy.)
5
+ #
6
+ # plum build benchmarks/map_snapshots/snapshots.plum -o /tmp/snapshots && /tmp/snapshots
7
+ import std/Int
8
+ import std/Float
9
+ import std/Str
10
+ import std/Option
11
+ import std/Io
12
+ import std/List
13
+ import std/Map
14
+
15
+ fun fill(m: Map[Int, Int], i: Int, n: Int) -> Map[Int, Int] = if i >= n then m else fill(m.with(i, i), i + 1, n)
16
+
17
+ # Round `r`'s updates: 1,000 keys spread over the map, each set to `r`.
18
+ fun round(m: Map[Int, Int], r: Int, i: Int) -> Map[Int, Int] = if i >= 1000 then m else round(m.with({r * 7919 + i * 104729} % 100000, r), r, i + 1)
19
+
20
+ # The maps after each round, newest first.
21
+ fun rounds(m: Map[Int, Int], r: Int, acc: List[Map[Int, Int]]) -> List[Map[Int, Int]] =
22
+ if r > 100
23
+ acc
24
+ else
25
+ next := round(m, r, 0)
26
+ rounds(next, r + 1, Cons(head: next, tail: acc))
27
+
28
+ # A checksum of one snapshot: 1,000 lookups.
29
+ fun sample(m: Map[Int, Int], i: Int, acc: Int) -> Int = if i >= 1000 then acc else sample(m, i + 1, {acc * 31 + m.getOr(i * 97, -1)} % 1000000007)
30
+
31
+ fun main(io: Io) =
32
+ t0 := io.nowMicros()
33
+ snaps := rounds(fill(Map.empty(), 0, 100000), 1, Nil)
34
+ check := snaps.fold(0, |acc, m| {acc * 7 + sample(m, 0, 0)} % 1000000007)
35
+ t1 := io.nowMicros()
36
+ el := {t1 - t0} / 1000.0
37
+ io.printLn("ms {el} checksum {check} snapshots {snaps.length()}")
benchmarks/master_vs_simpler/branch/map.plum CHANGED
@@ -11,10 +11,11 @@ import std/math
11
11
 
12
12
  fun look(m: Map[Int, Int], i: Int, n: Int, acc: Int) -> Int = if i >= n then acc else look(m, i + 1, n, acc + m.get(i * 7919 % 1000003).unwrapOr(0) % 13)
13
13
 
14
+ # Each `with` gets the map the last one made and returns the next one.
15
+ fun fill(m: Map[Int, Int], i: Int, n: Int) -> Map[Int, Int] = if i >= n then m else fill(m.with(i * 7919 % 1000003, i), i + 1, n)
16
+
14
17
  fun once(n: Int) -> Int =
15
- m: Map[Int, Int] := Map.empty()
18
+ m := fill(Map.empty(), 0, n)
16
- for i := range n
17
- m.set(i * 7919 % 1000003, i)
18
19
  look(m, 0, n, 0) + m.length()
19
20
 
20
21
  fun reps(k: Int, acc: Int) -> Int = if k == 0 then acc else reps(k - 1, acc + once(200000))
compiler/core/tests/core/layout_test.rs CHANGED
@@ -88,13 +88,13 @@ fn std_and_examples_layouts() {
88
88
  let l = structLayout(e, &all);
89
89
  assert_eq!(l, plum_core::layout::itemLayout(e, &s.items), "{} in {}", e.name, f.display());
90
90
  if l == Layout::Flat { flat += 1 } else { boxed += 1 }
91
- if f.ends_with("std/game/Vec2.plum") || f.ends_with("std/Map.plum") {
91
+ if f.ends_with("std/game/Vec2.plum") || f.ends_with("std/Set.plum") {
92
92
  known.push((e.name.clone(), l));
93
93
  }
94
94
  }
95
95
  }
96
96
  assert!(flat > 20 && boxed > 100, "flat {flat}, boxed {boxed}");
97
- for (name, want) in [("Vec2", Layout::Flat), ("Map", Layout::Boxed), ("Str", Layout::Boxed), ("Slice", Layout::Boxed)] {
97
+ for (name, want) in [("Vec2", Layout::Flat), ("Set", Layout::Boxed), ("Str", Layout::Boxed), ("Slice", Layout::Boxed)] {
98
98
  assert!(known.iter().any(|(n, l)| n == name && *l == want), "{name} not {want:?}: {known:?}");
99
99
  }
100
100
  }
docs/language.md CHANGED
@@ -334,7 +334,7 @@ A good habit is one error enum per module. Use `?` and `mapErr` for failures you
334
334
  | `List[T]` | recursion and pattern matching | `[1, 2, 3]` |
335
335
  | `Slice[T]` | a growable array with fast indexing | `[1, 2, 3].toSlice()`, `Slice[Int]()` |
336
336
  | `Array[T]` | a fixed-size array | `Array.filled(10, 0)` |
337
- | `Map[K, V]` | key and value lookup | `["a" => 1, "b" => 2]` |
337
+ | `Map[K, V]` | key and value lookup, in key order | `["a" => 1, "b" => 2]`, `Map[Str, Int]()` |
338
338
 
339
339
  ```plum
340
340
  import std/Int
@@ -351,6 +351,8 @@ fun main() =
351
351
 
352
352
  A `List` is `Nil` or `Cons(head, tail)`, so you can match on it. Indexing a `List` is slow, so reach for a `Slice` when you need it.
353
353
 
354
+ A `Map` is persistent, like a `List`: `m.with(k, v)` and `m.remove(k)` return a new map that shares most of its nodes with `m`, and `m` stays as it was. A map literal `[k => v, ..]` is `Map.empty().with(k, v)...`, so a later duplicate key wins. Keys are kept in order by their `compare` method, which `Int`, `Float`, `Str`, `Bool` and `Byte` have and a struct can define, and every walk goes in key order. See [the standard library](std.md#collections).
355
+
354
356
  ## Loops
355
357
 
356
358
  `for x := range source` is the only `for`. Like `while`, it is for side effects: the body acts through a `mut` field or `io`, and it can't reassign a local from outside the loop.
@@ -373,7 +375,7 @@ fun main(io: Io) =
373
375
  total.n = total.n + i
374
376
  for x := range [1, 2, 3] # a List, Slice or Array
375
377
  total.n = total.n + x
376
- for e := range ["a" => 1].entries() # a Map: e.first and e.second
378
+ for e := range ["a" => 1] # a Map, in key order: e.first and e.second
377
379
  io.printLn("{e.first} is {e.second}")
378
380
  ```
379
381
 
docs/std.md CHANGED
@@ -34,16 +34,18 @@ fun main() =
34
34
  d := Int.parse("42").unwrapOr(0)
35
35
  ```
36
36
 
37
- - `Int`: `abs`, `sign`, `min`, `max`, `pow`, `toStr`, `Int.parse`, `Int.Min`, `Int.Max`, and on the 64-bit pattern `leadingZeros`, `trailingZeros`, `popCount` (64 for 0)
38
- - `Float`: `abs`, `sqrt`, `pow`, `floor`, `ceil`, `round`, `trunc`, `isNaN`, `toStr`, `Float.parse`, `Float.Pi`, `Float.Tau`, `Float.E`, and `toBits` / `Float.fromBits` between a Float and its 64 IEEE 754 bits as an Int
37
+ - `Int`: `abs`, `sign`, `min`, `max`, `pow`, `compare`, `toStr`, `Int.parse`, `Int.Min`, `Int.Max`, and on the 64-bit pattern `leadingZeros`, `trailingZeros`, `popCount` (64 for 0)
38
+ - `Float`: `abs`, `sqrt`, `pow`, `floor`, `ceil`, `round`, `trunc`, `isNaN`, `compare`, `toStr`, `Float.parse`, `Float.Pi`, `Float.Tau`, `Float.E`, and `toBits` / `Float.fromBits` between a Float and its 64 IEEE 754 bits as an Int
39
39
  - `math`: `math.sqrt`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2`, `exp`, `ln`, `hypot`, `cbrt`
40
40
 
41
41
  Where wasm has the operation, std uses its instruction, compiled in line at each call: `math.sqrt` and `Float.sqrt` are `f64.sqrt`, correctly rounded; `abs`, `floor`, `ceil` and `trunc` are `f64.abs`, `f64.floor`, `f64.ceil` and `f64.trunc`; `leadingZeros`, `trailingZeros` and `popCount` are `i64.clz`, `i64.ctz` and `i64.popcnt`; `x.toBits()` and `Float.fromBits(b)` are `i64.reinterpret_f64` and `f64.reinterpret_i64`, so a NaN keeps its payload and `{-0.0}.toBits()` is `Int.Min`. These are exact for every Float: NaN and the infinities pass through, a value past `Int`'s range comes back whole as it was, and a zero keeps its sign (`{-0.5}.floor()` is `-1.0`, `{-0.5}.ceil()` is `-0.0`, `{-0.0}.abs()` is `0.0`). `round` is half away from zero and exact too (`0.49999999999999994.round()` is `0.0`). `math.hypot(a, b)` is `sqrt(a * a + b * b)` unless that sum overflows or underflows, then it scales: `hypot(3e200, 4e200)` is about `5e200`, and an infinite side gives Infinity even next to a NaN. `min` and `max` stay comparisons: `x.min(y)` is `if x < y then x else y`, so with a NaN it returns `y`. `sin`, `cos`, `exp`, `ln` and the rest have no wasm instruction and are Plum code made of exact IEEE operations, so they give the same bits on every host. Their series are written out term by term (no loop), and `ln` reads the power of two of its argument from the exponent bits instead of halving or doubling it, as `exp` does for the scaling into [-0.5, 0.5]; `benchmarks/math_bits/check.plum` checks that these give the same bits as the loop versions did.
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` starts from a guess read from the bits (the exponent divided by 3) and is faithfully rounded, under 0.667 ulp, for every Float, subnormals and `1e300` included (`cbrt(1e300)` is `1e100`); it keeps the sign (`cbrt(-0.0)` is `-0.0`), and NaN and the infinities pass through. `math.atan` past 2^60 is `Pi/2 - atan(1/|x|)` with the sign of `x`, so `atan(1e300)` and `atan(Infinity)` are `Pi/2`. `sin(-0.0)`, `tan(-0.0)` and `atan(-0.0)` are `-0.0`. `math.atan2` gives NaN for a NaN on either side, and `±Pi/4` or `±3*Pi/4` when both sides are infinite.
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) no longer collide in a `Map`; `0.0` and `-0.0`, which are `==`, both hash to 0, and every NaN hashes the same.
46
- - `Bool`: `toStr`, `Bool.parse`
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 an `FHamt`; `0.0` and `-0.0`, which are `==`, both hash to 0, and every NaN hashes the same.
46
+
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
+ - `Bool`: `toStr`, `Bool.parse`, `compare`
47
49
 
48
50
  ## Text
49
51
 
@@ -61,6 +63,7 @@ fun main() =
61
63
  ```
62
64
 
63
65
  - **Search:** `contains`, `startsWith`, `endsWith`, `indexOf`
66
+ - **Order:** `compare(o)` and `<`, `<=`, `>`, `>=` compare byte by byte, which for UTF-8 is code point order, a prefix first (`"ab" < "b"`, `"a" < "ab"`)
64
67
  - **Cut:** `sub`, `slice`, `split(separator, limit)`, `trim`, `trimStart`, `trimEnd`, `truncate`. `trim` strips ASCII whitespace and Unicode's other White_Space characters (U+00A0, U+3000, U+2028, ...). `truncate(n)` cuts at a character boundary, never inside a multi-byte character.
65
68
  - **Change:** `replace`, `replaceAll`, `repeat`, `reverse`, `padStart`, `padEnd`
66
69
  - **Case:** `upperCase`, `lowerCase`, `capitalize`, `camelCase`, `snakeCase`, `kebabCase`
@@ -90,7 +93,7 @@ fun main() =
90
93
  - **Read:** `get`, `at`, `first`, `last`, `length`, `isEmpty`, `contains`, `findValue`. `at` crashes with the index and the length out of range (also on a view, and past a `pop`).
91
94
  - **Loop:** `fold`, `each`, `map`, `filter`, `find(pred)`, `any`, `all`, as on `List`
92
95
  - **Change:** `push`, `pop`, `set`, `add`, `remove`, `removeAt`, `clear`, `reverse`, `shuffle`
93
- - **Other:** `sort(before)` (a new slice; a stable merge sort, O(n log n)), `slice` (a view that shares storage), `sublist` (a copy), `chunk`, `join`, `drop`, and with `std/Map` imported `groupBy(key)` (a `Map` from each key to its elements, in order)
96
+ - **Other:** `sort(before)` (a new slice; a stable merge sort, O(n log n)), `slice` (a view that shares storage), `sublist` (a copy), `chunk`, `join`, `drop`, and with `std/Map` imported `groupBy(key)` (a `Map` from each key to its elements, in order; the groups come in key order)
94
97
 
95
98
  Renamed or removed: `Slice.head` (use `first`), `Set.toList` is now `toSlice`.
96
99
 
@@ -105,12 +108,28 @@ import std/Map
105
108
 
106
109
  fun main() =
107
110
  ages := ["ann" => 30, "bob" => 25]
108
- ages.set("cy", 40)
111
+ more := ages.with("cy", 40) # a new map; `ages` still has two entries
109
- ann := ages.get("ann").unwrapOr(0)
112
+ ann := more.get("ann").unwrapOr(0)
113
+ start: Map[Str, Int] := Map.empty()
114
+ counts := ["a", "b", "a"].fold(start, |m, w| m.upsert(w, 1, |n| n + 1))
110
115
  ```
111
116
 
112
- - **`Map`:** `get`, `set`, `has`, `remove`, `keys`, `values`, `entries`, `length`. `Map[Str, Int]()` makes an empty one, like `Slice[T]()` and `Set[T]()` (`m: Map[Str, Int] := Map.empty()` too). `with(k, v)` is what a map literal `[k => v]` is built with: it sets the key in the map itself and returns it, so it is `set` that chains, not a copy
113
- - **`Set`:** `add`, `has`, `remove`, `length`, `toSlice`
117
+ **`Map[K, V]`** is a persistent ordered map: a weight-balanced binary search tree, as in Haskell's `Data.Map`. It is an `enum` (`MapTip`, or `MapBin(size, key, value, left, right)`), and every node keeps its subtree's size, so neither side of a node holds more than 3 times as many entries as the other and the height stays below 2 log2(n) + 2.
118
+
119
+ - **Persistent.** Nothing changes in place. `m.with(k, v)` returns a new map that rebuilds the O(log n) nodes on the path to `k` and shares every other node with `m`, and `m` stays as it was, so keeping old versions is cheap (`benchmarks/map_snapshots`). An update is a value, so a loop that fills a map threads it: `fold`, a tail-recursive function, or a `mut` field (`state.m = state.m.with(k, v)`). A call whose result is dropped (`m.set(k, v)` as a statement) is an "unused result" error.
120
+ - **Ordered keys.** Keys are compared with their `compare(self, o) -> Int` method (negative before, 0 the same key, positive after). `Int`, `Float`, `Str`, `Bool` and `Byte` have one (see [Numbers](#numbers) for `Float`'s total order); a struct becomes a key by defining one. A key type without it is a compile error that names the type and the call that needed it: `Map.with[Pt, Int] (called at main.plum:8:8): Pt has no method 'compare'`. Keys need no `hash` any more.
121
+ - **Key order everywhere.** `for e := range m`, `keys`, `values`, `entries`, `fold`, `each`, `toStr` and `==` go in ascending key order, which depends only on the keys, never on the order they were added.
122
+ - **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).
123
+ - **Read, O(log n):** `get(k)` (an `Option`), `getOr(k, fallback)` (no `Option` made), `has(k)`; O(1): `length`, `isEmpty`.
124
+ - **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).
125
+ - **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
+ - **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`.
127
+ - **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.
128
+
129
+ 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.
130
+
131
+ **`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.
132
+
114
133
  - **`Deque`:** a queue you can use from both ends: `pushBack`, `pushFront`, `popBack`, `popFront`, `get`, `at` (crashes out of range)
115
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`
116
135
 
@@ -165,7 +184,7 @@ fun main() =
165
184
  p: Result[Point, JsonError] := Json.decode(text)
166
185
  ```
167
186
 
168
- The result's annotation tells `decode` which type to build. `Option` doesn't have JSON support yet, so write those conversions by hand.
187
+ The result's annotation tells `decode` which type to build. A JSON object is a `Map[Str, Json]`, so its fields come back, and are written, in key order; a later duplicate key wins. `Option` doesn't have JSON support yet, so write those conversions by hand.
169
188
 
170
189
  Numbers are `Float`s. Writing one gives the shortest digits that read back as the same Float, the way JavaScript writes them: `Json.encode(123)` is `123`, `0.1 + 0.2` is `0.30000000000000004`, `1e21` is `1e+21`, and NaN and the infinities are `null`. Reading one gives the Float nearest the number's exact value, so text written by any correct JSON library reads back exactly. A leading zero (`01`), a number past Float's range (`1e400`) and more than `MaxJsonDepth` (1000) nested arrays and objects are errors. Both directions are [`std/decimal`](../std/decimal.plum) (`decimal.parse(text)`, `decimal.format(x)`, `decimal.shortest(x)`), which `Float.parse` uses too: it takes an exponent (`2.5e-3`) and `Float.parse("0.3")` is `0.3`.
171
190
 
examples/errors.plum CHANGED
@@ -407,10 +407,11 @@ test "a Unit result propagates with question mark and is handled with if Err"
407
407
 
408
408
  test "a Map can hold results as values"
409
409
  m: Map[Int, Result[Int, Neg]] := Map.empty()
410
- m.set(1, negOrSeven(7))
410
+ a := m.with(1, negOrSeven(7))
411
- assert lookup(m) == 7
411
+ assert lookup(a) == 7
412
- m.set(1, negOrSeven(-2))
412
+ b := a.with(1, negOrSeven(-2))
413
- assert lookup(m) == 0
413
+ assert lookup(b) == 0
414
+ assert lookup(a) == 7
414
415
 
415
416
  # ==== Option tests ====
416
417
 
examples/games/game_loop.plum CHANGED
@@ -1,7 +1,7 @@
1
1
  # A tiny game update loop. Particles are structs in a `Slice`, which stores them
2
2
  # field by field (struct-of-arrays), so 100 frames of updates allocate nothing per
3
3
  # particle; dead ones are removed by swap-remove. Entities live in a `Map[Int,
4
- # Entity]` and are changed by events handled with `match`.
4
+ # Entity]`, and each event handled with `match` gives the next map (the old one is unchanged).
5
5
  module game_loop
6
6
  import std/Str
7
7
  import std/Int
@@ -57,13 +57,12 @@ fun run(frames: Int, ps: Slice[Particle]) -> Stats =
57
57
  Stats(spawned: spawned, removed: stats.removed + step(ps, 0.5))
58
58
  )
59
59
 
60
- fun handle(world: Map[Int, Entity], e: Event) =
60
+ fun handle(world: Map[Int, Entity], e: Event) -> Map[Int, Entity] =
61
61
  match e
62
62
  Spawn(id, name) =>
63
- world.set(id, Entity(id: id, name: name, hp: 100))
63
+ world.with(id, Entity(id: id, name: name, hp: 100))
64
64
  Damage(id, amount) =>
65
- if Some(ent) := world.get(id)
66
- ent.hp = ent.hp - amount
65
+ world.update(id, |ent| Entity(..ent, hp: ent.hp - amount))
67
66
  Despawn(id) =>
68
67
  world.remove(id)
69
68
 
@@ -84,13 +83,12 @@ test "survivors have moved and aged the expected amount"
84
83
  assert life == 20
85
84
 
86
85
  test "events change the entity map"
87
- world: Map[Int, Entity] := Map.empty()
86
+ start: Map[Int, Entity] := Map.empty()
88
- handle(world, Spawn(id: 1, name: "orc"))
89
- handle(world, Spawn(id: 2, name: "elf"))
87
+ events := [Spawn(id: 1, name: "orc"), Spawn(id: 2, name: "elf"), Damage(id: 1, amount: 30), Damage(id: 9, amount: 5)]
90
- handle(world, Damage(id: 1, amount: 30))
91
- handle(world, Damage(id: 9, amount: 5))
88
+ world := events.fold(start, |w, e| handle(w, e))
92
89
  assert world.get(1)!.hp == 70
93
90
  assert world.get(2)!.name == "elf"
94
- handle(world, Despawn(id: 2))
91
+ after := handle(world, Despawn(id: 2))
92
+ assert after.length() == 1
93
+ assert !after.has(2)
95
- assert world.length() == 1
94
+ assert world.length() == 2
96
- assert !world.has(2)
examples/generics.plum CHANGED
@@ -182,17 +182,11 @@ test "Int and Float extremes survive List push/get"
182
182
  assert floats.get(2).unwrapOr(0.0) == 5e-324
183
183
 
184
184
  test "Int and Float extremes survive a Map[Str, V] value"
185
- mi: Map[Str, Int] := Map.empty()
186
- mi.set("big", 9223372036854775807)
187
- mi.set("small", 0 - 9223372036854775807 - 1)
185
+ mi := ["big" => 9223372036854775807, "small" => 0 - 9223372036854775807 - 1, "odd" => 9007199254740993]
188
- mi.set("odd", 9007199254740993)
189
186
  assert mi.get("big").unwrapOr(0) == 9223372036854775807
190
187
  assert mi.get("small").unwrapOr(0) == 0 - 9223372036854775807 - 1
191
188
  assert mi.get("odd").unwrapOr(0) == 9007199254740993
192
- mf: Map[Str, Float] := Map.empty()
193
- mf.set("nan", 0.0 / 0.0)
189
+ mf := ["nan" => 0.0 / 0.0, "negzero" => -0.0, "tiny" => 5e-324]
194
- mf.set("negzero", -0.0)
195
- mf.set("tiny", 5e-324)
196
190
  nan := mf.get("nan").unwrapOr(0.0)
197
191
  assert nan != nan
198
192
  assert 1.0 / mf.get("negzero").unwrapOr(1.0) < 0.0
examples/maps.plum CHANGED
@@ -1,12 +1,30 @@
1
+ # Maps: a `Map[K, V]` is a persistent ordered map, a balanced tree like Haskell's
1
- # Maps: building a `Map` from `key => value` pairs. `k => v` is sugar for
2
+ # `Data.Map`. `[k => v, ..]` builds one (`k => v` is sugar for `Pair(k, v)` in any call's
3
+ # argument list; a later duplicate key wins). Nothing changes in place: `with` and `remove`
2
- # `Pair(k, v)` in any call's argument list; later duplicate keys win.
4
+ # return a new map that shares most of its nodes with the old one, and the old one stays
5
+ # as it was. Keys are kept in order by their `compare` method, so walks go in key order.
3
6
  import std/Int
4
7
  import std/Str
5
8
  import std/Map
6
9
  import std/Float
10
+ import std/Option
11
+ import std/Pair
12
+ import std/Slice
7
13
 
8
14
  struct MapPoint(x: Float, y: Float)
9
15
 
16
+ # A key type of your own: `compare` returns a negative Int, 0 or a positive Int.
17
+ struct Version(major: Int, minor: Int) =
18
+ fun compare(self, o: Version) -> Int =
19
+ if self.major != o.major then self.major.compare(o.major) else self.minor.compare(o.minor)
20
+
21
+ fun toStr(self) -> Str = "{self.major}.{self.minor}"
22
+
23
+ # Fills a map with `n` points: each `with` is handed the map the last one made.
24
+ fun points(n: Int) -> Map[Int, MapPoint] =
25
+ start: Map[Int, MapPoint] := Map.empty()
26
+ 0.until(n).fold(start, |m, i| m.with(i, MapPoint(x: Float(i), y: Float(i) * 2.0)))
27
+
10
28
  test "maps_example_arrow_form"
11
29
  m := ["ann" => 3, "bob" => 5]
12
30
  assert m.get("bob")! == 5
@@ -15,13 +33,40 @@ test "maps_example_arrow_form"
15
33
  test "maps_mixed_pair_and_arrow"
16
34
  assert ["a" => 1, "b" => 2].length() == 2
17
35
 
36
+ test "old versions stay as they were"
37
+ v1 := ["ann" => 3, "bob" => 5]
38
+ v2 := v1.with("cy", 7)
39
+ v3 := v2.remove("ann").with("bob", 50)
40
+ assert v1.toStr() == "[ann => 3, bob => 5]"
41
+ assert v2.toStr() == "[ann => 3, bob => 5, cy => 7]"
42
+ assert v3.toStr() == "[bob => 50, cy => 7]"
43
+
44
+ test "walks go in key order"
45
+ m := [30 => "c", 10 => "a", 20 => "b"]
46
+ assert m.keys().toStr() == "[10,20,30]"
47
+ assert m.fold("", |acc, k, v| acc + v) == "abc"
48
+ assert m.min()!.first == 10 && m.max()!.second == "c"
49
+ assert m.atLeast(15)!.first == 20 && m.below(10).isNone()
50
+ total := Slice[Int]()
51
+ for e := range m
52
+ total.push(e.first)
53
+ assert total.toStr() == "[10,20,30]"
54
+
55
+ test "counting with upsert"
56
+ start: Map[Str, Int] := Map.empty()
57
+ counts := ["a", "b", "a", "c", "a"].fold(start, |m, w| m.upsert(w, 1, |n| n + 1))
58
+ assert counts.toStr() == "[a => 3, b => 1, c => 1]"
59
+
60
+ test "a struct with compare is a key"
61
+ m := [Version(major: 1, minor: 10) => "late", Version(major: 1, minor: 2) => "early"]
62
+ assert m.keys().map(|v| v.toStr()).join(" ") == "1.2 1.10"
63
+
18
64
  test "Map[Int, MapPoint] struct values"
19
- m: Map[Int, MapPoint] := Map.empty()
20
- for i := range 500
65
+ m := points(500)
21
- m.set(i, MapPoint(x: Float(i), y: Float(i) * 2.0))
22
66
  v := m.get(499)!
23
67
  assert v.x == 499.0
24
68
  assert v.y == 998.0
25
- m.set(499, MapPoint(x: 1.0, y: 2.0))
69
+ m2 := m.with(499, MapPoint(x: 1.0, y: 2.0))
26
- assert m.get(499)!.y == 2.0
70
+ assert m2.get(499)!.y == 2.0
71
+ assert m.get(499)!.y == 998.0
27
- assert m.length() == 500
72
+ assert m2.length() == 500
std/Json.plum CHANGED
@@ -523,7 +523,8 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
523
523
  else
524
524
  self.parsePairs(pairs)
525
525
 
526
- # `parseObject`'s loop: the `key: value` pairs up to the closing brace, set into `pairs`.
526
+ # `parseObject`'s loop: the `key: value` pairs up to the closing brace, added to `pairs`
527
+ # (a later duplicate key wins).
527
528
  fun parsePairs(self, pairs: Map[Str, Json]) -> Result[Json, JsonError] =
528
529
  self.skipSpace()
529
530
  if self.peek() != 34
@@ -539,19 +540,19 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
539
540
  self.advance()
540
541
  self.skipSpace()
541
542
  v := self.parseValue()?
542
- pairs.set(key, v)
543
+ more := pairs.with(key, v)
543
544
  self.skipSpace()
544
545
  c := self.peek()
545
546
  if c == 125
546
547
  self.advance()
547
548
  self.depth = self.depth - 1
548
- Ok(JsonObj(fields: pairs))
549
+ Ok(JsonObj(fields: more))
549
550
  else if c != 44
550
551
  self.note("expected ',' or '}}'")
551
552
  Err(InvalidJson)
552
553
  else
553
554
  self.advance()
554
- self.parsePairs(pairs)
555
+ self.parsePairs(more)
555
556
 
556
557
  fun hexDigitValue(b: Int) -> Int =
557
558
  if b >= 48 && b <= 57
@@ -625,11 +626,9 @@ primitive Slice[T] =
625
626
  fromJsonFrom(items, i + 1, out)
626
627
 
627
628
  primitive Map[K, V] =
628
- # A JSON object; keys must be `Str`.
629
+ # A JSON object; keys must be `Str`. Its fields are in key order.
629
630
  fun toJson(self) -> Json =
630
- out: Map[Str, Json] := Map.empty()
631
+ out: Map[Str, Json] := self.map(|v| v.toJson())
631
- for e := range self.entries()
632
- out.set(e.first, e.second.toJson())
633
632
  JsonObj(fields: out)
634
633
 
635
634
  fun fromJson(j: Json) -> Result[Map[Str, V], JsonError] =
@@ -637,15 +636,14 @@ primitive Map[K, V] =
637
636
  out: Map[Str, V] := Map.empty()
638
637
  fromJsonPairs(pairs.entries(), 0, out)
639
638
 
640
- # `fromJson`'s loop: decodes the values of `entries` from `i` on, setting them into `out`.
639
+ # `fromJson`'s loop: decodes the values of `entries` from `i` on, adding them to `out`.
641
640
  fun fromJsonPairs(entries: Slice[Pair[Str, Json]], i: Int, out: Map[Str, V]) -> Result[Map[Str, V], JsonError] =
642
641
  if i >= entries.length()
643
642
  Ok(out)
644
643
  else
645
644
  e := entries.at(i)
646
645
  v := V.fromJson(e.second)?
647
- out.set(e.first, v)
648
- fromJsonPairs(entries, i + 1, out)
646
+ fromJsonPairs(entries, i + 1, out.with(e.first, v))
649
647
 
650
648
  fun jsonTestDecodeInt(s: Str) -> Result[Int, JsonError] = Json.decode(s)
651
649
 
std/Map.plum CHANGED
@@ -5,493 +5,943 @@ import std/Array
5
5
  import std/Int
6
6
  import std/Float
7
7
  import std/Str
8
+ import std/Bool
9
+ import std/Byte
8
10
  import std/Buffer
9
11
  import std/Pair
10
12
  import std/Option
13
+ import std/List
11
14
 
12
- # A Map is an open-addressing hash table with an insertion-ordered dense entry
15
+ # A Map is a persistent ordered map: a weight-balanced binary search tree, as in Haskell's
16
+ # `Data.Map` (Adams 1993). Every node stores the size of its subtree, and neither side of a
17
+ # node holds more than 3 times as many entries as the other (unless both together hold at
13
- # store (the layout of Python's dict):
18
+ # most one), so the height stays below 2 log2(n) + 2.
14
19
  #
20
+ # Nothing changes in place. `m.with(k, v)` returns a new map that rebuilds only the
21
+ # O(log n) nodes on the path to `k` and shares every other subtree with `m`, and `m` stays
15
- # index : Array[Int] power-of-two sized probe table (capacity, starts at 16).
22
+ # as it was. The updates match a node and rebuild one of the same shape, the form the
16
- # 0 = empty, 1 = tombstone (deleted), e + 2 = entry e.
17
- # hashes : Array[Int] per entry: the mixed hash, compared before `==` so
23
+ # compiler's cell reuse (FBIP) looks for, but that pass only takes free non-generic fns so
18
- # most mismatches never call `==`, and reused on rehash.
24
+ # far, so each update allocates its path even when nothing else holds `m`.
19
- # keys : Array[K] per entry (parallel arrays; `Array[V]` of a struct V is
20
- # vals : Array[V] stored field by field, so inserting allocates nothing).
21
- # alive : Array[Bool] per entry: false once deleted.
22
- # used : Int entries appended so far, dead ones included.
23
- # size : Int live entries.
24
25
  #
26
+ # Keys are ordered by their `compare(self, o) -> Int` method (negative: before, 0: the same
25
- # Entries are appended in insertion order; `index` is probed linearly. A delete
27
+ # key, positive: after). `Int`, `Float`, `Str`, `Bool` and `Byte` have one; a struct
26
- # writes a tombstone into `index` and clears `alive`. The entry arrays hold
27
- # capacity * 3/4 slots, so `used == capacity * 3/4` is the 75% load limit counting
28
- # tombstones (every dead entry owns at most one tombstone): at that point the
28
+ # becomes a key type by defining it. `Float` keys use a total order: `-0.0` and `0.0` are
29
- # table is rebuilt, doubling the capacity if at least half the slots are live,
30
- # or just compacting dead entries away otherwise. A tombstone met while
29
+ # the same key, and every NaN is one key, after `Infinity`. Iteration, `keys`, `values`,
31
- # inserting a new key is reused.
32
- # Iteration order is insertion order (a re-`set` of an existing key keeps its
30
+ # `entries`, `fold`, `each` and `toStr` all go in ascending key order.
31
+ #
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`,
34
+ # `entries`, `fold`, `each`, `map`, `filter`, `==` and `toStr` O(n); `split` O(log n);
35
+ # `union`, `intersection` and `difference` O(m log(n / m + 1)) for sizes m <= n;
33
- # original position; a removed-then-re-added key goes to the end).
36
+ # `fromSlice` O(n) on keys already strictly ascending, else O(n log n).
37
+ # Stack: every walk is O(log n) deep (lookups are tail calls), so a 1,000,000-entry map is
38
+ # fine.
39
+ enum Map[K, V] =
40
+ | MapTip
34
- # `K` must have a `hash() -> Int` method (duck-typed) and `==`.
41
+ | MapBin(size: Int, key: K, value: V, left: Map[K, V], right: Map[K, V])
35
- struct Map[K, V](mut index: Array[Int], mut hashes: Array[Int], mut keys: Array[K], mut vals: Array[V], mut alive: Array[Bool], mut used: Int, mut size: Int) =
42
+
36
-
37
- # The empty map (`m: Map[Str, Int] := Map.empty()`); a map literal
43
+ # The empty map (`m: Map[Str, Int] := Map.empty()`). A map literal `[k => v, ..]` is
38
- # `[k => v, ..]` desugars to `Map.empty().with(k, v)...` (a later duplicate
44
+ # `Map.empty().with(k, v)...`, so a later duplicate key wins.
39
- # key wins, as in `set`).
40
- fun empty() -> Map[K, V] =
45
+ fun empty() -> Map[K, V] = MapTip
41
- m := Map(index: Array[Int](), hashes: Array[Int](), keys: Array[K](), vals: Array[V](), alive: Array[Bool](), used: 0, size: 0)
42
- m.allocate(16)
43
- m
44
46
 
45
47
  # `Map[Str, Int]()` is the empty map too, like `Slice[T]()` and `Set[T]()`.
46
- fun init() -> Map[K, V] =
48
+ fun init() -> Map[K, V] = MapTip
47
- Map.empty()
49
+
48
-
49
- # Installs empty storage for `cap` index slots (a power of two).
50
- fun allocate(self, cap: Int) -> Unit =
51
- n := cap - cap / 4
50
+ # The map of one entry.
52
- self.index = Array[Int]().resize(cap)
53
- self.hashes = Array[Int]().resize(n)
54
- self.keys = Array[K]().resize(n)
55
- self.vals = Array[V]().resize(n)
56
- self.alive = Array[Bool]().resize(n)
57
- self.used = 0
58
- self.size = 0
59
-
60
- # `k`'s hash, avalanched so identity hashes (`Int`) and sequential keys
61
- # spread across the low bits that pick the slot.
62
- fun hashOf(self, k: K) -> Int =
51
+ fun single(k: K, v: V) -> Map[K, V] =
63
- h := k.hash()
64
- mixed := {h ^ {h >> 32}} * 0x5851f42d4c957f2d
65
- mixed ^ {mixed >> 29}
52
+ tip: Map[K, V] := MapTip
66
-
53
+ MapBin(size: 1, key: k, value: v, left: tip, right: tip)
54
+
67
- # The `index` slot holding `k` (whose hash is `h`), or -1.
55
+ # The map of `entries` (a later duplicate key wins). O(n) when the keys are already
56
+ # strictly ascending, O(n log n) otherwise.
68
- fun findSlot(self, k: K, h: Int) -> Int =
57
+ fun fromSlice(entries: Slice[Pair[K, V]]) -> Map[K, V] =
69
- mask := self.index.length() - 1
58
+ n := entries.length()
70
- self.probeFor(h & mask, mask, k, h)
59
+ if mapAscendingFrom(entries, 1, n)
71
-
72
- # Linear probe from `slot` for `k`: the slot holding it, or -1 at an empty slot.
73
- fun probeFor(self, slot: Int, mask: Int, k: K, h: Int) -> Int =
74
- x := self.index.get(slot)
60
+ Map.buildSorted(entries, 0, n)
75
- if x == 0
76
- -1
77
- else if x >= 2 && self.hashes.get(x - 2) == h && self.keys.get(x - 2) == k
78
- slot
79
61
  else
62
+ tip: Map[K, V] := MapTip
80
- self.probeFor({slot + 1} & mask, mask, k, h)
63
+ entries.fold(tip, |m, e| m.with(e.first, e.second))
81
64
 
82
- # Gets the value for `k`, or None if absent.
83
- fun get(self, k: K) -> Option[V] =
65
+ fun fromList(entries: List[Pair[K, V]]) -> Map[K, V] =
84
- slot := self.findSlot(k, self.hashOf(k))
85
- if slot < 0
86
- None
87
- else
88
- Some(self.vals.get(self.index.get(slot) - 2))
66
+ Map.fromSlice(entries.toSlice())
89
-
90
- fun has(self, k: K) -> Bool =
67
+
91
- self.findSlot(k, self.hashOf(k)) >= 0
92
-
93
- # Rebuilds the table when the entry arrays are full: doubles the capacity if
94
- # at least half the entries are live, else compacts at the same capacity.
68
+ # The balanced tree of the entries `lo` to `hi - 1` of `xs`, whose keys ascend.
95
- fun rebuild(self) -> Unit =
96
- cap := self.index.length()
97
- oldHashes := self.hashes
98
- oldKeys := self.keys
99
- oldVals := self.vals
100
- oldAlive := self.alive
101
- oldUsed := self.used
102
- n := cap - cap / 4
103
- newCap := if self.size * 2 >= n then cap * 2 else cap
104
- self.allocate(newCap)
105
- mask := newCap - 1
106
- for e := range oldUsed
107
- if oldAlive.get(e)
108
- h := oldHashes.get(e)
109
- slot := self.emptySlot(h & mask, mask)
110
- j := self.used
111
- self.index.set(slot, j + 2)
112
- self.hashes.set(j, h)
113
- self.keys.set(j, oldKeys.get(e))
114
- self.vals.set(j, oldVals.get(e))
115
- self.alive.set(j, true)
116
- self.used = j + 1
117
- self.size = self.used
118
-
119
- # The first empty (0) slot at or after `slot`, probing linearly.
120
- fun emptySlot(self, slot: Int, mask: Int) -> Int =
121
- if self.index.get(slot) != 0
122
- self.emptySlot({slot + 1} & mask, mask)
123
- else
124
- slot
125
-
126
- # The slot a new key is inserted at: the first tombstone on its probe path,
127
- # else the empty slot that ends it. `tomb` is the first tombstone seen, or -1.
128
- fun insertSlot(self, slot: Int, mask: Int, tomb: Int) -> Int =
69
+ fun buildSorted(xs: Slice[Pair[K, V]], lo: Int, hi: Int) -> Map[K, V] =
129
- x := self.index.get(slot)
130
- if x == 0
131
- if tomb >= 0 then tomb else slot
132
- else
133
- self.insertSlot({slot + 1} & mask, mask, if tomb < 0 && x == 1 then slot else tomb)
134
-
135
- # Sets `k`'s value to `v`, replacing an existing entry for `k` in place.
136
- fun set(self, k: K, v: V) -> Unit =
137
- h := self.hashOf(k)
138
- slot := self.findSlot(k, h)
139
- if slot >= 0
70
+ if lo >= hi
140
- self.vals.set(self.index.get(slot) - 2, v)
71
+ MapTip
141
72
  else
142
- self.insertNew(k, v, h)
143
-
144
- # Appends a key known to be absent (hash `h`), rebuilding first if full.
145
- fun insertNew(self, k: K, v: V, h: Int) -> Unit =
146
- if self.used >= self.hashes.length()
147
- self.rebuild()
148
- mask := self.index.length() - 1
149
- slot := self.insertSlot(h & mask, mask, -1)
150
- e := self.used
151
- self.index.set(slot, e + 2)
152
- self.hashes.set(e, h)
153
- self.keys.set(e, k)
154
- self.vals.set(e, v)
155
- self.alive.set(e, true)
156
- self.used = e + 1
157
- self.size = self.size + 1
158
-
159
- # `set`, returning the map so calls chain: a map literal `[k => v, ..]`
160
- # desugars to `Map.empty().with(k, v)...`. (`set` stays `Unit` so its many
161
- # statement-position callers need no `_ :=`.)
162
- fun with(self, k: K, v: V) -> Map[K, V] =
163
- self.set(k, v)
164
- self
165
-
166
- # Sets `k`'s value to `v` only if `k` isn't already present.
167
- fun putIfAbsent(self, k: K, v: V) -> Unit =
168
- if !self.has(k)
169
- self.set(k, v)
170
-
171
- # Removes `k`'s entry, if present (leaves a tombstone).
172
- fun remove(self, k: K) -> Unit =
173
- slot := self.findSlot(k, self.hashOf(k))
174
- if slot >= 0
175
- self.alive.set(self.index.get(slot) - 2, false)
176
- self.index.set(slot, 1)
177
- self.size = self.size - 1
178
-
179
- fun length(self) -> Int =
180
- self.size
181
-
182
- fun isEmpty(self) -> Bool =
183
- self.size == 0
184
-
185
- fun clear(self) -> Unit =
186
- self.allocate(16)
187
-
188
- # Every key with its value, in insertion order: `for e := range m.entries()`
189
- # (`e.first`, `e.second`).
73
+ mid := {lo + hi} / 2
74
+ e := xs.at(mid)
75
+ MapBin(size: hi - lo, key: e.first, value: e.second, left: Map.buildSorted(xs, lo, mid), right: Map.buildSorted(xs, mid + 1, hi))
76
+
77
+ # ---- queries ----
78
+
79
+ fun length(self) -> Int = match self
80
+ MapTip => 0
81
+ MapBin(n, _, _, _, _) => n
82
+
83
+ fun isEmpty(self) -> Bool = match self
84
+ MapTip => true
85
+ MapBin(_, _, _, _, _) => false
86
+
87
+ # The value stored for `k`, or None. A tail call, one `compare` per level.
88
+ fun get(self, k: K) -> Option[V] = match self
89
+ MapTip => None
90
+ MapBin(_, nk, nv, l, r) =>
91
+ c := k.compare(nk)
92
+ if c < 0 then l.get(k) else if c > 0 then r.get(k) else Some(nv)
93
+
94
+ # The value stored for `k`, or `fallback` (no `Option` is made).
95
+ fun getOr(self, k: K, fallback: V) -> V = match self
96
+ MapTip => fallback
97
+ MapBin(_, nk, nv, l, r) =>
98
+ c := k.compare(nk)
99
+ if c < 0 then l.getOr(k, fallback) else if c > 0 then r.getOr(k, fallback) else nv
100
+
101
+ fun has(self, k: K) -> Bool = match self
102
+ MapTip => false
103
+ MapBin(_, nk, _, l, r) =>
104
+ c := k.compare(nk)
105
+ if c < 0 then l.has(k) else if c > 0 then r.has(k) else true
106
+
107
+ # The number of nodes on the longest path from the root (0 when empty).
108
+ fun height(self) -> Int = match self
109
+ MapTip => 0
110
+ MapBin(_, _, _, l, r) => l.height().max(r.height()) + 1
111
+
112
+ # ---- updates (each returns a new map; the receiver stays as it was) ----
113
+
114
+ # The map with `k` mapped to `v`, replacing the value of an existing `k`.
115
+ fun with(self, k: K, v: V) -> Map[K, V] = match self
116
+ MapTip => MapBin(size: 1, key: k, value: v, left: self, right: self)
117
+ MapBin(n, nk, nv, l, r) =>
118
+ c := k.compare(nk)
119
+ if c < 0
120
+ nl := l.with(k, v)
121
+ sl := nl.length()
122
+ sr := r.length()
123
+ if sl + sr > 1 && sl > 3 * sr
124
+ Map.rotateRight(nk, nv, nl, r)
125
+ else
126
+ MapBin(size: sl + sr + 1, key: nk, value: nv, left: nl, right: r)
127
+ else if c > 0
128
+ nr := r.with(k, v)
129
+ sl := l.length()
130
+ sr := nr.length()
131
+ if sl + sr > 1 && sr > 3 * sl
132
+ Map.rotateLeft(nk, nv, l, nr)
133
+ else
134
+ MapBin(size: sl + sr + 1, key: nk, value: nv, left: l, right: nr)
135
+ else
136
+ MapBin(size: n, key: k, value: v, left: l, right: r)
137
+
138
+ # `with`, by its older name.
139
+ fun set(self, k: K, v: V) -> Map[K, V] = self.with(k, v)
140
+
141
+ # The map with `k` mapped to `v` if `k` is absent; the same map otherwise.
142
+ fun putIfAbsent(self, k: K, v: V) -> Map[K, V] =
143
+ if self.has(k) then self else self.with(k, v)
144
+
145
+ # The map with `k` mapped to `f` of its value, or to `v` when `k` is absent:
146
+ # `counts.upsert(word, 1, |n| n + 1)` (Data.Map's `insertWith`).
147
+ fun upsert(self, k: K, v: V, f: fn(V) -> V) -> Map[K, V] = match self.get(k)
148
+ Some(old) => self.with(k, f(old))
149
+ None => self.with(k, v)
150
+
151
+ # The map with `k`'s value replaced by `f` of it; the same map when `k` is absent
152
+ # (Data.Map's `adjust`).
153
+ fun update(self, k: K, f: fn(V) -> V) -> Map[K, V] = match self.get(k)
154
+ Some(old) => self.with(k, f(old))
155
+ None => self
156
+
157
+ # The map with `k`'s entry decided by `f`: given the value (or None), it returns the new
158
+ # value, or None to leave `k` out (Data.Map's `alter`).
159
+ fun alter(self, k: K, f: fn(Option[V]) -> Option[V]) -> Map[K, V] = match f(self.get(k))
160
+ Some(v) => self.with(k, v)
161
+ None => self.remove(k)
162
+
163
+ # The map without `k`; an equal map when `k` is absent.
164
+ fun remove(self, k: K) -> Map[K, V] = match self
165
+ MapTip => self
166
+ MapBin(_, nk, nv, l, r) =>
167
+ c := k.compare(nk)
168
+ if c < 0
169
+ nl := l.remove(k)
170
+ sl := nl.length()
171
+ sr := r.length()
172
+ if sl + sr > 1 && sr > 3 * sl
173
+ Map.rotateLeft(nk, nv, nl, r)
174
+ else
175
+ MapBin(size: sl + sr + 1, key: nk, value: nv, left: nl, right: r)
176
+ else if c > 0
177
+ nr := r.remove(k)
178
+ sl := l.length()
179
+ sr := nr.length()
180
+ if sl + sr > 1 && sl > 3 * sr
181
+ Map.rotateRight(nk, nv, l, nr)
182
+ else
183
+ MapBin(size: sl + sr + 1, key: nk, value: nv, left: l, right: nr)
184
+ else
185
+ Map.glue(l, r)
186
+
187
+ # ---- order ----
188
+
189
+ # The entry with the smallest key, or None. A tail call down the left spine.
190
+ fun min(self) -> Option[Pair[K, V]] = match self
191
+ MapTip => None
192
+ MapBin(_, k, v, MapTip, _) => Some(Pair(first: k, second: v))
193
+ MapBin(_, _, _, l, _) => l.min()
194
+
195
+ # The entry with the largest key, or None.
196
+ fun max(self) -> Option[Pair[K, V]] = match self
197
+ MapTip => None
198
+ MapBin(_, k, v, _, MapTip) => Some(Pair(first: k, second: v))
199
+ MapBin(_, _, _, _, r) => r.max()
200
+
201
+ # The map without its smallest key (the same map when empty).
202
+ fun removeMin(self) -> Map[K, V] = match self
203
+ MapTip => self
204
+ MapBin(_, _, _, MapTip, r) => r
205
+ MapBin(_, k, v, l, r) => Map.balance(k, v, l.removeMin(), r)
206
+
207
+ # The map without its largest key.
208
+ fun removeMax(self) -> Map[K, V] = match self
209
+ MapTip => self
210
+ MapBin(_, _, _, l, MapTip) => l
211
+ MapBin(_, k, v, l, r) => Map.balance(k, v, l, r.removeMax())
212
+
213
+ # The entry with the largest key before `k`, or None (Data.Map's `lookupLT`).
214
+ fun below(self, k: K) -> Option[Pair[K, V]] =
215
+ none: Option[Pair[K, V]] := None
216
+ self.belowFrom(k, none, false)
217
+
218
+ # The entry with the largest key at or before `k` (`lookupLE`).
219
+ fun atMost(self, k: K) -> Option[Pair[K, V]] =
220
+ none: Option[Pair[K, V]] := None
221
+ self.belowFrom(k, none, true)
222
+
223
+ # The entry with the smallest key after `k` (`lookupGT`).
224
+ fun above(self, k: K) -> Option[Pair[K, V]] =
225
+ none: Option[Pair[K, V]] := None
226
+ self.aboveFrom(k, none, false)
227
+
228
+ # The entry with the smallest key at or after `k` (`lookupGE`).
229
+ fun atLeast(self, k: K) -> Option[Pair[K, V]] =
230
+ none: Option[Pair[K, V]] := None
231
+ self.aboveFrom(k, none, true)
232
+
233
+ fun belowFrom(self, k: K, best: Option[Pair[K, V]], orEqual: Bool) -> Option[Pair[K, V]] = match self
234
+ MapTip => best
235
+ MapBin(_, nk, nv, l, r) =>
236
+ c := nk.compare(k)
237
+ if c < 0 || orEqual && c == 0
238
+ if c == 0 then Some(Pair(first: nk, second: nv)) else r.belowFrom(k, Some(Pair(first: nk, second: nv)), orEqual)
239
+ else
240
+ l.belowFrom(k, best, orEqual)
241
+
242
+ fun aboveFrom(self, k: K, best: Option[Pair[K, V]], orEqual: Bool) -> Option[Pair[K, V]] = match self
243
+ MapTip => best
244
+ MapBin(_, nk, nv, l, r) =>
245
+ c := nk.compare(k)
246
+ if c > 0 || orEqual && c == 0
247
+ if c == 0 then Some(Pair(first: nk, second: nv)) else l.aboveFrom(k, Some(Pair(first: nk, second: nv)), orEqual)
248
+ else
249
+ r.aboveFrom(k, best, orEqual)
250
+
251
+ # The entry with the `i`-th smallest key (from 0), or None out of range (`elemAt`).
252
+ fun entryAt(self, i: Int) -> Option[Pair[K, V]] = match self
253
+ MapTip => None
254
+ MapBin(_, nk, nv, l, r) =>
255
+ sl := l.length()
256
+ if i < 0
257
+ None
258
+ else if i < sl
259
+ l.entryAt(i)
260
+ else if i == sl
261
+ Some(Pair(first: nk, second: nv))
262
+ else
263
+ r.entryAt(i - sl - 1)
264
+
265
+ # The position of `k` in key order (from 0), or None when absent (`lookupIndex`).
266
+ fun indexOf(self, k: K) -> Option[Int] = self.indexFrom(k, 0)
267
+
268
+ fun indexFrom(self, k: K, n: Int) -> Option[Int] = match self
269
+ MapTip => None
270
+ MapBin(_, nk, _, l, r) =>
271
+ c := k.compare(nk)
272
+ 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())
273
+
274
+ # The entries with keys before `k` (`first`) and after `k` (`second`); an entry for `k`
275
+ # itself is in neither (read it with `get`).
276
+ fun split(self, k: K) -> Pair[Map[K, V], Map[K, V]] =
277
+ c := self.cut(k)
278
+ Pair(first: c.below, second: c.above)
279
+
280
+ # ---- combining ----
281
+
282
+ # Every entry of either map; for a key in both, the value from `self` (left-biased).
283
+ fun union(self, other: Map[K, V]) -> Map[K, V] = match other
284
+ MapTip => self
285
+ MapBin(_, _, _, _, _) =>
286
+ match self
287
+ MapTip => other
288
+ MapBin(_, k, v, l, r) =>
289
+ c := other.cut(k)
290
+ Map.link(k, v, l.union(c.below), r.union(c.above))
291
+
292
+ # Every entry of either map; for a key in both, `f(self's value, other's value)`.
293
+ fun unionWith(self, other: Map[K, V], f: fn(V, V) -> V) -> Map[K, V] = match other
294
+ MapTip => self
295
+ MapBin(_, _, _, _, _) =>
296
+ match self
297
+ MapTip => other
298
+ MapBin(_, k, v, l, r) =>
299
+ c := other.cut(k)
300
+ nv := match c.found
301
+ Some(ov) => f(v, ov)
302
+ None => v
303
+ Map.link(k, nv, l.unionWith(c.below, f), r.unionWith(c.above, f))
304
+
305
+ # The entries of `self` whose keys are also in `other`, with `self`'s values.
306
+ fun intersection(self, other: Map[K, V]) -> Map[K, V] = match other
307
+ MapTip => other
308
+ MapBin(_, _, _, _, _) =>
309
+ match self
310
+ MapTip => self
311
+ MapBin(_, k, v, l, r) =>
312
+ c := other.cut(k)
313
+ l2 := l.intersection(c.below)
314
+ r2 := r.intersection(c.above)
315
+ if c.found.isSome() then Map.link(k, v, l2, r2) else Map.merge(l2, r2)
316
+
317
+ # The entries of `self` whose keys are not in `other`.
318
+ fun difference(self, other: Map[K, V]) -> Map[K, V] = match self
319
+ MapTip => self
320
+ MapBin(_, _, _, _, _) =>
321
+ match other
322
+ MapTip => self
323
+ MapBin(_, k, _, l, r) =>
324
+ c := self.cut(k)
325
+ Map.merge(c.below.difference(l), c.above.difference(r))
326
+
327
+ # ---- walks, in ascending key order ----
328
+
329
+ # `f(..f(f(acc, k0, v0), k1, v1).., kn, vn)`.
330
+ fun fold[A](self, acc: A, f: fn(A, K, V) -> A) -> A = match self
331
+ MapTip => acc
332
+ MapBin(_, k, v, l, r) => r.fold(f(l.fold(acc, f), k, v), f)
333
+
334
+ # Calls `f(k, v)` on each entry.
335
+ fun each(self, f: fn(K, V) -> Unit) -> Unit =
336
+ if MapBin(_, k, v, l, r) := self
337
+ l.each(f)
338
+ f(k, v)
339
+ r.each(f)
340
+
341
+ # The same keys, each value replaced by `f` of it. Same shape, so O(n).
342
+ fun map[B](self, f: fn(V) -> B) -> Map[K, B] = match self
343
+ MapTip => MapTip
344
+ MapBin(n, k, v, l, r) => MapBin(size: n, key: k, value: f(v), left: l.map(f), right: r.map(f))
345
+
346
+ # The entries for which `keep(k, v)` holds.
347
+ fun filter(self, keep: fn(K, V) -> Bool) -> Map[K, V] = match self
348
+ MapTip => self
349
+ MapBin(_, k, v, l, r) =>
350
+ l2 := l.filter(keep)
351
+ r2 := r.filter(keep)
352
+ if keep(k, v) then Map.link(k, v, l2, r2) else Map.merge(l2, r2)
353
+
354
+ fun any(self, pred: fn(K, V) -> Bool) -> Bool = match self
355
+ MapTip => false
356
+ MapBin(_, k, v, l, r) => l.any(pred) || pred(k, v) || r.any(pred)
357
+
358
+ fun all(self, pred: fn(K, V) -> Bool) -> Bool = match self
359
+ MapTip => true
360
+ MapBin(_, k, v, l, r) => l.all(pred) && pred(k, v) && r.all(pred)
361
+
362
+ # Every key with its value: `for e := range m.entries()` (`e.first`, `e.second`).
190
363
  fun entries(self) -> Slice[Pair[K, V]] =
191
364
  out := Slice[Pair[K, V]]()
192
- for i := range self.used
193
- if self.alive.get(i)
194
- out.push(Pair(first: self.keys.get(i), second: self.vals.get(i)))
365
+ self.each(|k, v| out.push(Pair(first: k, second: v)))
195
366
  out
196
367
 
197
- # Every key, in insertion order: `for k := range m.keys()`.
368
+ # Every key, ascending.
198
369
  fun keys(self) -> Slice[K] =
199
370
  out := Slice[K]()
200
- for i := range self.used
201
- if self.alive.get(i)
202
- out.push(self.keys.get(i))
371
+ self.each(|k, v| out.push(k))
203
372
  out
204
373
 
205
- # Every value, in insertion order: `for v := range m.values()`.
374
+ # Every value, in key order.
206
375
  fun values(self) -> Slice[V] =
207
376
  out := Slice[V]()
208
- for i := range self.used
209
- if self.alive.get(i)
210
- out.push(self.vals.get(i))
377
+ self.each(|k, v| out.push(v))
211
378
  out
212
379
 
380
+ # The loop protocol: `for e := range m` visits each entry (`e.first`, `e.second`) in key
381
+ # order. Each step is O(log n); `m.entries()` is cheaper when every entry is read.
382
+ fun next(self) -> Option[Pair[Pair[K, V], Map[K, V]]] = match self
383
+ MapTip => None
384
+ MapBin(_, _, _, _, _) => Some(Pair(first: self.min()!, second: self.removeMin()))
385
+
386
+ # Same keys with equal values (`m == n`); the shapes may differ.
387
+ fun eq(self, o: Map[K, V]) -> Bool =
388
+ if self.length() != o.length()
389
+ false
390
+ else
391
+ a := self.entries()
392
+ b := o.entries()
393
+ 0.until(a.length()).find(|i| a.at(i).first.compare(b.at(i).first) != 0 || a.at(i).second != b.at(i).second).isNone()
394
+
395
+ # The entries in key order, written like a literal: `[1 => one, 2 => two]`.
396
+ fun toStr(self) -> Str =
397
+ buf := Buffer()
398
+ buf.write("[")
399
+ self.each(|k, v|
400
+ if buf.length() > 1
401
+ buf.write(", ")
402
+ buf.write(k.toStr())
403
+ buf.write(" => ")
404
+ buf.write(v.toStr())
405
+ )
406
+ buf.write("]")
407
+ buf.toStr()
408
+
409
+ # ---- the tree's own helpers ----
410
+
411
+ # A node over `l` and `r` with its size worked out (no rebalancing).
412
+ fun bin(k: K, v: V, l: Map[K, V], r: Map[K, V]) -> Map[K, V] =
413
+ MapBin(size: l.length() + r.length() + 1, key: k, value: v, left: l, right: r)
414
+
415
+ # `bin`, rotating when one side holds more than 3 times the other's entries (after one
416
+ # insert or remove below, or one `link`/`merge` step).
417
+ fun balance(k: K, v: V, l: Map[K, V], r: Map[K, V]) -> Map[K, V] =
418
+ sl := l.length()
419
+ sr := r.length()
420
+ if sl + sr <= 1
421
+ MapBin(size: sl + sr + 1, key: k, value: v, left: l, right: r)
422
+ else if sr > 3 * sl
423
+ Map.rotateLeft(k, v, l, r)
424
+ else if sl > 3 * sr
425
+ Map.rotateRight(k, v, l, r)
426
+ else
427
+ MapBin(size: sl + sr + 1, key: k, value: v, left: l, right: r)
428
+
429
+ # `k` over `l` and a too-heavy `r`: a single rotation lifts `r`, a double one lifts `r`'s
430
+ # left child (when that holds at least twice the entries of `r`'s right child).
431
+ fun rotateLeft(k: K, v: V, l: Map[K, V], r: Map[K, V]) -> Map[K, V] = match r
432
+ MapBin(_, rk, rv, rl, rr) =>
433
+ if rl.length() < 2 * rr.length()
434
+ Map.bin(rk, rv, Map.bin(k, v, l, rl), rr)
435
+ else
436
+ match rl
437
+ MapBin(_, mk, mv, ml, mr) => Map.bin(mk, mv, Map.bin(k, v, l, ml), Map.bin(rk, rv, mr, rr))
438
+ MapTip => Map.bin(k, v, l, r)
439
+ MapTip => Map.bin(k, v, l, r)
440
+
441
+ # The mirror of `rotateLeft`.
442
+ fun rotateRight(k: K, v: V, l: Map[K, V], r: Map[K, V]) -> Map[K, V] = match l
443
+ MapBin(_, lk, lv, ll, lr) =>
444
+ if lr.length() < 2 * ll.length()
445
+ Map.bin(lk, lv, ll, Map.bin(k, v, lr, r))
446
+ else
447
+ match lr
448
+ MapBin(_, mk, mv, ml, mr) => Map.bin(mk, mv, Map.bin(lk, lv, ll, ml), Map.bin(k, v, mr, r))
449
+ MapTip => Map.bin(k, v, l, r)
450
+ MapTip => Map.bin(k, v, l, r)
451
+
452
+ # `l` and `r` joined, where every key of `l` is before every key of `r` and the two are
453
+ # balanced against each other: the larger side gives up its end entry as the new root.
454
+ fun glue(l: Map[K, V], r: Map[K, V]) -> Map[K, V] =
455
+ if l.isEmpty()
456
+ r
457
+ else if r.isEmpty()
458
+ l
459
+ else if l.length() > r.length()
460
+ m := l.max()!
461
+ Map.balance(m.first, m.second, l.removeMax(), r)
462
+ else
463
+ m := r.min()!
464
+ Map.balance(m.first, m.second, l, r.removeMin())
465
+
466
+ # `l` and `r` joined, where every key of `l` is before every key of `r`, of any sizes.
467
+ fun merge(l: Map[K, V], r: Map[K, V]) -> Map[K, V] = match l
468
+ MapTip => r
469
+ MapBin(sl, lk, lv, ll, lr) =>
470
+ match r
471
+ MapTip => l
472
+ MapBin(sr, rk, rv, rl, rr) =>
473
+ if 3 * sl < sr
474
+ Map.balance(rk, rv, Map.merge(l, rl), rr)
475
+ else if 3 * sr < sl
476
+ Map.balance(lk, lv, ll, Map.merge(lr, r))
477
+ else
478
+ Map.glue(l, r)
479
+
480
+ # `l`, then `k`, then `r`, where every key of `l` is before `k` and `k` before every key
481
+ # of `r`, of any sizes: descends the larger side until the two are balanced.
482
+ fun link(k: K, v: V, l: Map[K, V], r: Map[K, V]) -> Map[K, V] = match l
483
+ MapTip => r.insertMin(k, v)
484
+ MapBin(sl, lk, lv, ll, lr) =>
485
+ match r
486
+ MapTip => l.insertMax(k, v)
487
+ MapBin(sr, rk, rv, rl, rr) =>
488
+ if 3 * sl < sr
489
+ Map.balance(rk, rv, Map.link(k, v, l, rl), rr)
490
+ else if 3 * sr < sl
491
+ Map.balance(lk, lv, ll, Map.link(k, v, lr, r))
492
+ else
493
+ Map.bin(k, v, l, r)
494
+
495
+ # Adds `k`, which is before every key here.
496
+ fun insertMin(self, k: K, v: V) -> Map[K, V] = match self
497
+ MapTip => MapBin(size: 1, key: k, value: v, left: self, right: self)
498
+ MapBin(_, nk, nv, l, r) => Map.balance(nk, nv, l.insertMin(k, v), r)
499
+
500
+ # Adds `k`, which is after every key here.
501
+ fun insertMax(self, k: K, v: V) -> Map[K, V] = match self
502
+ MapTip => MapBin(size: 1, key: k, value: v, left: self, right: self)
503
+ MapBin(_, nk, nv, l, r) => Map.balance(nk, nv, l, r.insertMax(k, v))
504
+
505
+ # This map cut at `k`.
506
+ fun cut(self, k: K) -> MapCut[K, V] = match self
507
+ MapTip =>
508
+ none: Option[V] := None
509
+ MapCut(below: self, found: none, above: self)
510
+ MapBin(_, nk, nv, l, r) =>
511
+ c := k.compare(nk)
512
+ if c < 0
513
+ lc := l.cut(k)
514
+ MapCut(below: lc.below, found: lc.found, above: Map.link(nk, nv, lc.above, r))
515
+ else if c > 0
516
+ rc := r.cut(k)
517
+ MapCut(below: Map.link(nk, nv, l, rc.below), found: rc.found, above: rc.above)
518
+ else
519
+ MapCut(below: l, found: Some(nv), above: r)
520
+
521
+ # A map cut at a key: the entries before it, its value if present, and the entries after it.
522
+ struct MapCut[K, V](below: Map[K, V], found: Option[V], above: Map[K, V])
523
+
524
+ # True when the keys of `xs` from `i - 1` to `n - 1` strictly ascend.
525
+ fun mapAscendingFrom[K, V](xs: Slice[Pair[K, V]], i: Int, n: Int) -> Bool =
526
+ if i >= n
527
+ true
528
+ else if xs.at(i - 1).first.compare(xs.at(i).first) >= 0
529
+ false
530
+ else
531
+ mapAscendingFrom(xs, i + 1, n)
213
532
 
214
533
  # ---- extensions of std types that need a Map (Slice can't import Map: Map uses Slice) ----
215
534
 
216
535
  primitive Slice[T] =
217
- # The elements grouped by `key`, each group in order, the groups in the order their
536
+ # The elements grouped by `key`, each group in order, the groups in key order:
218
- # keys first appear: `words.groupBy(|w| w.length())`.
537
+ # `words.groupBy(|w| w.length())`.
219
538
  fun groupBy[K](self, key: fn(T) -> K) -> Map[K, Slice[T]] =
220
- out: Map[K, Slice[T]] := Map.empty()
539
+ empty: Map[K, Slice[T]] := Map.empty()
221
- for x := range self
540
+ self.fold(empty, |m, x|
222
541
  k := key(x)
223
- match out.get(k)
542
+ match m.get(k)
224
- Some(g) => g.push(x)
543
+ Some(g) =>
544
+ g.push(x)
545
+ m
225
546
  None =>
226
547
  g := Slice[T]()
227
548
  g.push(x)
228
- out.set(k, g)
549
+ m.with(k, g)
550
+ )
551
+
552
+ # ---------------------------------------------------------------------------
553
+ # Test helpers: an invariant checker and a brute-force model (a sorted association list).
554
+ # ---------------------------------------------------------------------------
555
+
556
+ # The size of `m` if every node's cached size is right and every node is weight balanced
557
+ # (a side holds at most 3 times the other, unless both together hold at most one), else -1.
558
+ fun mapCheckedSize(m: Map[Int, Int]) -> Int = match m
559
+ MapTip => 0
560
+ MapBin(n, _, _, l, r) =>
561
+ sl := mapCheckedSize(l)
562
+ sr := mapCheckedSize(r)
563
+ if sl < 0 || sr < 0 || n != sl + sr + 1
564
+ -1
565
+ else if sl + sr > 1 && {sl > 3 * sr || sr > 3 * sl}
566
+ -1
567
+ else
568
+ n
569
+
570
+ # True when the keys of `xs` strictly ascend.
571
+ fun mapAscending(xs: Slice[Int]) -> Bool =
572
+ 0.until(xs.length() - 1).fold(true, |ok, i| ok && xs.at(i) < xs.at(i + 1))
573
+
574
+ # The invariants: cached sizes right, every node balanced, keys strictly ascending.
575
+ fun mapValid(m: Map[Int, Int]) -> Bool =
576
+ mapCheckedSize(m) == m.length() && mapAscending(m.keys())
577
+
578
+ # The model: entries sorted by key, each key once.
579
+ fun mapModelWith(xs: List[Pair[Int, Int]], k: Int, v: Int) -> List[Pair[Int, Int]] = match xs
580
+ Nil => Cons(head: Pair(first: k, second: v), tail: xs)
581
+ Cons(h, t) =>
582
+ if k < h.first
583
+ Cons(head: Pair(first: k, second: v), tail: xs)
584
+ else if k == h.first
585
+ Cons(head: Pair(first: k, second: v), tail: t)
586
+ else
587
+ Cons(head: h, tail: mapModelWith(t, k, v))
588
+
589
+ fun mapModelWithout(xs: List[Pair[Int, Int]], k: Int) -> List[Pair[Int, Int]] = match xs
590
+ Nil => xs
591
+ Cons(h, t) =>
592
+ if k == h.first
229
- out
593
+ t
594
+ else if k < h.first
595
+ xs
596
+ else
597
+ Cons(head: h, tail: mapModelWithout(t, k))
230
598
 
231
- test "get/set/has round-trip and set replaces an existing key in place"
232
- m: Map[Str, Int] := Map.empty()
233
- assert m.has("a") == false
234
- m.set("a", 1)
235
- assert m.has("a") == true
236
- assert m.get("a")! == 1
237
- assert m.length() == 1
238
- m.set("a", 2)
239
- assert m.get("a")! == 2
240
- assert m.length() == 1
241
-
242
- test "putIfAbsent only sets a key that isn't already present"
599
+ fun mapModelGet(xs: List[Pair[Int, Int]], k: Int) -> Option[Int] =
243
- m: Map[Str, Int] := Map.empty()
600
+ xs.find(|e| e.first == k).map(|e| e.second)
244
- m.putIfAbsent("a", 1)
245
- m.putIfAbsent("a", 2)
246
- assert m.get("a")! == 1
247
601
 
248
- test "remove deletes an entry and clear empties the map"
249
- m: Map[Str, Int] := Map.empty()
250
- m.set("a", 1)
251
- m.set("b", 2)
252
- m.remove("a")
253
- assert m.has("a") == false
254
- assert m.length() == 1
255
- m.clear()
256
- assert m.isEmpty() == true
257
-
258
- test "removing then re-adding keys keeps lookups correct"
259
- m: Map[Str, Int] := Map.empty()
260
- m.set("a", 1)
261
- m.set("b", 2)
262
- m.remove("a")
263
- m.set("a", 3)
264
- assert m.get("a")! == 3
265
- assert m.get("b")! == 2
266
- assert m.length() == 2
267
-
268
- test "many keys landing in the same bucket still resolve correctly (collision chaining)"
269
- m: Map[Int, Int] := Map.empty()
270
- for i := range 40
271
- m.set(i, i * i)
272
- assert m.length() == 40
273
- for j := range 40
274
- assert m.get(j)! == j * j
275
- m.remove(5)
276
- assert m.has(5) == false
277
- assert m.get(4)! == 16
278
- assert m.get(21)! == 441
279
- assert m.length() == 39
280
-
281
- test "map_collisions_erased: Map[Str, Int] with 500 keys round-trips"
282
- m: Map[Str, Int] := Map.empty()
283
- for i := range 500
284
- m.set("key{i}", i * 3)
285
- assert m.length() == 500
286
- for j := range 500
287
- assert m.get("key{j}")! == j * 3
288
- assert m.has("key500") == false
289
- m.remove("key250")
290
- assert m.length() == 499
291
- assert m.has("key250") == false
292
- assert m.get("key251")! == 753
293
-
294
- test "map_for_entries: for e := range m.entries() visits every entry once"
295
- m: Map[Str, Int] := Map.empty()
296
- m.set("a", 1)
297
- m.set("b", 2)
298
- m.set("c", 3)
299
- es := m.entries()
300
- total := 0.until(es.length()).fold(0, |acc, i| acc + es.at(i).second)
301
- seen := 0.until(es.length()).fold(0, |acc, i| acc + es.at(i).first.length())
302
- assert total == 6
303
- assert seen == 3
304
-
305
- test "map_keys_values_methods: keys() and values() are for sources"
306
- m: Map[Int, Int] := Map.empty()
307
- for i := range 20
308
- m.set(i, i * 10)
309
- ks := m.keys()
310
- vs := m.values()
311
- assert 0.until(ks.length()).fold(0, |acc, i| acc + ks.at(i)) == 190
312
- assert 0.until(vs.length()).fold(0, |acc, i| acc + vs.at(i)) == 1900
313
-
314
- test "values and keys alone"
315
- m: Map[Int, Int] := Map.empty()
316
- m.set(1, 5)
317
- m.set(2, 7)
318
- vs := m.values()
319
- ks := m.keys()
320
- assert 0.until(vs.length()).fold(0, |acc, i| acc + vs.at(i)) == 12
321
- assert 0.until(ks.length()).fold(0, |acc, i| acc + ks.at(i)) == 3
322
-
323
- test "map entries: an if filters, find stops at the first hit"
602
+ fun mapModelStr(xs: List[Pair[Int, Int]]) -> Str =
324
- m: Map[Int, Int] := Map.empty()
325
- for i := range 30
326
- m.set(i, i)
327
- es := m.entries()
328
- n := 0.until(es.length()).fold(0, |acc, i|
603
+ "[" + xs.fold("", |acc, e| if acc == "" then "{e.first} => {e.second}" else "{acc}, {e.first} => {e.second}") + "]"
329
- if es.at(i).second % 2 == 0
330
- acc + 1
331
- else
332
- acc
333
- )
334
- assert n == 15
335
- visited := Array.filled(1, 0)
336
- hit := 0.until(es.length()).find(|i|
337
- visited.set(0, visited.get(0) + 1)
338
- visited.get(0) == 4
339
- )
340
- assert hit.unwrapOr(-1) == 3
341
- assert visited.get(0) == 4
342
604
 
343
- test "empty map iterates zero times"
605
+ # Whether the entry `e` has the key `k`, or both are None.
606
+ fun mapSameKey(e: Option[Pair[Int, Int]], k: Option[Int]) -> Bool = match e
344
- m: Map[Str, Int] := Map.empty()
607
+ None => k.isNone()
345
- assert m.entries().length() == 0
608
+ Some(p) => k.isSome() && p.first == k!
346
609
 
347
- test "init_infers_kv_from_pairs: K and V come from the pairs"
348
- m := ["a" => 1]
349
- m.set("b", 2)
350
- assert m.get("a")! == 1
351
- assert m.get("b")! == 2
352
- assert m.length() == 2
353
-
354
- test "init: two pairs give length 2"
355
- assert ["a" => 1, "b" => 2].length() == 2
356
-
357
- test "init: duplicate key, last wins"
358
- m := ["a" => 1, "a" => 9]
359
- assert m.get("a")! == 9
360
- assert m.length() == 1
361
-
362
- test "empty: Map.empty() is empty"
363
- m: Map[Str, Int] := Map.empty()
364
- assert m.isEmpty() == true
365
-
366
- test "init_many_entries_cross_buckets: 20 pairs all read back"
367
- m := ["0" => 0, "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9, "10" => 10, "11" => 11, "12" => 12, "13" => 13, "14" => 14, "15" => 15, "16" => 16, "17" => 17, "18" => 18, "19" => 19]
368
- assert m.length() == 20
369
- assert m.get("0")! == 0
370
- assert m.get("1")! == 1
371
- assert m.get("2")! == 2
372
- assert m.get("3")! == 3
373
- assert m.get("4")! == 4
374
- assert m.get("5")! == 5
375
- assert m.get("6")! == 6
376
- assert m.get("7")! == 7
377
- assert m.get("8")! == 8
378
- assert m.get("9")! == 9
379
- assert m.get("10")! == 10
380
- assert m.get("11")! == 11
381
- assert m.get("12")! == 12
382
- assert m.get("13")! == 13
383
- assert m.get("14")! == 14
384
- assert m.get("15")! == 15
385
- assert m.get("16")! == 16
386
- assert m.get("17")! == 17
387
- assert m.get("18")! == 18
388
- assert m.get("19")! == 19
389
-
390
- test "init_int_keys"
391
- assert [1 => "x", 2 => "y"].get(2)! == "y"
392
-
393
- test "init_nested_value"
394
- m := ["a" => ["x" => 1]]
395
- assert m.get("a")!.get("x")! == 1
396
-
397
- test "init_negative_int_keys_and_duplicates"
398
- m := [-5 => "a", -17 => "b", -5 => "c"]
399
- assert m.length() == 2
400
- assert m.get(-5)! == "c"
401
- assert m.get(-17)! == "b"
402
-
403
- test "100k inserts, every key found, 100k missing keys absent"
404
- m: Map[Int, Int] := Map.empty()
405
- for i := range 100000
406
- m.set(i, i * 2)
407
- assert m.length() == 100000
408
- bad := 0.until(100000).fold(0, |acc, i|
409
- if m.get(i)! != i * 2
410
- acc + 1
411
- else
412
- acc
413
- )
414
- assert bad == 0
415
- found := 100000.until(200000).fold(0, |acc, i|
416
- if m.has(i)
417
- acc + 1
418
- else
419
- acc
420
- )
421
- assert found == 0
610
+ # The next value of the test's pseudo-random generator.
611
+ fun mapLcg(x: Int) -> Int = {x * 1103515245 + 12345} % 2147483648
612
+
613
+ # A map of `count` pseudo-random keys below `bound` (value `k * 10 + tag`).
614
+ fun mapRandom(seed: Int, count: Int, bound: Int, tag: Int) -> Map[Int, Int] =
615
+ mapRandomFrom(Map.empty(), mapLcg(seed), count, bound, tag)
422
616
 
617
+ fun mapRandomFrom(m: Map[Int, Int], x: Int, count: Int, bound: Int, tag: Int) -> Map[Int, Int] =
618
+ if count <= 0
619
+ m
620
+ else
621
+ k := {x / 7} % bound
622
+ mapRandomFrom(m.with(k, k * 10 + tag), mapLcg(x), count - 1, bound, tag)
623
+
624
+ # The keys from 0 to `n - 1` with `keep(k)`, in the same text form as `keys().toStr()`.
625
+ fun mapKeysWhere(n: Int, keep: fn(Int) -> Bool) -> Str =
626
+ out := Slice[Int]()
627
+ for k := range n
628
+ if keep(k)
629
+ out.push(k)
630
+ out.toStr()
631
+
632
+ # `lo` to `hi - 1` added in order, each with value `2 * key`. A tail call.
633
+ fun mapRange(m: Map[Int, Int], lo: Int, hi: Int) -> Map[Int, Int] =
634
+ if lo >= hi then m else mapRange(m.with(lo, lo * 2), lo + 1, hi)
635
+
636
+ # How many keys from `i` to `hi - 1` read back wrong.
637
+ fun mapBadFrom(m: Map[Int, Int], i: Int, hi: Int, bad: Int) -> Int =
638
+ if i >= hi
639
+ bad
640
+ else if m.getOr(i, -1) != i * 2
641
+ mapBadFrom(m, i + 1, hi, bad + 1)
642
+ else
643
+ mapBadFrom(m, i + 1, hi, bad)
644
+
645
+ # Removes `lo`, `lo + step`, .. below `hi`. A tail call.
646
+ fun mapRemoveFrom(m: Map[Int, Int], lo: Int, hi: Int, step: Int) -> Map[Int, Int] =
647
+ if lo >= hi then m else mapRemoveFrom(m.remove(lo), lo + step, hi, step)
648
+
423
- test "delete half, reinsert, tombstones are reused and lookups stay right"
649
+ # The state of the random-operations test: the map, the model and the generator.
650
+ struct MapTestRun(mut m: Map[Int, Int], mut model: List[Pair[Int, Int]], mut x: Int, mut bad: Int)
651
+
652
+ # A key type with its own order: by length, then by text.
653
+ struct MapTestWord(text: Str) =
654
+ fun compare(self, o: MapTestWord) -> Int =
655
+ if self.text.length() != o.text.length() then self.text.length().compare(o.text.length()) else self.text.compare(o.text)
656
+
657
+ fun toStr(self) -> Str = self.text
658
+
659
+ test "an empty map"
424
660
  m: Map[Int, Int] := Map.empty()
425
- for i := range 20000
426
- m.set(i, i)
427
- for i := range 10000
428
- m.remove(i * 2)
429
- assert m.length() == 10000
430
- bad := 0.until(20000).fold(0, |acc, i|
431
- if m.has(i) != {i % 2 == 1}
432
- acc + 1
433
- else
434
- acc
661
+ assert m.isEmpty() && m.length() == 0 && m.height() == 0
662
+ assert m.get(1).isNone() && !m.has(1) && m.getOr(1, 7) == 7
663
+ assert m.min().isNone() && m.max().isNone()
664
+ assert m.removeMin().isEmpty() && m.removeMax().isEmpty()
665
+ assert m.below(1).isNone() && m.atMost(1).isNone() && m.above(1).isNone() && m.atLeast(1).isNone()
666
+ assert m.entryAt(0).isNone() && m.indexOf(1).isNone()
667
+ assert m.entries().length() == 0 && m.keys().length() == 0 && m.values().length() == 0
668
+ assert m.toStr() == "[]"
669
+ assert m.remove(1).isEmpty()
670
+ assert m.split(3).first.isEmpty() && m.split(3).second.isEmpty()
671
+ assert m.union(m).isEmpty() && m.intersection(m).isEmpty() && m.difference(m).isEmpty()
672
+ assert m.fold(0, |a, k, v| a + 1) == 0
673
+ assert m == Map[Int, Int]()
674
+ assert mapValid(m)
675
+
676
+ test "with, get, has, getOr and set"
677
+ m := Map[Str, Int]().with("b", 2).with("a", 1).set("c", 3)
678
+ assert m.length() == 3
679
+ assert m.get("a")! == 1 && m.get("c")! == 3 && m.get("z").isNone()
680
+ assert m.has("b") && !m.has("bb")
681
+ assert m.getOr("b", 0) == 2 && m.getOr("q", -1) == -1
682
+ r := m.with("a", 10)
683
+ assert r.length() == 3 && r.get("a")! == 10
684
+ assert m.get("a")! == 1
685
+
686
+ test "old versions are unchanged after every kind of update"
687
+ v1 := [1 => 10, 2 => 20, 3 => 30, 4 => 40, 5 => 50]
688
+ v2 := v1.with(6, 60)
689
+ v3 := v2.remove(1).with(3, 0)
690
+ v4 := v3.union([9 => 90]).difference([2 => 0])
691
+ v5 := v4.update(4, |x| x + 1).upsert(7, 70, |x| x).alter(5, |o| None).putIfAbsent(8, 80)
692
+ v6 := v5.filter(|k, v| k % 2 == 0).map(|v| v * 2).removeMin().removeMax()
693
+ p := v4.split(5)
694
+ assert v1.toStr() == "[1 => 10, 2 => 20, 3 => 30, 4 => 40, 5 => 50]"
695
+ assert v2.toStr() == "[1 => 10, 2 => 20, 3 => 30, 4 => 40, 5 => 50, 6 => 60]"
696
+ assert v3.toStr() == "[2 => 20, 3 => 0, 4 => 40, 5 => 50, 6 => 60]"
697
+ assert v4.toStr() == "[3 => 0, 4 => 40, 5 => 50, 6 => 60, 9 => 90]"
698
+ assert v5.toStr() == "[3 => 0, 4 => 41, 6 => 60, 7 => 70, 8 => 80, 9 => 90]"
699
+ assert v6.toStr() == "[6 => 120]"
700
+ assert p.first.toStr() == "[3 => 0, 4 => 40]" && p.second.toStr() == "[6 => 60, 9 => 90]"
701
+ assert mapValid(v1) && mapValid(v2) && mapValid(v3) && mapValid(v4) && mapValid(v5) && mapValid(v6)
702
+
703
+ test "literals: later duplicate keys win, values may be maps"
704
+ m := ["a" => 1, "a" => 9, "b" => 2]
705
+ assert m.length() == 2 && m.get("a")! == 9
706
+ n := ["x" => [1 => "one"], "y" => Map[Int, Str]()]
707
+ assert n.get("x")!.get(1)! == "one" && n.get("y")!.isEmpty()
708
+ big := ["0" => 0, "1" => 1, "2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, "7" => 7, "8" => 8, "9" => 9, "10" => 10, "11" => 11, "12" => 12, "13" => 13, "14" => 14, "15" => 15, "16" => 16, "17" => 17, "18" => 18, "19" => 19]
709
+ assert big.length() == 20
710
+ assert 0.until(20).find(|i| big.get("{i}")! != i).isNone()
711
+ assert big.keys().join(",") == "0,1,10,11,12,13,14,15,16,17,18,19,2,3,4,5,6,7,8,9"
712
+ neg := [-5 => "a", -17 => "b", -5 => "c"]
713
+ assert neg.toStr() == "[-17 => b, -5 => c]"
714
+
715
+ test "putIfAbsent, upsert, update and alter"
716
+ m := [1 => 10]
717
+ assert m.putIfAbsent(1, 99).get(1)! == 10 && m.putIfAbsent(2, 20).get(2)! == 20
718
+ assert m.upsert(1, 0, |v| v + 1).get(1)! == 11 && m.upsert(2, 0, |v| v + 1).get(2)! == 0
719
+ assert m.update(1, |v| v * 3).get(1)! == 30 && m.update(5, |v| v * 3).length() == 1
720
+ assert m.alter(1, |o| o.map(|v| v + 5)).get(1)! == 15
721
+ assert m.alter(1, |o| None).isEmpty()
722
+ assert m.alter(3, |o| Some(o.unwrapOr(0) + 3)).get(3)! == 3
723
+ start: Map[Str, Int] := Map.empty()
724
+ counts := ["x", "y", "x", "x"].fold(start, |acc, w| acc.upsert(w, 1, |n| n + 1))
725
+ assert counts.toStr() == "[x => 3, y => 1]"
726
+
727
+ test "remove a leaf, an inner node, the root, missing keys and everything"
728
+ t := Map.fromList([50, 30, 70, 20, 40, 60, 80, 10, 35, 45, 65].map(|k| Pair(first: k, second: k * 10)))
729
+ a := t.remove(10)
730
+ assert !a.has(10) && a.length() == 10 && mapValid(a)
731
+ b := t.remove(30)
732
+ assert b.keys().toStr() == "[10,20,35,40,45,50,60,65,70,80]" && mapValid(b)
733
+ assert mapValid(t.remove(50)) && !t.remove(50).has(50)
734
+ assert t.remove(99).length() == 11 && t.remove(99) == t
735
+ e := t.keys().fold(t, |acc, k|
736
+ next := acc.remove(k)
737
+ assert mapValid(next)
738
+ next
435
739
  )
740
+ assert e.isEmpty() && t.length() == 11
741
+
742
+ test "min, max, removeMin, removeMax and the neighbours of a key"
743
+ m := [40 => 4, 10 => 1, 30 => 3, 20 => 2]
744
+ assert m.min()!.first == 10 && m.min()!.second == 1 && m.max()!.first == 40
745
+ assert m.removeMin().keys().toStr() == "[20,30,40]" && m.removeMax().keys().toStr() == "[10,20,30]"
746
+ assert m.below(30)!.first == 20 && m.below(31)!.first == 30 && m.below(10).isNone()
747
+ assert m.atMost(30)!.first == 30 && m.atMost(9).isNone() && m.atMost(99)!.first == 40
748
+ assert m.above(30)!.first == 40 && m.above(29)!.first == 30 && m.above(40).isNone()
749
+ assert m.atLeast(30)!.first == 30 && m.atLeast(41).isNone() && m.atLeast(-5)!.second == 1
750
+
751
+ test "neighbours agree with a scan over pseudo-random maps"
752
+ for seed := range 1.to(8)
753
+ m := mapRandom(seed, 120, 300, 0)
754
+ ks := m.keys()
755
+ bad := -2.until(303).fold(0, |b, q|
756
+ lt := ks.filter(|k| k < q).last()
757
+ le := ks.filter(|k| k <= q).last()
758
+ gt := ks.filter(|k| k > q).first()
759
+ ge := ks.filter(|k| k >= q).first()
760
+ ok := mapSameKey(m.below(q), lt) && mapSameKey(m.atMost(q), le) && mapSameKey(m.above(q), gt) && mapSameKey(m.atLeast(q), ge)
761
+ if ok then b else b + 1
762
+ )
436
- assert bad == 0
763
+ assert bad == 0
764
+
765
+ test "entryAt and indexOf count positions in key order"
766
+ m := [30 => 3, 10 => 1, 50 => 5, 20 => 2, 40 => 4]
767
+ assert m.entryAt(0)!.first == 10 && m.entryAt(2)!.second == 3 && m.entryAt(4)!.first == 50
768
+ assert m.entryAt(5).isNone() && m.entryAt(-1).isNone()
769
+ assert m.indexOf(10)! == 0 && m.indexOf(40)! == 3 && m.indexOf(35).isNone()
437
- for i := range 10000
770
+ for i := range 5
771
+ assert m.indexOf(m.entryAt(i)!.first)! == i
772
+
773
+ test "split leaves out the key and keeps both halves valid"
438
- m.set(i * 2, i * 2 + 1)
774
+ t := mapRange(Map.empty(), 1, 10)
775
+ p := t.split(4)
776
+ assert p.first.keys().toStr() == "[1,2,3]" && p.second.keys().toStr() == "[5,6,7,8,9]"
777
+ assert mapValid(p.first) && mapValid(p.second)
778
+ assert t.split(0).first.isEmpty() && t.split(0).second.length() == 9
779
+ assert t.split(100).first.length() == 9 && t.split(100).second.isEmpty()
780
+ s := [2 => 0, 4 => 0, 6 => 0].split(5)
781
+ assert s.first.keys().toStr() == "[2,4]" && s.second.keys().toStr() == "[6]"
782
+
783
+ test "union, unionWith, intersection and difference; values come from self"
784
+ a := [1 => 10, 2 => 20, 3 => 30, 4 => 40, 5 => 50]
785
+ b := [4 => 4, 5 => 5, 6 => 6, 7 => 7]
786
+ assert a.union(b).toStr() == "[1 => 10, 2 => 20, 3 => 30, 4 => 40, 5 => 50, 6 => 6, 7 => 7]"
439
- assert m.length() == 20000
787
+ assert b.union(a).get(5)! == 5
788
+ assert a.unionWith(b, |x, y| x + y).toStr() == "[1 => 10, 2 => 20, 3 => 30, 4 => 44, 5 => 55, 6 => 6, 7 => 7]"
789
+ assert a.intersection(b).toStr() == "[4 => 40, 5 => 50]" && b.intersection(a).get(5)! == 5
790
+ assert a.difference(b).keys().toStr() == "[1,2,3]" && b.difference(a).keys().toStr() == "[6,7]"
791
+ e: Map[Int, Int] := Map.empty()
792
+ assert a.union(e) == a && e.union(a) == a && a.intersection(e).isEmpty() && a.difference(e) == a && e.difference(a).isEmpty()
793
+
794
+ test "set operations agree with a filter over pseudo-random maps, and stay balanced"
795
+ for seed := range 1.to(12)
796
+ a := mapRandom(seed, 300, 400, 1)
797
+ b := mapRandom(seed * 7919, 200, 400, 2)
798
+ u := a.union(b)
799
+ i := a.intersection(b)
800
+ d := a.difference(b)
801
+ w := a.unionWith(b, |x, y| x + y)
802
+ assert mapValid(u) && mapValid(i) && mapValid(d) && mapValid(w)
803
+ assert u.keys().toStr() == mapKeysWhere(400, |k| a.has(k) || b.has(k))
804
+ assert i.keys().toStr() == mapKeysWhere(400, |k| a.has(k) && b.has(k))
805
+ assert d.keys().toStr() == mapKeysWhere(400, |k| a.has(k) && !b.has(k))
806
+ assert u.all(|k, v| v == a.getOr(k, b.getOr(k, -1)))
807
+ assert w.all(|k, v| v == a.getOr(k, 0) + b.getOr(k, 0))
808
+ p := a.split(200)
809
+ assert mapValid(p.first) && mapValid(p.second)
810
+ assert p.first.keys().toStr() == mapKeysWhere(200, |k| a.has(k))
811
+ big := mapRandom(7, 3000, 100000, 0)
812
+ small := [5 => 0, 500 => 0, 50000 => 0, 99999 => 0, 123456 => 0]
813
+ assert mapValid(big.union(small)) && mapValid(small.union(big)) && mapValid(big.intersection(small))
814
+ assert mapValid(big.difference(small)) && mapValid(small.difference(big))
815
+ assert big.difference(small).length() + big.intersection(small).length() == big.length()
816
+
817
+ test "walks go in key order: fold, each, keys, values, entries, for, toStr"
818
+ m := [3 => "c", 1 => "a", 2 => "b"]
819
+ assert m.fold("", |acc, k, v| acc + "{k}{v}") == "1a2b3c"
820
+ seen := Slice[Int]()
821
+ m.each(|k, v| seen.push(k))
822
+ assert seen.toStr() == "[1,2,3]"
823
+ assert m.keys().toStr() == "[1,2,3]" && m.values().join("") == "abc"
824
+ assert m.entries().at(1).first == 2 && m.entries().at(1).second == "b"
825
+ got := Slice[Str]()
826
+ for e := range m
827
+ got.push("{e.first}={e.second}")
828
+ assert got.join(" ") == "1=a 2=b 3=c"
829
+ assert m.toStr() == "[1 => a, 2 => b, 3 => c]"
830
+ assert m.any(|k, v| v == "b") && !m.any(|k, v| k > 3) && m.all(|k, v| k > 0) && !m.all(|k, v| k > 1)
831
+
832
+ test "map keeps the shape, filter rebalances"
833
+ m := mapRange(Map.empty(), 0, 1000)
834
+ doubled := m.map(|v| v + 1)
835
+ assert doubled.length() == 1000 && doubled.get(10)! == 21 && doubled.height() == m.height()
836
+ odd := m.filter(|k, v| k % 2 == 1)
837
+ assert odd.length() == 500 && mapValid(odd) && odd.min()!.first == 1
838
+ few := m.filter(|k, v| k < 3 || k > 996)
839
+ assert few.keys().toStr() == "[0,1,2,997,998,999]" && mapValid(few)
840
+ strs: Map[Int, Str] := m.map(|v| "{v}")
841
+ assert strs.get(7)! == "14"
842
+
843
+ test "fromSlice and fromList: sorted input is built directly, any input works"
440
- bad2 := 0.until(20000).fold(0, |acc, i|
844
+ sorted := 0.until(1000).fold(Slice[Pair[Int, Int]](), |xs, i|
441
- if m.get(i)! != {if i % 2 == 0 then i + 1 else i}
845
+ xs.push(Pair(first: i, second: i * 2))
442
- acc + 1
443
- else
846
+ xs
444
- acc
445
847
  )
446
- assert bad2 == 0
447
-
448
- test "repeated set/remove of a few keys never grows the table without bound"
449
- m: Map[Int, Int] := Map.empty()
450
- for i := range 100000
451
- m.set(i % 7, i)
452
- m.remove(i % 7)
453
- assert m.length() == 0
454
- m.set(3, 9)
455
- assert m.get(3)! == 9
456
- assert m.index.length() == 16
457
-
458
- test "growth past several doublings"
459
- m: Map[Int, Int] := Map.empty()
460
- assert m.index.length() == 16
461
- for i := range 1000
462
- m.set(i, i)
463
- assert m.index.length() == 2048
464
- assert m.length() == 1000
465
-
466
- test "Map[Str, Int] with Buffer-built keys"
467
- m: Map[Str, Int] := Map.empty()
468
- for i := range 2000
469
- b := Buffer()
470
- b.write("k")
471
- b.write(i.toStr())
472
- m.set(b.toStr(), i)
473
- assert m.length() == 2000
474
- assert m.get("k1999")! == 1999
475
- assert m.has("k2000") == false
476
-
477
- test "iteration is insertion order, skipping removed entries"
478
- m: Map[Int, Int] := Map.empty()
479
- m.set(30, 1)
480
- m.set(10, 2)
481
- m.set(20, 3)
482
- m.set(10, 4)
483
- m.remove(30)
484
- m.set(30, 5)
485
- es := m.entries()
486
- order := 0.until(es.length()).fold("", |acc, i| "{acc}{es.at(i).first}={es.at(i).second} ")
487
- assert order == "10=4 20=3 30=5 "
488
-
489
- test "clear then reuse"
490
- m: Map[Int, Int] := Map.empty()
491
- for i := range 100
492
- m.set(i, i)
493
- m.clear()
494
- assert m.length() == 0
495
- assert m.has(5) == false
496
- m.set(5, 1)
497
- assert m.get(5)! == 1
848
+ a := Map.fromSlice(sorted)
849
+ assert a.length() == 1000 && mapValid(a) && mapBadFrom(a, 0, 1000, 0) == 0
850
+ b := Map.fromList([5, 1, 4, 1, 3].map(|k| Pair(first: k, second: k)))
851
+ assert b.keys().toStr() == "[1,3,4,5]" && mapValid(b)
852
+ dup := Map.fromList([Pair(first: 1, second: 1), Pair(first: 1, second: 2), Pair(first: 2, second: 3)])
853
+ assert dup.toStr() == "[1 => 2, 2 => 3]"
854
+ e: Map[Int, Int] := Map.fromSlice(Slice[Pair[Int, Int]]())
855
+ assert e.isEmpty()
856
+
857
+ test "== compares entries, not shapes"
858
+ a := mapRange(Map.empty(), 0, 100)
859
+ b := Map.fromSlice(a.entries())
860
+ assert a == b
861
+ assert a != b.with(5, 0) && a != b.remove(5) && a != b.with(500, 1000)
862
+ assert ["a" => 1] == ["a" => 1] && ["a" => 1] != ["a" => 2]
863
+
864
+ test "pseudo-random operations agree with a sorted-list model, with snapshots"
865
+ run := MapTestRun(m: Map.empty(), model: Nil, x: 2024, bad: 0)
866
+ snap := MapTestRun(m: Map.empty(), model: Nil, x: 0, bad: 0)
867
+ for i := range 4000
868
+ run.x = mapLcg(run.x)
869
+ k := run.x % 500
870
+ op := {run.x / 500} % 10
871
+ if op < 5
872
+ run.m = run.m.with(k, i)
873
+ run.model = mapModelWith(run.model, k, i)
874
+ else if op < 8
875
+ run.m = run.m.remove(k)
876
+ run.model = mapModelWithout(run.model, k)
877
+ else if op == 8
878
+ run.m = run.m.upsert(k, i, |v| v + 1)
879
+ run.model = mapModelWith(run.model, k, match mapModelGet(run.model, k)
880
+ Some(v) => v + 1
881
+ None => i
882
+ )
883
+ else
884
+ if run.m.getOr(k, -1) != mapModelGet(run.model, k).unwrapOr(-1)
885
+ run.bad = run.bad + 1
886
+ if run.m.length() != run.model.length()
887
+ run.bad = run.bad + 1
888
+ if i % 100 == 0
889
+ if !mapValid(run.m) || run.m.toStr() != mapModelStr(run.model)
890
+ run.bad = run.bad + 1
891
+ if i == 2000
892
+ snap.m = run.m
893
+ snap.model = run.model
894
+ assert run.bad == 0
895
+ assert mapValid(run.m) && run.m.toStr() == mapModelStr(run.model)
896
+ assert mapValid(snap.m) && snap.m.toStr() == mapModelStr(snap.model)
897
+
898
+ test "keys of every std kind: Str, Float, Bool, Byte and a struct with compare"
899
+ s := ["pear" => 1, "apple" => 2, "fig" => 3, "" => 4, "applesauce" => 5]
900
+ assert s.keys().join(",") == ",apple,applesauce,fig,pear"
901
+ nan := 0.0 / 0.0
902
+ f := Map[Float, Int]().with(1.5, 1).with(-0.0, 2).with(0.0, 3).with(nan, 4).with(-1.0 / 0.0, 5).with(1.0 / 0.0, 6).with(nan, 7)
903
+ assert f.length() == 5
904
+ assert f.get(-0.0)! == 3 && f.get(0.0)! == 3
905
+ assert f.get(nan)! == 7 && f.max()!.second == 7 && f.min()!.second == 5
906
+ assert f.remove(nan).length() == 4 && !f.remove(nan).has(nan)
907
+ b := [true => "t", false => "f"]
908
+ assert b.keys().toStr() == "[false,true]"
909
+ y := Map[Byte, Int]().with(Byte(200), 1).with(Byte(3), 2)
910
+ assert y.min()!.second == 2
911
+ w := [MapTestWord(text: "ccc") => 1, MapTestWord(text: "b") => 2, MapTestWord(text: "aa") => 3, MapTestWord(text: "a") => 4]
912
+ assert w.keys().map(|k| k.text).join(",") == "a,b,aa,ccc"
913
+ assert w.get(MapTestWord(text: "aa"))! == 3
914
+
915
+ test "10,000 ascending keys stay balanced"
916
+ t := mapRange(Map.empty(), 0, 10000)
917
+ assert t.length() == 10000 && mapValid(t) && t.height() <= 2 * 14 + 2
918
+ assert mapBadFrom(t, 0, 10000, 0) == 0
919
+ u := mapRemoveFrom(t, 0, 10000, 2)
920
+ assert u.length() == 5000 && mapValid(u) && u.min()!.first == 1 && u.indexOf(5001)! == 2500
921
+ assert t.length() == 10000 && t.min()!.first == 0
922
+
923
+ test "1,000,000 inserts, lookups, walks and removals in constant stack"
924
+ t := mapRange(Map.empty(), 0, 1000000)
925
+ assert t.length() == 1000000
926
+ assert t.height() <= 2 * 20 + 2
927
+ assert mapBadFrom(t, 0, 1000000, 0) == 0
928
+ assert t.fold(0, |acc, k, v| acc + v) == 999999000000
929
+ assert t.entries().length() == 1000000
930
+ assert mapCheckedSize(t) == 1000000
931
+ u := mapRemoveFrom(t, 0, 1000000, 1)
932
+ assert u.isEmpty()
933
+ assert t.max()!.first == 999999
934
+
935
+ test "the invariant checker rejects wrong sizes, unbalanced nodes and unordered keys"
936
+ e: Map[Int, Int] := MapTip
937
+ assert mapCheckedSize(MapBin(size: 5, key: 1, value: 10, left: e, right: e)) == -1
938
+ chain := Map.bin(1, 10, e, Map.bin(2, 20, e, Map.bin(3, 30, e, e)))
939
+ assert mapCheckedSize(chain) == -1
940
+ assert mapCheckedSize(Map.bin(2, 20, Map.bin(1, 10, e, e), e)) == 2
941
+ assert !mapValid(Map.bin(5, 50, e, Map.bin(1, 10, e, e)))
942
+
943
+ test "groupBy keeps each group in order, the groups in key order"
944
+ words := ["bb", "a", "cc", "ddd", "e"].toSlice()
945
+ g := words.groupBy(|w| w.length())
946
+ assert g.keys().toStr() == "[1,2,3]"
947
+ assert g.get(2)!.join(",") == "bb,cc" && g.get(1)!.join(",") == "a,e"
std/Set.plum CHANGED
@@ -2,68 +2,191 @@ module std
2
2
 
3
3
  import std/Map
4
4
  import std/Slice
5
+ import std/List
5
6
  import std/Int
6
7
  import std/Float
8
+ import std/Str
9
+ import std/Buffer
10
+ import std/Pair
11
+ import std/Option
7
12
 
8
- # A set of unique `T`s, a thin layer over `Map[T, Bool]` (so `T` needs the same
13
+ # A persistent ordered set of `T`s: the keys of a `Map[T, Bool]` (see std/Map), so `T` needs
9
- # duck-typed `hash() -> Int` and `==` that `Map`'s keys do). `Set[Int]()`
14
+ # the same `compare(self, o) -> Int` that `Map`'s keys do, and every operation has the
15
+ # `Map` operation's cost. Nothing changes in place: `s.add(x)` returns a new set and `s`
10
- # builds an empty one.
16
+ # stays as it was. Members come out in ascending order. `Set[Int]()` is the empty set.
11
17
  struct Set[T](map: Map[T, Bool]) =
12
18
 
13
19
  fun init() -> Set[T] =
14
20
  Set(map: Map.empty())
15
21
 
22
+ fun empty() -> Set[T] =
23
+ Set(map: Map.empty())
24
+
25
+ # The set of `xs`' members. O(n) when they already strictly ascend.
26
+ fun fromSlice(xs: Slice[T]) -> Set[T] =
27
+ Set(map: Map.fromSlice(xs.map(|x| Pair(first: x, second: true))))
28
+
29
+ fun fromList(xs: List[T]) -> Set[T] =
30
+ Set.fromSlice(xs.toSlice())
31
+
16
- # Adds `v`; adding a value already present changes nothing.
32
+ # The set with `v` in it (the same members when `v` already is).
17
- fun add(self, v: T) -> Unit =
33
+ fun add(self, v: T) -> Set[T] =
18
- self.map.set(v, true)
34
+ Set(map: self.map.with(v, true))
35
+
36
+ # The set without `v`.
37
+ fun remove(self, v: T) -> Set[T] =
38
+ Set(map: self.map.remove(v))
19
39
 
20
40
  fun has(self, v: T) -> Bool =
21
41
  self.map.has(v)
22
42
 
23
- fun remove(self, v: T) -> Unit =
24
- self.map.remove(v)
25
-
26
43
  fun length(self) -> Int =
27
44
  self.map.length()
28
45
 
29
46
  fun isEmpty(self) -> Bool =
30
47
  self.map.isEmpty()
31
48
 
49
+ # The smallest member, or None.
50
+ fun min(self) -> Option[T] = self.map.min().map(|e| e.first)
51
+
52
+ # The largest member, or None.
53
+ fun max(self) -> Option[T] = self.map.max().map(|e| e.first)
54
+
55
+ fun removeMin(self) -> Set[T] = Set(map: self.map.removeMin())
56
+
57
+ fun removeMax(self) -> Set[T] = Set(map: self.map.removeMax())
58
+
59
+ # The largest member before `v`, at or before `v`, after `v`, at or after `v`.
60
+ fun below(self, v: T) -> Option[T] = self.map.below(v).map(|e| e.first)
61
+
62
+ fun atMost(self, v: T) -> Option[T] = self.map.atMost(v).map(|e| e.first)
63
+
64
+ fun above(self, v: T) -> Option[T] = self.map.above(v).map(|e| e.first)
65
+
66
+ fun atLeast(self, v: T) -> Option[T] = self.map.atLeast(v).map(|e| e.first)
67
+
68
+ # The `i`-th smallest member (from 0), or None out of range.
69
+ fun at(self, i: Int) -> Option[T] = self.map.entryAt(i).map(|e| e.first)
70
+
71
+ # The members before `v` (`first`) and after `v` (`second`).
32
- fun clear(self) -> Unit =
72
+ fun split(self, v: T) -> Pair[Set[T], Set[T]] =
33
- self.map.clear()
73
+ p := self.map.split(v)
74
+ Pair(first: Set(map: p.first), second: Set(map: p.second))
75
+
76
+ fun union(self, o: Set[T]) -> Set[T] = Set(map: self.map.union(o.map))
77
+
78
+ fun intersection(self, o: Set[T]) -> Set[T] = Set(map: self.map.intersection(o.map))
34
79
 
80
+ fun difference(self, o: Set[T]) -> Set[T] = Set(map: self.map.difference(o.map))
81
+
82
+ # True when every member of `self` is in `o`.
83
+ fun isSubsetOf(self, o: Set[T]) -> Bool =
84
+ self.length() <= o.length() && self.map.all(|k, v| o.has(k))
85
+
86
+ # `f(..f(f(acc, x0), x1).., xn)`, ascending.
87
+ fun fold[A](self, acc: A, f: fn(A, T) -> A) -> A =
88
+ self.map.fold(acc, |a, k, v| f(a, k))
89
+
90
+ fun each(self, f: fn(T) -> Unit) -> Unit =
91
+ self.map.each(|k, v| f(k))
92
+
93
+ # The members for which `keep` holds.
94
+ fun filter(self, keep: fn(T) -> Bool) -> Set[T] =
95
+ Set(map: self.map.filter(|k, v| keep(k)))
96
+
97
+ fun any(self, pred: fn(T) -> Bool) -> Bool = self.map.any(|k, v| pred(k))
98
+
99
+ fun all(self, pred: fn(T) -> Bool) -> Bool = self.map.all(|k, v| pred(k))
100
+
35
- # Every member, in insertion order, as a new `Slice` (was `toList`).
101
+ # Every member, ascending, as a new `Slice`.
36
102
  fun toSlice(self) -> Slice[T] =
37
103
  self.map.keys()
38
104
 
105
+ # The loop protocol: `for x := range s` visits the members in ascending order.
106
+ fun next(self) -> Option[Pair[T, Set[T]]] = match self.map.min()
107
+ None => None
108
+ Some(e) => Some(Pair(first: e.first, second: Set(map: self.map.removeMin())))
109
+
110
+ # The same members (`s == t`).
111
+ fun eq(self, o: Set[T]) -> Bool =
112
+ if self.length() != o.length()
113
+ false
114
+ else
115
+ a := self.toSlice()
116
+ b := o.toSlice()
117
+ 0.until(a.length()).find(|i| a.at(i).compare(b.at(i)) != 0).isNone()
118
+
119
+ # The members, ascending: `[1, 2, 3]`.
120
+ fun toStr(self) -> Str =
121
+ buf := Buffer()
122
+ buf.write("[")
123
+ self.map.each(|k, v|
124
+ if buf.length() > 1
125
+ buf.write(", ")
126
+ buf.write(k.toStr())
127
+ )
128
+ buf.write("]")
129
+ buf.toStr()
130
+
131
+ # A set of `count` pseudo-random members below `bound`.
132
+ fun setRandom(x: Int, count: Int, bound: Int, acc: Set[Int]) -> Set[Int] =
133
+ if count <= 0 then acc else setRandom({x * 1103515245 + 12345} % 2147483648, count - 1, bound, acc.add({x / 7} % bound))
134
+
39
- test "set_dedup: adding duplicates keeps one copy"
135
+ # The members from 0 to `n - 1` with `keep(x)`, as text.
136
+ fun setWhere(n: Int, keep: fn(Int) -> Bool) -> Str =
40
- s := Set[Int]()
137
+ out := Slice[Int]()
138
+ for x := range n
139
+ if keep(x)
140
+ out.push(x)
141
+ out.toStr()
142
+
143
+ # A set in a `mut` field, so a loop can update it.
144
+ struct SetTestRun(mut s: Set[Int])
145
+
146
+ test "add keeps one copy, remove and has; the old set stays as it was"
147
+ s := Set[Int]().add(3).add(1).add(3).add(2)
148
+ assert s.length() == 3 && s.has(3) && !s.has(10)
149
+ t := s.remove(1).remove(99)
150
+ assert t.toStr() == "[2, 3]" && s.toStr() == "[1, 2, 3]"
151
+ assert Set[Int]().isEmpty() && !s.isEmpty() && Set[Str]().toStr() == "[]"
152
+
153
+ test "dedup in a loop, through a mut field"
154
+ run := SetTestRun(s: Set.empty())
41
155
  for i := range 100
42
- s.add(i % 10)
156
+ run.s = run.s.add(i % 10)
157
+ assert run.s.length() == 10 && run.s.toSlice().toStr() == "[0,1,2,3,4,5,6,7,8,9]"
158
+
159
+ test "order: min, max, neighbours, at, split, removeMin, removeMax"
160
+ s := Set.fromList([40, 10, 30, 20])
161
+ assert s.min()! == 10 && s.max()! == 40
162
+ assert s.removeMin().toStr() == "[20, 30, 40]" && s.removeMax().toStr() == "[10, 20, 30]"
163
+ assert s.below(30)! == 20 && s.atMost(30)! == 30 && s.above(30)! == 40 && s.atLeast(31)! == 40 && s.above(40).isNone()
164
+ assert s.at(1)! == 20 && s.at(4).isNone()
165
+ p := s.split(25)
166
+ assert p.first.toStr() == "[10, 20]" && p.second.toStr() == "[30, 40]"
167
+
168
+ test "union, intersection, difference and isSubsetOf agree with a filter"
43
- assert s.length() == 10
169
+ for seed := range 1.to(10)
44
- assert s.has(3)
170
+ a := setRandom(seed, 200, 300, Set.empty())
171
+ b := setRandom(seed * 7919, 150, 300, Set.empty())
172
+ assert a.union(b).toSlice().toStr() == setWhere(300, |x| a.has(x) || b.has(x))
173
+ assert a.intersection(b).toSlice().toStr() == setWhere(300, |x| a.has(x) && b.has(x))
174
+ assert a.difference(b).toSlice().toStr() == setWhere(300, |x| a.has(x) && !b.has(x))
175
+ assert a.intersection(b).isSubsetOf(a) && a.isSubsetOf(a.union(b))
176
+ assert a.difference(b).isSubsetOf(b) == a.difference(b).isEmpty()
177
+
178
+ test "walks: fold, each, filter, any, all, for, toSlice, fromSlice, =="
179
+ s := Set.fromSlice([5, 3, 9, 1].toSlice())
45
- assert s.has(10) == false
180
+ assert s.fold(0, |acc, x| acc * 10 + x) == 1359
46
- s.add(3)
47
- assert s.length() == 10
48
-
49
- test "remove and clear"
50
- s := Set[Int]()
181
+ seen := Slice[Int]()
51
- s.add(1)
52
- s.add(2)
53
- s.remove(1)
54
- assert s.has(1) == false
55
- assert s.has(2)
182
+ s.each(|x| seen.push(x))
56
- assert s.length() == 1
57
- s.remove(99)
58
- assert s.length() == 1
59
- s.clear()
60
- assert s.isEmpty()
61
-
62
- test "toSlice returns each member once"
183
+ assert seen.toStr() == "[1,3,5,9]"
184
+ assert s.filter(|x| x > 3).toStr() == "[5, 9]"
185
+ assert s.any(|x| x == 9) && !s.any(|x| x == 2) && s.all(|x| x % 2 == 1)
63
- s := Set[Int]()
186
+ got := Slice[Int]()
187
+ for x := range s
64
- s.add(5)
188
+ got.push(x)
65
- s.add(5)
66
- s.add(7)
67
- l := s.toSlice()
68
- assert l.length() == 2
69
- assert l.get(0)! + l.get(1)! == 12
189
+ assert got.toStr() == "[1,3,5,9]"
190
+ assert s == Set[Int]().add(9).add(1).add(5).add(3) && s != s.add(4) && s != s.remove(1)
191
+ w := Set.fromList(["b", "a", "c", "a"])
192
+ assert w.toSlice().join("") == "abc"
std/collections/functional/FAvlTree.plum CHANGED
@@ -194,7 +194,7 @@ enum FAvlBranch[K, V] =
194
194
  FAvlNode(nk, nv, _, l, r) => l.collect(Cons(head: Pair(first: nk, second: nv), tail: r.collect(acc)))
195
195
 
196
196
  # ---------------------------------------------------------------------------
197
- # Test helpers. Tests may use loops, `mut` fields and std's mutable `Map` as the
197
+ # Test helpers. Tests may use loops, `mut` fields and std's `Map` as the
198
198
  # reference model; the structure above may not.
199
199
  # ---------------------------------------------------------------------------
200
200
 
@@ -246,7 +246,7 @@ fun fAvlRange(t: FAvlTree[Int, Int], lo: Int, hi: Int) -> FAvlTree[Int, Int] =
246
246
  fAvlRange(t.insert(lo, lo), lo + 1, hi)
247
247
 
248
248
  # The state of the random-operations test: the tree, the generator and the model.
249
- struct FAvlTestRun(mut t: FAvlTree[Int, Int], mut x: Int, present: Map[Int, Int])
249
+ struct FAvlTestRun(mut t: FAvlTree[Int, Int], mut x: Int, mut present: Map[Int, Int])
250
250
 
251
251
  test "an empty tree"
252
252
  t := fAvlInts()
@@ -367,10 +367,10 @@ test "invariants hold through pseudo-random inserts and removes"
367
367
  k := run.x % 500
368
368
  if {run.x / 1000} % 3 == 0
369
369
  run.t = run.t.remove(k)
370
- run.present.remove(k)
370
+ run.present = run.present.remove(k)
371
371
  else
372
372
  run.t = run.t.insert(k, i)
373
- run.present.set(k, i)
373
+ run.present = run.present.with(k, i)
374
374
  if i % 50 == 0
375
375
  assert fAvlValid(run.t)
376
376
  assert fAvlValid(run.t)
std/collections/functional/FBvh.plum CHANGED
@@ -247,6 +247,9 @@ struct FBvhRng(mut x: Int) =
247
247
  # A counter for test loops.
248
248
  struct FBvhTally(mut n: Int)
249
249
 
250
+ # The pairs seen so far: a persistent `Set` in a `mut` field, so a loop can update it.
251
+ struct FBvhSeen(mut s: Set[Int])
252
+
250
253
  # The depth of `node` (nodes on the longest root-to-leaf path: ceil(log2 n) + 1 when
251
254
  # balanced) if every branch's box is exactly the union of its children's boxes and
252
255
  # contains both, and no branch has an empty child; else -1.
@@ -334,14 +337,15 @@ fun fBvhBruteRay(items: Slice[Pair[Aabb, Int]], o: Vec2, d: Vec2, maxT: Float) -
334
337
 
335
338
  fun fBvhCheckPairs(items: Slice[Pair[Aabb, Int]], tree: FBvh[Int]) -> Unit =
336
339
  n := items.length()
337
- got := Set[Int]()
340
+ seen := FBvhSeen(s: Set[Int]())
338
341
  for p := range tree.pairs()
339
342
  assert p.first != p.second
340
343
  a := p.first.min(p.second)
341
344
  b := p.first.max(p.second)
342
345
  key := a * n + b
343
- assert !got.has(key)
346
+ assert !seen.s.has(key)
347
+ seen.s = seen.s.add(key)
344
- got.add(key)
348
+ got := seen.s
345
349
  count := FBvhTally(n: 0)
346
350
  for i := range n
347
351
  for j := range {i + 1}.until(n)
std/collections/functional/FHamt.plum CHANGED
@@ -276,7 +276,7 @@ fun fHamtRemoveAt[T](xs: List[T], pos: Int) -> List[T] = match xs
276
276
  if pos == 0 then t else Cons(head: h, tail: fHamtRemoveAt(t, pos - 1))
277
277
 
278
278
  # ---------------------------------------------------------------------------
279
- # Test helpers. Tests may use loops, `mut` fields and std's mutable `Map` as the
279
+ # Test helpers. Tests may use loops, `mut` fields and std's `Map` as the
280
280
  # reference model; the structure above may not.
281
281
  # ---------------------------------------------------------------------------
282
282
 
@@ -294,6 +294,9 @@ struct FHamtBadKey(id: Int) =
294
294
  # The state a randomized test threads from step to step.
295
295
  struct FHamtSim[K](mut h: FHamt[K, Int], mut snap: FHamt[K, Int], mut x: Int, mut bad: Int)
296
296
 
297
+ # The reference model: a persistent `Map` in a `mut` field, so a loop can update it.
298
+ struct FHamtModel(mut m: Map[Int, Int])
299
+
297
300
  fun fHamtLcg(x: Int) -> Int =
298
301
  {x * 1103515245 + 12345} % 2147483648
299
302
 
@@ -532,8 +535,8 @@ test "collision nodes mixed with ordinary keys"
532
535
 
533
536
  test "12,000 pseudo-random operations agree with Map, with invariants and a snapshot"
534
537
  s := FHamtSim(h: fHamtInts(), snap: fHamtInts(), x: 2024, bad: 0)
535
- m: Map[Int, Int] := Map.empty()
538
+ model := FHamtModel(m: Map.empty())
536
- snapVals: Map[Int, Int] := Map.empty()
539
+ snapModel := FHamtModel(m: Map.empty())
537
540
  for i := range 12000
538
541
  s.x = fHamtLcg(s.x)
539
542
  k := s.x % 3000
@@ -541,20 +544,22 @@ test "12,000 pseudo-random operations agree with Map, with invariants and a snap
541
544
  op := s.x % 10
542
545
  if op < 6
543
546
  s.h = s.h.set(k, i)
544
- m.set(k, i)
547
+ model.m = model.m.with(k, i)
545
548
  else if op < 9
546
549
  s.h = s.h.remove(k)
547
- m.remove(k)
550
+ model.m = model.m.remove(k)
548
- else if s.h.get(k).unwrapOr(-1) != m.get(k).unwrapOr(-1)
551
+ else if s.h.get(k).unwrapOr(-1) != model.m.get(k).unwrapOr(-1)
549
552
  s.bad = s.bad + 1
550
- if s.h.length() != m.length()
553
+ if s.h.length() != model.m.length()
551
554
  s.bad = s.bad + 1
552
555
  if i % 1000 == 0 && !fHamtValid(s.h)
553
556
  s.bad = s.bad + 1
554
557
  if i == 6000
555
558
  s.snap = s.h
556
559
  for j := range 3000
557
- snapVals.set(j, m.get(j).unwrapOr(-1))
560
+ snapModel.m = snapModel.m.with(j, model.m.get(j).unwrapOr(-1))
561
+ m := model.m
562
+ snapVals := snapModel.m
558
563
  assert s.bad == 0
559
564
  assert fHamtValid(s.h)
560
565
  for k := range 3000
@@ -571,21 +576,22 @@ test "12,000 pseudo-random operations agree with Map, with invariants and a snap
571
576
  test "pseudo-random ops on colliding keys agree with Map"
572
577
  h0: FHamt[FHamtBadKey, Int] := FHamt.empty()
573
578
  s := FHamtSim(h: h0, snap: h0, x: 7, bad: 0)
574
- m: Map[Int, Int] := Map.empty()
579
+ model := FHamtModel(m: Map.empty())
575
580
  for i := range 3000
576
581
  s.x = fHamtLcg(s.x)
577
582
  k := s.x % 60
578
583
  s.x = fHamtLcg(s.x)
579
584
  if s.x % 3 == 0
580
585
  s.h = s.h.remove(FHamtBadKey(id: k))
581
- m.remove(k)
586
+ model.m = model.m.remove(k)
582
587
  else
583
588
  s.h = s.h.set(FHamtBadKey(id: k), i)
584
- m.set(k, i)
589
+ model.m = model.m.with(k, i)
585
- if s.h.length() != m.length()
590
+ if s.h.length() != model.m.length()
586
591
  s.bad = s.bad + 1
587
592
  if i % 100 == 0 && !fHamtValid(s.h)
588
593
  s.bad = s.bad + 1
594
+ m := model.m
589
595
  assert s.bad == 0
590
596
  for k := range 60
591
597
  if s.h.get(FHamtBadKey(id: k)).unwrapOr(-1) != m.get(k).unwrapOr(-1)
std/collections/functional/FRadixTree.plum CHANGED
@@ -350,7 +350,7 @@ enum FRadixEdges[V] =
350
350
  FRadixEdge(lab, _, rest) => rest.labelList(Cons(head: lab, tail: acc))
351
351
 
352
352
  # ---------------------------------------------------------------------------
353
- # Test helpers. Tests may use loops over `mut` fields and std's mutable `Map` and
353
+ # Test helpers. Tests may use loops over `mut` fields and std's `Map` and
354
354
  # `Slice` as the reference model; the structure above may not.
355
355
  # ---------------------------------------------------------------------------
356
356
 
@@ -463,6 +463,9 @@ fun fRadixGrow(t: FRadixTree[Int], s: Str, i: Int) -> FRadixTree[Int] =
463
463
  # and the number of failed checks.
464
464
  struct FRadixRun(mut t: FRadixTree[Int], mut tr: FTrie[Int], mut s: Int, mut bad: Int)
465
465
 
466
+ # The reference model: a persistent `Map` in a `mut` field, so a loop can update it.
467
+ struct FRadixModel(mut m: Map[Str, Int])
468
+
466
469
  test "an empty tree"
467
470
  t: FRadixTree[Int] := FRadixTree.empty()
468
471
  assert t.isEmpty()
@@ -647,20 +650,21 @@ test "invariants_after_random_ops: pseudo-random inserts and removes match an FT
647
650
  empty: FRadixTree[Int] := FRadixTree.empty()
648
651
  emptyTrie: FTrie[Int] := FTrie.empty()
649
652
  run := FRadixRun(t: empty, tr: emptyTrie, s: 7, bad: 0)
650
- m: Map[Str, Int] := Map.empty()
653
+ model := FRadixModel(m: Map.empty())
651
654
  for step := range 4000
652
655
  run.s = fRadixLcg(run.s)
653
656
  w := fRadixWord(run.s)
654
657
  if {run.s / 1024} % 3 == 0
655
658
  run.t = run.t.remove(w)
656
659
  run.tr = run.tr.remove(w)
657
- m.remove(w)
660
+ model.m = model.m.remove(w)
658
661
  else
659
662
  run.t = run.t.insert(w, step)
660
663
  run.tr = run.tr.insert(w, step)
661
- m.set(w, step)
664
+ model.m = model.m.with(w, step)
662
665
  if step % 250 == 0 && !fRadixValid(run.t)
663
666
  run.bad = run.bad + 1
667
+ m := model.m
664
668
  t := run.t
665
669
  tr := run.tr
666
670
  assert run.bad == 0
std/collections/functional/FRedBlackTree.plum CHANGED
@@ -253,7 +253,7 @@ enum FRbBranch[K, V] =
253
253
  FRbNode(_, nk, nv, l, r) => l.collect(Cons(head: Pair(first: nk, second: nv), tail: r.collect(acc)))
254
254
 
255
255
  # ---------------------------------------------------------------------------
256
- # Test helpers. Tests may use loops, `mut` fields and std's mutable `Map` as the
256
+ # Test helpers. Tests may use loops, `mut` fields and std's `Map` as the
257
257
  # reference model; the structure above may not.
258
258
  # ---------------------------------------------------------------------------
259
259
 
@@ -334,7 +334,7 @@ fun fRbRemoveAllValid(t: FRedBlackTree[Int, Int], ks: List[Int]) -> Bool = match
334
334
  fRbRemoveAllValid(u, rest)
335
335
 
336
336
  # The state of the random-operations test: the tree, the generator and the model.
337
- struct FRbTestRun(mut t: FRedBlackTree[Int, Int], mut x: Int, m: Map[Int, Int])
337
+ struct FRbTestRun(mut t: FRedBlackTree[Int, Int], mut x: Int, mut m: Map[Int, Int])
338
338
 
339
339
  test "an empty tree"
340
340
  t := fRbInts()
@@ -475,10 +475,10 @@ test "invariants hold through pseudo-random inserts and removes"
475
475
  k := run.x % 500
476
476
  if run.x % 3 == 0
477
477
  run.t = run.t.remove(k)
478
- run.m.remove(k)
478
+ run.m = run.m.remove(k)
479
479
  else
480
480
  run.t = run.t.insert(k, i)
481
- run.m.set(k, i)
481
+ run.m = run.m.with(k, i)
482
482
  assert fRbValid(run.t)
483
483
  assert fRbValid(run.t)
484
484
  assert run.t.length() == run.m.length()
std/collections/functional/FTreap.plum CHANGED
@@ -308,7 +308,7 @@ enum FTreapNode[K, V] =
308
308
  FTreapBranch(nk, nv, _, _, l, r) => l.collect(Cons(head: Pair(first: nk, second: nv), tail: r.collect(acc)))
309
309
 
310
310
  # ---------------------------------------------------------------------------
311
- # Test helpers. Tests may use loops, `mut` fields and std's mutable `Map` as the
311
+ # Test helpers. Tests may use loops, `mut` fields and std's `Map` as the
312
312
  # reference model; the structure above may not.
313
313
  # ---------------------------------------------------------------------------
314
314
 
@@ -366,15 +366,18 @@ fun fTreapValid(t: FTreap[Int, Int]) -> Bool =
366
366
  fun fTreapModelKeys(m: Map[Int, Int]) -> Str =
367
367
  m.keys().sort(|a, b| a < b).toStr()
368
368
 
369
+ # A brute-force model: a persistent `Map` in a `mut` field, so a loop can update it.
370
+ struct FTreapModel(mut m: Map[Int, Int])
371
+
369
372
  # A pseudo-random treap of keys below `bound` (from an LCG seeded by `seed`),
370
373
  # mirrored into `model`, each value `k * 10 + tag`.
371
- fun fTreapRandom(seed: Int, count: Int, bound: Int, tag: Int, model: Map[Int, Int]) -> FTreap[Int, Int] =
374
+ fun fTreapRandom(seed: Int, count: Int, bound: Int, tag: Int, model: FTreapModel) -> FTreap[Int, Int] =
372
375
  s := FTreapSim(t: fTreapInts(), x: seed)
373
376
  for i := range count
374
377
  s.x = {s.x * 1103515245 + 12345} % 2147483648
375
378
  k := {s.x / 7} % bound
376
379
  s.t = s.t.insert(k, k * 10 + tag)
377
- model.set(k, k * 10 + tag)
380
+ model.m = model.m.with(k, k * 10 + tag)
378
381
  s.t
379
382
 
380
383
  test "an empty treap"
@@ -544,18 +547,19 @@ test "old versions are unchanged after insert, remove, split and set operations"
544
547
 
545
548
  test "invariants hold through pseudo-random inserts and removes"
546
549
  s := FTreapSim(t: fTreapInts(), x: 12345)
547
- present: Map[Int, Int] := Map.empty()
550
+ model := FTreapModel(m: Map.empty())
548
551
  for i := range 3000
549
552
  s.x = {s.x * 1103515245 + 12345} % 2147483648
550
553
  k := s.x % 500
551
554
  if {s.x / 1000} % 3 == 0
552
555
  s.t = s.t.remove(k)
553
- present.remove(k)
556
+ model.m = model.m.remove(k)
554
557
  else
555
558
  s.t = s.t.insert(k, i)
556
- present.set(k, i)
559
+ model.m = model.m.with(k, i)
557
560
  if i % 50 == 0
558
561
  assert fTreapValid(s.t)
562
+ present := model.m
559
563
  t := s.t
560
564
  assert fTreapValid(t)
561
565
  assert t.length() == present.length()
@@ -565,25 +569,30 @@ test "invariants hold through pseudo-random inserts and removes"
565
569
 
566
570
  test "set operations match a brute-force model on random maps"
567
571
  for seed := range 1.until(6)
568
- ma: Map[Int, Int] := Map.empty()
572
+ maModel := FTreapModel(m: Map.empty())
569
- mb: Map[Int, Int] := Map.empty()
573
+ mbModel := FTreapModel(m: Map.empty())
570
- a := fTreapRandom(seed, 300, 400, 1, ma)
574
+ a := fTreapRandom(seed, 300, 400, 1, maModel)
571
- b := fTreapRandom(seed * 7919, 200, 400, 2, mb)
575
+ b := fTreapRandom(seed * 7919, 200, 400, 2, mbModel)
576
+ ma := maModel.m
577
+ mb := mbModel.m
572
578
  u := a.union(b)
573
579
  i := a.intersection(b)
574
580
  d := a.difference(b)
575
581
  assert fTreapValid(u) && fTreapValid(i) && fTreapValid(d)
576
- mu: Map[Int, Int] := Map.empty()
582
+ muModel := FTreapModel(m: Map.empty())
577
- mi: Map[Int, Int] := Map.empty()
583
+ miModel := FTreapModel(m: Map.empty())
578
- md: Map[Int, Int] := Map.empty()
584
+ mdModel := FTreapModel(m: Map.empty())
579
585
  for k := range mb.keys()
580
- mu.set(k, mb.get(k)!)
586
+ muModel.m = muModel.m.with(k, mb.get(k)!)
581
587
  for k := range ma.keys()
582
- mu.set(k, ma.get(k)!)
588
+ muModel.m = muModel.m.with(k, ma.get(k)!)
583
589
  if mb.has(k)
584
- mi.set(k, ma.get(k)!)
590
+ miModel.m = miModel.m.with(k, ma.get(k)!)
585
591
  else
586
- md.set(k, ma.get(k)!)
592
+ mdModel.m = mdModel.m.with(k, ma.get(k)!)
593
+ mu := muModel.m
594
+ mi := miModel.m
595
+ md := mdModel.m
587
596
  assert u.length() == mu.length() && i.length() == mi.length() && d.length() == md.length()
588
597
  for k := range mu.keys()
589
598
  assert u.get(k)! == mu.get(k)!
std/collections/functional/FTrie.plum CHANGED
@@ -297,7 +297,7 @@ enum FTrieKids[V] =
297
297
  FTrieKid(kb, _, rest) => rest.byteList(Cons(head: kb, tail: acc))
298
298
 
299
299
  # ---------------------------------------------------------------------------
300
- # Test helpers. Tests may use loops over `mut` fields and std's mutable `Map` and
300
+ # Test helpers. Tests may use loops over `mut` fields and std's `Map` and
301
301
  # `Slice` as the reference model; the structure above may not.
302
302
  # ---------------------------------------------------------------------------
303
303
 
@@ -388,6 +388,9 @@ fun fTrieRemoveRange(t: FTrie[Int], i: Int, n: Int) -> FTrie[Int] =
388
388
  # number of failed checks.
389
389
  struct FTrieRun(mut t: FTrie[Int], mut s: Int, mut bad: Int)
390
390
 
391
+ # The reference model: a persistent `Map` in a `mut` field, so a loop can update it.
392
+ struct FTrieModel(mut m: Map[Str, Int])
393
+
391
394
  test "an empty trie"
392
395
  t: FTrie[Int] := FTrie.empty()
393
396
  assert t.isEmpty()
@@ -537,18 +540,19 @@ test "the kids list stays sorted and shares its tail"
537
540
  test "invariants_after_random_ops: pseudo-random inserts and removes match a Map"
538
541
  empty: FTrie[Int] := FTrie.empty()
539
542
  run := FTrieRun(t: empty, s: 42, bad: 0)
540
- m: Map[Str, Int] := Map.empty()
543
+ model := FTrieModel(m: Map.empty())
541
544
  for step := range 3000
542
545
  run.s = fTrieLcg(run.s)
543
546
  w := fTrieWord(run.s)
544
547
  if {run.s / 1024} % 3 == 0
545
548
  run.t = run.t.remove(w)
546
- m.remove(w)
549
+ model.m = model.m.remove(w)
547
550
  else
548
551
  run.t = run.t.insert(w, step)
549
- m.set(w, step)
552
+ model.m = model.m.with(w, step)
550
553
  if step % 250 == 0 && !fTrieValid(run.t)
551
554
  run.bad = run.bad + 1
555
+ m := model.m
552
556
  t := run.t
553
557
  assert run.bad == 0
554
558
  assert fTrieValid(t)
std/collections/functional/FWeightBalancedTree.plum CHANGED
@@ -376,7 +376,7 @@ enum FWbBranch[K, V] =
376
376
  FWbNode(_, nk, nv, l, r) => l.collect(Cons(head: Pair(first: nk, second: nv), tail: r.collect(acc)))
377
377
 
378
378
  # ---------------------------------------------------------------------------
379
- # Test helpers. Tests may use loops, `mut` fields and std's mutable `Map` as the
379
+ # Test helpers. Tests may use loops, `mut` fields and std's `Map` as the
380
380
  # reference model; the structure above may not.
381
381
  # ---------------------------------------------------------------------------
382
382
 
@@ -469,7 +469,7 @@ fun fWbRemoveEvens(t: FWeightBalancedTree[Int, Int], i: Int, hi: Int) -> FWeight
469
469
  fWbRemoveEvens(t.remove(i), i + 2, hi)
470
470
 
471
471
  # The state of the random-operations test: the tree, the generator and the model.
472
- struct FWbTestRun(mut t: FWeightBalancedTree[Int, Int], mut x: Int, m: Map[Int, Int])
472
+ struct FWbTestRun(mut t: FWeightBalancedTree[Int, Int], mut x: Int, mut m: Map[Int, Int])
473
473
 
474
474
  test "an empty tree"
475
475
  t := fWbInts()
@@ -669,10 +669,10 @@ test "invariants hold through pseudo-random inserts and removes"
669
669
  k := run.x % 500
670
670
  if run.x % 3 == 0
671
671
  run.t = run.t.remove(k)
672
- run.m.remove(k)
672
+ run.m = run.m.remove(k)
673
673
  else
674
674
  run.t = run.t.insert(k, i)
675
- run.m.set(k, i)
675
+ run.m = run.m.with(k, i)
676
676
  if i % 20 == 0
677
677
  assert fWbValid(run.t)
678
678
  assert fWbValid(run.t)
std/game/scene/SceneTree.plum CHANGED
@@ -10,6 +10,7 @@ import std/Slice
10
10
  import std/Array
11
11
  import std/Map
12
12
  import std/Set
13
+ import std/Pair
13
14
  import std/math
14
15
  import std/Io
15
16
  import std/ref
@@ -255,7 +256,7 @@ struct TreeScan(mut top: Int, mut ok: Bool) =
255
256
  # A batch of commands as a walk uses them: the ids to drop, and the nodes to add under
256
257
  # each parent id, in the order pushed. The walk asks about every actor, so beside the set
257
258
  # and the map it keeps a bitset of each (one bit per id up to the batch's largest): most
258
- # answers are a shift and a mask, and only an actor with spawns does a hash lookup. Ids
259
+ # answers are a shift and a mask, and only an actor with spawns does a map lookup. Ids
259
260
  # below 0 or from 2^22 up make that batch use the set and the map alone. A batch with no
260
261
  # `Kill` and no `Spawn` (most ticks) has neither: it builds nothing.
261
262
  struct TreeWalk[M](
@@ -271,23 +272,28 @@ struct TreeWalk[M](
271
272
 
272
273
  # `of` for a batch with a `Kill` or a `Spawn`.
273
274
  fun ofTree(cmds: Slice[Cmd[M]]) -> TreeWalk[M] =
274
- kills := Set[Int]()
275
- spawns: Map[Int, Slice[FRoseTree[Actor[M]]]] := Map.empty()
275
+ noSpawns: Map[Int, Slice[FRoseTree[Actor[M]]]] := Map.empty()
276
+ start: Pair[Set[Int], Map[Int, Slice[FRoseTree[Actor[M]]]]] := Pair(first: Set[Int](), second: noSpawns)
276
277
  scan := TreeScan(top: 0, ok: true)
277
- for c := range cmds
278
+ found := cmds.fold(start, |acc, c|
278
279
  match c
279
280
  Kill(id) =>
280
- kills.add(id)
281
281
  scan.see(id)
282
+ Pair(first: acc.first.add(id), second: acc.second)
282
283
  Spawn(parent, node) =>
283
284
  scan.see(parent)
284
- if Some(xs) := spawns.get(parent)
285
+ match acc.second.get(parent)
286
+ Some(xs) =>
285
- xs.push(node)
287
+ xs.push(node)
286
- else
288
+ acc
289
+ None =>
287
- ys := Slice[FRoseTree[Actor[M]]]()
290
+ ys := Slice[FRoseTree[Actor[M]]]()
288
- ys.push(node)
291
+ ys.push(node)
289
- spawns.set(parent, ys)
292
+ Pair(first: acc.first, second: acc.second.with(parent, ys))
290
- _ => Unit
293
+ _ => acc
294
+ )
295
+ kills := found.first
296
+ spawns := found.second
291
297
  words := if scan.ok && {kills.length() > 0 || spawns.length() > 0} then scan.top / 64 + 1 else 0
292
298
  killBits := Array[Int]().resize(words)
293
299
  spawnBits := Array[Int]().resize(words)
std/http.plum CHANGED
@@ -68,17 +68,16 @@ fun encodeHeaders(headers: Map[Str, Str]) -> Str =
68
68
  # The reverse of `encodeHeaders`, for the response headers `rawHttpRequest`
69
69
  # packs into its result.
70
70
  fun decodeHeaders(raw: Str) -> Map[Str, Str] =
71
- result := emptyHeaders()
72
71
  if raw == ""
73
- result
72
+ emptyHeaders()
74
73
  else
75
- for line := range raw.split("\n", 0)
74
+ raw.split("\n", 0).fold(emptyHeaders(), |result, line|
76
75
  idx := line.indexOf(": ")
77
76
  if idx >= 0
78
- key := line.sub(0, idx)
79
- val := line.sub(idx + 2, line.length())
77
+ result.with(line.sub(0, idx), line.sub(idx + 2, line.length()))
80
- result.set(key, val)
78
+ else
81
- result
79
+ result
80
+ )
82
81
 
83
82
  # Performs a single HTTP request and waits for the full response. Fails
84
83
  # only for a transport-level problem (DNS failure, connection refused, TLS
@@ -120,15 +119,12 @@ fun patch(io: Io, url: Str, headers: Map[Str, Str], body: Str) -> Result[Respons
120
119
 
121
120
  # Convenience wrapper: sends `body` as a JSON `Str`, adding a
122
121
  # `Content-Type: application/json` header, and parses the response back as
123
- # JSON via `Response.json()`.
122
+ # JSON via `Response.json()`. The caller's `headers` stay as they were.
124
123
  fun postJson(io: Io, url: Str, headers: Map[Str, Str], body: Json) -> Result[Response, HttpError] =
125
- headers.set("Content-Type", "application/json")
124
+ post(io, url, headers.with("Content-Type", "application/json"), body.toStr())
126
- post(io, url, headers, body.toStr())
127
125
 
128
126
  test "encodeHeaders/decodeHeaders round-trip a header map"
129
- h := emptyHeaders()
130
- h.set("Content-Type", "application/json")
127
+ h := emptyHeaders().with("Content-Type", "application/json").with("Accept", "*/*")
131
- h.set("Accept", "*/*")
132
128
  decoded := decodeHeaders(encodeHeaders(h))
133
129
  assert decoded.get("Content-Type")! == "application/json"
134
130
  assert decoded.get("Accept")! == "*/*"
tests/core/math_edges.plum CHANGED
@@ -140,12 +140,10 @@ test "Float.hash uses the bits, and Floats that are == hash the same"
140
140
  assert Inf.hash() != {-Inf}.hash()
141
141
 
142
142
  test "Map with Float keys in (-1, 1)"
143
- m: Map[Float, Int] := Map.empty()
143
+ e: Map[Float, Int] := Map.empty()
144
- m.set(0.1f, 1)
145
- m.set(0.2f, 2)
146
- m.set(-0.5f, 3)
144
+ m := e.with(0.1f, 1).with(0.2f, 2).with(-0.5f, 3).with(0.0f, 4)
147
- m.set(0.0f, 4)
148
145
  assert m.length() == 4
146
+ assert m.keys().toStr() == [-0.5f, 0.0f, 0.1f, 0.2f].toSlice().toStr()
149
147
  assert m.get(0.1f).unwrapOr(0) == 1
150
148
  assert m.get(0.2f).unwrapOr(0) == 2
151
149
  assert m.get(-0.5f).unwrapOr(0) == 3
tests/fbip/aliasing.plum CHANGED
@@ -130,9 +130,9 @@ test "stored in a slice by a helper then updated"
130
130
  test "stored in a map then updated"
131
131
  m: Map[Int, Cell] := Map.empty()
132
132
  a := Cell(label: "a", n: 0)
133
- m.set(1, a)
133
+ m2 := m.with(1, a)
134
134
  b := a.bumped()
135
- assert m.get(1)!.n == 0
135
+ assert m2.get(1)!.n == 0
136
136
  assert b.n == 1
137
137
 
138
138
  test "stored in a field then updated"
tests/fbip_probes/map_set_get.plum CHANGED
@@ -5,14 +5,15 @@ import std/Option
5
5
  import std/Time
6
6
  import std/Io
7
7
 
8
+ # FBIP probe: n Map.with calls threaded through a fold (each map is unique, though cell reuse
8
- # FBIP probe: n Map.set calls, then n Map.get calls; the sum of the values read is the result.
9
+ # doesn't reach Map's generic methods yet), then n Map.get calls; the sum of the values read
10
+ # is the result.
9
11
 
10
12
  fun size() -> Int = 100000
11
13
 
12
14
  fun run(n: Int) -> Int =
13
- m: Map[Int, Int] := Map.empty()
15
+ start: Map[Int, Int] := Map.empty()
14
- for i := range n
15
- m.set(i, i * 2)
16
+ m := 0.until(n).fold(start, |acc, i| acc.with(i, i * 2))
16
17
  0.until(n).fold(0, |total, i| total + m.get(i).unwrapOr(0))
17
18
 
18
19
  fun main(io: Io) =
tests/std/collections.plum CHANGED
@@ -93,29 +93,26 @@ test "find stops at the first hit"
93
93
  )
94
94
  assert found! == 998 && calls.get(0) == 3
95
95
 
96
- test "groupBy keeps each group in order and the groups by first key"
96
+ test "groupBy keeps each group in order and the groups in key order"
97
97
  words := ["bb", "a", "cc", "ddd", "e"].toSlice()
98
98
  g := words.groupBy(|w| w.length())
99
99
  assert g.length() == 3
100
100
  assert g.get(2)!.join(",") == "bb,cc"
101
101
  assert g.get(1)!.join(",") == "a,e"
102
- assert g.keys().toStr() == "[2,1,3]"
102
+ assert g.keys().toStr() == "[1,2,3]"
103
103
  assert Slice[Int]().groupBy(|x| x).isEmpty()
104
104
 
105
105
  test "Map[K, V]() is an empty map, like Slice[T]() and Set[T]()"
106
106
  m := Map[Str, Int]()
107
107
  assert m.isEmpty()
108
- m.set("a", 1)
109
- assert m.get("a")! == 1
108
+ assert m.with("a", 1).get("a")! == 1
109
+ assert m.isEmpty()
110
110
  n := Map[Int, Slice[Int]]()
111
111
  assert n.length() == 0
112
112
 
113
- test "Set.toSlice gives the members in insertion order"
113
+ test "Set.toSlice gives the members in ascending order"
114
- s := Set[Int]()
114
+ s := Set[Int]().add(3).add(1).add(3)
115
- s.add(3)
116
- s.add(1)
117
- s.add(3)
118
- assert s.toSlice().toStr() == "[3,1]"
115
+ assert s.toSlice().toStr() == "[1,3]"
119
116
 
120
117
  test "Heap.by and Heap.byKey"
121
118
  h: Heap[Int] := Heap.by(|a, b| a < b)