(* A Brainfuck interpreter in Ocaml. *) (* Turns a string of brainfuck code into an array of characters. *) let array_of_string str = let astr = Array.init (String.length str) (fun c -> str.[c]) in astr (* The actual interpreter. *) let bf code = let m = Array.make 30000 0 in let cp = ref 0 in let tp = ref 0 in let lp = ref [] in while (!cp < Array.length code) do (match code.(!cp) with | '>' -> tp := !tp + 1 | '<' -> tp := !tp - 1 | '+' -> m.(!tp) <- m.(!tp) + 1 mod 256 | '-' -> m.(!tp) <- m.(!tp) - 1 mod 256 | '.' -> print_char (char_of_int m.(!tp)) | ',' -> m.(!tp) <- input_byte stdin | '[' -> if m.(!tp) <> 0 then lp := !cp :: !lp else let ll = ref 1 in while !ll > 0 do cp := !cp + 1; match code.(!cp) with | '[' -> ll := !ll + 1 | ']' -> ll := !ll - 1 | _ -> () done | ']' -> if m.(!tp) <> 0 then cp := (List.hd !lp) - 1 else (); lp := List.tl !lp | _ -> ()); cp := !cp + 1 done let main () = if Array.length Sys.argv <> 2 then print_endline "No input." else bf (array_of_string (Sys.argv.(1))) let () = main ()