From 0858986877c49c6c72396bbf793e431ad9a8757b Mon Sep 17 00:00:00 2001 From: giles Date: Fri, 8 May 2026 17:52:49 +0000 Subject: [PATCH] ocaml: phase 5.1 btree.ml baseline (13/13 pass) Polymorphic binary search tree with insert + in-order traversal. Exercises parametric ADT (type 'a tree = Leaf | Node of 'a * 'a tree * 'a tree), recursive match, List.append, List.fold_left. --- lib/ocaml/baseline/btree.ml | 25 +++++++++++++++++++++++++ lib/ocaml/baseline/expected.json | 1 + plans/ocaml-on-sx.md | 4 ++++ 3 files changed, 30 insertions(+) create mode 100644 lib/ocaml/baseline/btree.ml diff --git a/lib/ocaml/baseline/btree.ml b/lib/ocaml/baseline/btree.ml new file mode 100644 index 00000000..19dad101 --- /dev/null +++ b/lib/ocaml/baseline/btree.ml @@ -0,0 +1,25 @@ +(* Baseline: binary search tree with insert + in-order traversal *) +type 'a tree = + | Leaf + | Node of 'a * 'a tree * 'a tree +;; + +let rec insert x t = + match t with + | Leaf -> Node (x, Leaf, Leaf) + | Node (v, l, r) -> + if x < v then Node (v, insert x l, r) + else if x > v then Node (v, l, insert x r) + else t +;; + +let rec inorder t = + match t with + | Leaf -> [] + | Node (v, l, r) -> List.append (inorder l) (v :: inorder r) +;; + +let from_list xs = List.fold_left (fun t x -> insert x t) Leaf xs ;; + +let t = from_list [5; 3; 8; 1; 4; 7; 9; 2] ;; +List.fold_left (fun a b -> a + b) 0 (inorder t) diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index f277cca4..d5b441f4 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -1,4 +1,5 @@ { + "btree.ml": 39, "calc.ml": 13, "closures.ml": 315, "exception_handle.ml": 4, diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 6e3dc860..7dd9e206 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -399,6 +399,10 @@ _Newest first._ recognise `!` as the prefix-deref of an application argument, so `String.concat "" (List.rev !b)` parses as `(... (deref b))`. Buffer uses a ref holding a string list; contents reverses and concats. +- 2026-05-08 Phase 5.1 — btree.ml baseline (13/13 pass). Polymorphic + 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-08 Phase 5.1 — fizzbuzz.ml baseline (12/12 pass). Classic fizzbuzz using ref-cell accumulator, for-loop, mod, if/elseif chain, String.concat, Int.to_string. Verifies output via String.length.