plum

#treesitter#compiler#wasm

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

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


4e91020 — Peter John 2026-11-10T12:22:35+05:30
Map: note the similar balanced trees and how they differ
Files changed (1) hide show
  1. std/Map.plum +15 -0
std/Map.plum CHANGED
@@ -36,6 +36,21 @@ import std/List
36
36
  # `fromSlice` O(n) on keys already strictly ascending, else O(n log n).
37
37
  # Stack: every walk is O(log n) deep (lookups are tail calls), so a 1,000,000-entry map is
38
38
  # fine.
39
+ #
40
+ # Very similar structures: all four below are balanced binary search trees that give the
41
+ # same ordered-map operations at the same O(log n) costs, and differ only in how they keep
42
+ # the tree balanced. Map is the one std uses; reach for another only to study it.
43
+ # - weight-balanced tree: the very structure Map is (it was ported from std's
44
+ # WeightBalancedTree); balances on subtree sizes, which is what gives O(1) `length`
45
+ # and O(log n) `entryAt`/`indexOf` for free.
46
+ # - AVL tree: balances on subtree heights (the two sides differ by at most 1). Slightly
47
+ # shallower, so lookups compare a little less; it stores a height, not a size, so
48
+ # `length` and positional lookups need an extra field.
49
+ # - red-black tree: balances by colouring nodes. Fewer rebalancing steps per update,
50
+ # up to 2 log2(n) deep; deletion is the hardest of the four to write persistently.
51
+ # - treap: balances by a random priority per node (a heap on priorities, a search tree
52
+ # on keys). The simplest code, balanced only in expectation, and it needs a seed, so
53
+ # two maps with the same entries can have different shapes.
39
54
  enum Map[K, V] =
40
55
  | MapTip
41
56
  | MapBin(size: Int, key: K, value: V, left: Map[K, V], right: Map[K, V])