diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index ea5be3fe..269c63b2 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -140,6 +140,7 @@ "sum_squares.ml": 385, "tree_depth.ml": 4, "triangle.ml": 11, + "trie.ml": 6, "triangle_div.ml": 120, "twosum.ml": 5, "union_find.ml": 4, diff --git a/lib/ocaml/baseline/trie.ml b/lib/ocaml/baseline/trie.ml new file mode 100644 index 00000000..60f0358f --- /dev/null +++ b/lib/ocaml/baseline/trie.ml @@ -0,0 +1,36 @@ +type trie = { mutable terminal : bool; mutable children : (char * trie) list } + +let make_trie () = { terminal = false; children = [] } + +let rec lookup_child cs c = + match cs with + | [] -> None + | (k, v) :: rest -> if k = c then Some v else lookup_child rest c + +let rec insert t s i = + if i = String.length s then t.terminal <- true + else + let c = s.[i] in + match lookup_child t.children c with + | Some child -> insert child s (i + 1) + | None -> + let nc = make_trie () in + t.children <- (c, nc) :: t.children; + insert nc s (i + 1) + +let rec contains t s i = + if i = String.length s then t.terminal + else + let c = s.[i] in + match lookup_child t.children c with + | Some child -> contains child s (i + 1) + | None -> false + +;; + +let t = make_trie () in +List.iter (fun w -> insert t w 0) ["cat"; "car"; "card"; "cart"; "dog"; "doge"]; +let count = ref 0 in +List.iter (fun w -> if contains t w 0 then count := !count + 1) + ["cat"; "car"; "ca"; "card"; "cart"; "dog"; "doge"; "dogs"; "x"]; +!count diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 5f4211cc..4e42583d 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,16 @@ _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 — trie.ml baseline (prefix tree, 6 of 9 + word lookups match). Mutable record `{ terminal; children }` with + `children : (char * trie) list`; insert recurses down character + by character, mutating children list when a path is missing. + Insert {cat, car, card, cart, dog, doge}; lookup {cat, car, ca, + card, cart, dog, doge, dogs, x}. The 6 hits are exactly the + inserted words; "ca", "dogs", "x" miss. + Tests recursive type definition with self-reference, mutable + records, `match … | Some / None` over option, pattern with + `(k, v) :: rest` tuple destructuring. 146 baseline programs total. - 2026-05-10 Phase 5.1 — count_inversions.ml baseline (count inversions of [|8;4;2;1;3;5;7;6|] = 12, via merge-sort). Modified merge sort: when right element is taken, accumulate `mid - i + 1`