Files
rose-ash/lib/ocaml/baseline/bf_full.ml
giles 097c7f4590
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 24s
ocaml: phase 5.1 bf_full.ml baseline (full Brainfuck with [] loops, +++[.-] = 6)
Extends the iter-92 brainfuck.ml subset interpreter with bracket
matching:

  '['  if mem[ptr] = 0, jump past matching ']'
       (forward depth-counting scan: '[' increments depth, ']' decrements)
  ']'  if mem[ptr] <> 0, jump back to matching '['
       (backward depth-counting scan)

Test program '+++[.-]':
  +++   set cell 0 = 3
  [     enter loop (cell != 0)
    .   acc += cell
    -   cell -= 1
  ]     loop while cell != 0
  result: acc = 3 + 2 + 1 = 6

Tests deeply nested while loops, mutable pc / ptr / acc, multi-arm
if/else if dispatch on chars + nested begin/end blocks for loop
body conditionals.

58 baseline programs total.
2026-05-09 12:24:48 +00:00

43 lines
1.1 KiB
OCaml

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)
else if c = '[' then begin
if mem.(!ptr) = 0 then begin
let depth = ref 1 in
while !depth > 0 do
pc := !pc + 1;
let c = prog.[!pc] in
if c = '[' then depth := !depth + 1
else if c = ']' then depth := !depth - 1
done
end
end
else if c = ']' then begin
if mem.(!ptr) <> 0 then begin
let depth = ref 1 in
while !depth > 0 do
pc := !pc - 1;
let c = prog.[!pc] in
if c = ']' then depth := !depth + 1
else if c = '[' then depth := !depth - 1
done
end
end);
pc := !pc + 1
done;
!acc
;;
interpret "+++[.-]"