From 0f2eb45f5ce6fee24f9b2154630b26083e43968c Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 14:21:24 +0000 Subject: [PATCH] ocaml: phase 5.1 prefix_sum.ml baseline (precomputed sums + range queries, 14+25+27 = 66) Two utility functions: prefix_sums xs builds Array of len n+1 such that arr.(i) = sum of xs[0..i-1] range_sum p lo hi = p.(hi+1) - p.(lo) For [3;1;4;1;5;9;2;6;5;3]: range_sum 0 4 = 14 (3+1+4+1+5) range_sum 5 9 = 25 (9+2+6+5+3) range_sum 2 7 = 27 (4+1+5+9+2+6) sum = 66 Tests List.iter mutating Array indexed by a ref counter, plus the classic prefix-sum technique for O(1) range queries. 67 baseline programs total. --- lib/ocaml/baseline/expected.json | 1 + lib/ocaml/baseline/prefix_sum.ml | 16 ++++++++++++++++ plans/ocaml-on-sx.md | 7 +++++++ 3 files changed, 24 insertions(+) create mode 100644 lib/ocaml/baseline/prefix_sum.ml diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 62d779e8..4d72e60d 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -47,6 +47,7 @@ "palindrome.ml": 4, "pascal.ml": 252, "pi_leibniz.ml": 314, + "prefix_sum.ml": 66, "pretty_table.ml": 64, "poly_stack.ml": 5, "prime_factors.ml": 17, diff --git a/lib/ocaml/baseline/prefix_sum.ml b/lib/ocaml/baseline/prefix_sum.ml new file mode 100644 index 00000000..eb719e7d --- /dev/null +++ b/lib/ocaml/baseline/prefix_sum.ml @@ -0,0 +1,16 @@ +let prefix_sums xs = + let n = List.length xs in + let arr = Array.make (n + 1) 0 in + let i = ref 0 in + List.iter (fun x -> + arr.(!i + 1) <- arr.(!i) + x; + i := !i + 1 + ) xs; + arr + +let range_sum prefixes lo hi = prefixes.(hi + 1) - prefixes.(lo) + +;; + +let p = prefix_sums [3; 1; 4; 1; 5; 9; 2; 6; 5; 3] in +range_sum p 0 4 + range_sum p 5 9 + range_sum p 2 7 diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index cd5033fb..153ed59f 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 — prefix_sum.ml baseline (precomputed prefix + sums for O(1) range queries, sum of three queries = 66). + prefix_sums xs returns an Array of len n+1 such that + `arr.(i) = sum of xs[0..i-1]`. range_sum computes any contiguous + subarray sum in O(1) via subtraction. Tests List.iter mutating + Array indexed by ref counter, plus the classic prefix-sum + technique. 67 baseline programs total. - 2026-05-09 Phase 5.1 — tic_tac_toe.ml baseline (3x3 winner check, X wins top row → 1). Board encoded as 9-element flat int array with 0=empty, 1=X, 2=O. Three predicate functions check row,