Skip to content

Instantly share code, notes, and snippets.

@darkf
Created May 30, 2013 11:29
Show Gist options
  • Save darkf/5677240 to your computer and use it in GitHub Desktop.
Save darkf/5677240 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in OCaml
let eval str =
let cells = Array.make 4096 0 in
let ptr = ref 0 in
let len = String.length str in
let rec evalbf c =
if c >= len then
c
else
match String.get str c with
| '>' -> ptr := !ptr + 1; evalbf (c+1)
| '<' -> ptr := !ptr - 1; evalbf (c+1)
| '+' -> cells.(!ptr) <- cells.(!ptr) + 1; evalbf (c+1)
| '-' -> cells.(!ptr) <- cells.(!ptr) - 1; evalbf (c+1)
| '.' -> Printf.printf "%c" (Char.chr cells.(!ptr)); evalbf (c+1)
| '[' ->
(* evalbf returns the point in the input where it returns, so we use it to jump past the loop *)
let newp = ref c in
while cells.(!ptr) != 0 do
newp := evalbf (c+1)
done;
evalbf (!newp+1)
| ']' -> c
| _ -> failwith "Unknown op"
in
ignore (evalbf 0)
let () =
(* Hello World! *)
eval "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment