From fff8fe2dc8696231a1ccd3c1619de9f939a050b0 Mon Sep 17 00:00:00 2001 From: giles Date: Fri, 8 May 2026 19:10:49 +0000 Subject: [PATCH] ocaml: phase 5.1 memo_fib.ml baseline (16/16 pass) Memoized fibonacci using Hashtbl.find_opt + Hashtbl.add. fib(25) = 75025. Demonstrates mutable Hashtbl through the OCaml stdlib API in real recursive code. --- lib/ocaml/baseline/expected.json | 1 + lib/ocaml/baseline/memo_fib.ml | 15 +++++++++++++++ plans/ocaml-on-sx.md | 3 +++ 3 files changed, 19 insertions(+) create mode 100644 lib/ocaml/baseline/memo_fib.ml diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 6b51c383..c4ea6f4e 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -7,6 +7,7 @@ "factorial.ml": 3628800, "fizzbuzz.ml": 57, "list_ops.ml": 30, + "memo_fib.ml": 75025, "module_use.ml": 3, "mutable_record.ml": 10, "option_match.ml": 5, diff --git a/lib/ocaml/baseline/memo_fib.ml b/lib/ocaml/baseline/memo_fib.ml new file mode 100644 index 00000000..d4f4a4a9 --- /dev/null +++ b/lib/ocaml/baseline/memo_fib.ml @@ -0,0 +1,15 @@ +(* Baseline: memoized fibonacci using Hashtbl *) +let cache = Hashtbl.create 16 ;; + +let rec fib n = + if n < 2 then n + else + match Hashtbl.find_opt cache n with + | Some v -> v + | None -> + let v = fib (n - 1) + fib (n - 2) in + Hashtbl.add cache n v ; + v +;; + +fib 25 diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index a5fdfeb0..5deb193c 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,9 @@ _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-08 Phase 5.1 — memo_fib.ml baseline (16/16 pass). Memoized + fibonacci using `Hashtbl.find_opt` + `Hashtbl.add`. fib(25) = 75025. + Demonstrates mutable dict semantics through the OCaml stdlib API. - 2026-05-08 Phase 5.1 — queens.ml baseline (15/15 pass). 4-queens count via recursive backtracking with `List.fold_left`. Returns 2 (the two solutions of 4-queens). Per-program timeout in run.sh