From f68ea63e4665eb34144540fdaaea7c007c6415f8 Mon Sep 17 00:00:00 2001 From: giles Date: Sat, 9 May 2026 02:24:45 +0000 Subject: [PATCH] ocaml: phase 5.1 brainfuck.ml baseline (subset interpreter) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five '+++++.' groups, cumulative accumulator 5+10+15+20+25 = 75. This is a brainfuck *subset* — only > < + - . (no [ ] looping). That's intentional: the goal is to stress imperative idioms that the recently added Array module + array indexing syntax + s.[i] make ergonomic, all in one program. Exercises: Array.make 256 0 arr.(!ptr) arr.(!ptr) <- arr.(!ptr) + 1 prog.[!pc] ref / ! / := while + nested if/else if/else if for op dispatch 25 baseline programs total. --- lib/ocaml/baseline/brainfuck.ml | 20 ++++++++++++++++++++ lib/ocaml/baseline/expected.json | 1 + plans/ocaml-on-sx.md | 6 ++++++ 3 files changed, 27 insertions(+) create mode 100644 lib/ocaml/baseline/brainfuck.ml diff --git a/lib/ocaml/baseline/brainfuck.ml b/lib/ocaml/baseline/brainfuck.ml new file mode 100644 index 00000000..3ab5e0bd --- /dev/null +++ b/lib/ocaml/baseline/brainfuck.ml @@ -0,0 +1,20 @@ +let interpret prog = + let mem = Array.make 256 0 in + let ptr = ref 0 in + let pc = ref 0 in + let n = String.length prog in + let acc = ref 0 in + while !pc < n do + let c = prog.[!pc] in + (if c = '>' then ptr := !ptr + 1 + else if c = '<' then ptr := !ptr - 1 + else if c = '+' then mem.(!ptr) <- mem.(!ptr) + 1 + else if c = '-' then mem.(!ptr) <- mem.(!ptr) - 1 + else if c = '.' then acc := !acc + mem.(!ptr)); + pc := !pc + 1 + done; + !acc + +;; + +interpret "+++++.+++++.+++++.+++++.+++++." diff --git a/lib/ocaml/baseline/expected.json b/lib/ocaml/baseline/expected.json index 8c254deb..904c4111 100644 --- a/lib/ocaml/baseline/expected.json +++ b/lib/ocaml/baseline/expected.json @@ -2,6 +2,7 @@ "anagrams.ml": 3, "bfs.ml": 6, "btree.ml": 39, + "brainfuck.ml": 75, "caesar.ml": 215, "calc.ml": 13, "closures.ml": 315, diff --git a/plans/ocaml-on-sx.md b/plans/ocaml-on-sx.md index 9c6c2e00..6668bcc8 100644 --- a/plans/ocaml-on-sx.md +++ b/plans/ocaml-on-sx.md @@ -407,6 +407,12 @@ _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 — brainfuck.ml baseline (subset interpreter, + five `+++++.` groups → cumulative 5+10+15+20+25 = 75). No loop + brackets — the interpreter only handles `> < + - .`, but that's + enough to exercise Array.make, arr.(i), arr.(i) <- v, prog.[!pc], + ref/!/:=, while loop with conditional update via nested if/else. + 25 baseline programs total. - 2026-05-09 Phase 5.1 — sieve.ml baseline (Sieve of Eratosthenes, count of primes ≤ 50 = 15). Stresses Array.make + arr.(i) + arr.(i) <- v + nested for/while loops + `begin..end` block. 24