From a91ff62730e0e540fdabb5e9b6ede3f2712cd8e3 Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 10:40:49 +0000 Subject: [PATCH] ocaml: phase 5.1 bsearch.ml baseline (binary search, position sum = 7) Iterative binary search on a sorted int array: let bsearch arr target = let n = Array.length arr in let lo = ref 0 and hi = ref (n - 1) in let found = ref (-1) in while !lo <= !hi && !found = -1 do let mid = (!lo + !hi) / 2 in if arr.(mid) = target then found := mid else if arr.(mid) < target then lo := mid + 1 else hi := mid - 1 done; !found For [1;3;5;7;9;11;13;15;17;19;21]: bsearch a 13 = 6 bsearch a 5 = 2 bsearch a 100 = -1 sum = 7 Exercises Array.of_list + arr.(i) + multi-let 'let lo = ... and hi = ...' + while + multi-arm if/else if/else. 49 baseline programs total. --- lib/ocaml/baseline/bsearch.ml | 16 ++++++++++++++++ lib/ocaml/baseline/expected.json | 1 + plans/ocaml-on-sx.md | 7 +++++++ 3 files changed, 24 insertions(+) create mode 100644 lib/ocaml/baseline/bsearch.ml diff --git a/lib/ocaml/baseline/bsearch.ml b/lib/ocaml/baseline/bsearch.ml new file mode 100644 index 00000000..fb2df41f --- /dev/null +++ b/lib/ocaml/baseline/bsearch.ml @@ -0,0 +1,16 @@ +let bsearch arr target = + let n = Array.length arr in + let lo = ref 0 and hi = ref (n - 1) in + let found = ref (-1) in + while !lo <= !hi && !found = -1 do + let mid = (!lo + !hi) / 2 in + if arr.(mid) = target then found := mid + else if arr.(mid) < target then lo := mid + 1 + else hi := mid - 1 + done; + !found + +;; + +let a = Array.of_list [1;3;5;7;9;11;13;15;17;19;21] in +bsearch a 13 + bsearch a 5 + bsearch a 100 diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index cecf44fb..b97ffddf 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -7,6 +7,7 @@ "bfs.ml": 6, "btree.ml": 39, "brainfuck.ml": 75, + "bsearch.ml": 7, "caesar.ml": 215, "calc.ml": 13, "closures.ml": 315, diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 63949809..5a516692 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-09 Phase 5.1 — bsearch.ml baseline (binary search, + position-sum 6 + 2 + (-1) = 7). Iterative bsearch on a sorted int + array using two index refs `lo`/`hi` and a sentinel `found = -1`. + while loop runs until `lo > hi` or found set. For [1;3;...;21]: + position of 13 = 6, 5 = 2, 100 = -1. Exercises Array.of_list + + arr.(i) + multi-let `let lo = ... and hi = ...` + while + multi-arm + if/else if. 49 baseline programs total. - 2026-05-09 Phase 5.1 — palindrome.ml baseline (two-pointer palindrome check, 4 of 6 inputs are palindromes). is_palindrome walks from both ends meeting in the middle, returning false on