(* HQ9+.ml -- HQ9+ Interpreter in Ocaml v0.1 Markus Kliegl Compile with: ocamlopt -o HQ9+ HQ9+.ml Usage: HQ9+ For information on HQ9+ see http://www.cliff.biffle.org/hq.html This version implements the h, 9 and q commands and ignores the + command, because the author has no clue as to what it's supposed to do *) let hello () = print_endline "Hello World!"; exit 0 ;; let rec beer n = if n = 1 then begin print_endline "1 bottle of beer on the wall"; print_endline "1 bottle of beer"; print_endline "Take one down and pass it around"; print_endline "No bottles of beer on the wall" end else begin print_int n; print_endline " bottles of beer on the wall"; print_int n; print_endline " bottles of beer"; print_endline "Take one down and pass it around"; print_int (n - 1); print_endline " bottles of beer on the wall"; print_newline (); beer (n - 1) end ;; let quine chan = try while true do print_char (input_char chan) done with _ -> exit 0 ;; let accumulate () = () ;; let err_unknown c = print_string "Unknown command: "; print_char c; print_newline (); exit 1 ;; let err_unexpected_eof () = print_endline "Unexpected end of file"; exit 1 ;; let interpret chan = try let c = input_char chan in begin match c with 'h' -> hello () | '9' -> beer 99 | 'q' -> print_char c; quine chan | '+' -> accumulate () | _ -> err_unknown c end with End_of_file -> err_unexpected_eof () ;; let main argc argv = if argc <> 2 then begin print_string "Usage: "; print_string argv.(0); print_endline " " end else try let chan = open_in argv.(1) in interpret chan; close_in chan with Sys_error s -> print_endline s ;; main (Array.length Sys.argv) Sys.argv (* HQ9+.ml ends here *)