Created
May 30, 2013 11:29
-
-
Save darkf/5677240 to your computer and use it in GitHub Desktop.
Brainfuck interpreter in OCaml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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