From bcaa41d1aec594b4f33376883114386f7d1d7582 Mon Sep 17 00:00:00 2001 From: giles Date: Sun, 10 May 2026 03:59:56 +0000 Subject: [PATCH] ocaml: phase 5.1 union_find.ml baseline (10 nodes, 6 unions, 4 components) Disjoint-set union with path compression: let make_uf n = Array.init n (fun i -> i) let rec find p x = if p.(x) = x then x else begin let r = find p p.(x) in p.(x) <- r; r end let union p x y = let rx = find p x in let ry = find p y in if rx <> ry then p.(rx) <- ry After unioning (0,1), (2,3), (4,5), (6,7), (0,2), (4,6): {0,1,2,3} {4,5,6,7} {8} {9} --> 4 components. Tests Array.init with closure, recursive find, in-place .(i)<-r. 139 baseline programs total. --- lib/ocaml/baseline/expected.json | 1 + lib/ocaml/baseline/union_find.ml | 33 ++++++++++++++++++++++++++++++++ plans/ocaml-on-sx.md | 7 +++++++ 3 files changed, 41 insertions(+) create mode 100644 lib/ocaml/baseline/union_find.ml diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 08741db4..e6661889 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -136,6 +136,7 @@ "triangle.ml": 11, "triangle_div.ml": 120, "twosum.ml": 5, + "union_find.ml": 4, "unique_set.ml": 9, "validate.ml": 417, "word_count.ml": 3 diff --git a/lib/ocaml/baseline/union_find.ml b/lib/ocaml/baseline/union_find.ml new file mode 100644 index 00000000..391ac720 --- /dev/null +++ b/lib/ocaml/baseline/union_find.ml @@ -0,0 +1,33 @@ +let make_uf n = Array.init n (fun i -> i) + +let rec find p x = + if p.(x) = x then x + else begin + let r = find p p.(x) in + p.(x) <- r; + r + end + +let union p x y = + let rx = find p x in + let ry = find p y in + if rx <> ry then p.(rx) <- ry + +let count_components p n = + let c = ref 0 in + for i = 0 to n - 1 do + if find p i = i then c := !c + 1 + done; + !c + +;; + +let n = 10 in +let p = make_uf n in +union p 0 1; +union p 2 3; +union p 4 5; +union p 6 7; +union p 0 2; +union p 4 6; +count_components p n diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index a0861bdc..153bd948 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,13 @@ _Newest first._ binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree`) with insert + in-order traversal. Tests parametric ADT, recursive match, List.append, List.fold_left. +- 2026-05-10 Phase 5.1 — union_find.ml baseline (disjoint-set union + on n=10 with 6 unions → 4 components). Path-compressing find: + recursively walks parent links, splices subtree onto root in place. + After unioning {0-1, 2-3, 0-2} → {0,1,2,3}; {4-5, 6-7, 4-6} → + {4,5,6,7}; 8 and 9 remain singletons → 4 components. Tests + Array.init, in-place .(i)<-r mutation, recursive find with + path compression. 139 baseline programs total. - 2026-05-10 Phase 5.1 — quickselect.ml baseline (Hoare quickselect median of [7;2;9;1;5;6;3;8;4] = 5). Lomuto partition scheme: recursively partitions on the last element as pivot, narrows the