Skip to content

Instantly share code, notes, and snippets.

@phase
Forked from darkf/bf.ml
Created July 25, 2016 04:36
Show Gist options
  • Save phase/9411086c8cf5b5a1d86221eb9215ec15 to your computer and use it in GitHub Desktop.
Save phase/9411086c8cf5b5a1d86221eb9215ec15 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