ocaml: phase 5.1 brainfuck.ml baseline (subset interpreter)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 21s
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.
This commit is contained in:
20
lib/ocaml/baseline/brainfuck.ml
Normal file
20
lib/ocaml/baseline/brainfuck.ml
Normal file
@@ -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 "+++++.+++++.+++++.+++++.+++++."
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user