type 'a result = Success of 'a | Failure of string let beers x = let rec bob n = match n with 1 -> print_string "1 bottle of beer on the wall, "; print_endline "1 bottle of beer."; print_string "Go to the store and buy some more, "; Printf.printf "%d bottle of beer on the wall.\n" x; | _ -> Printf.printf "%d bottles of beer on the wall, " n; Printf.printf "%d bottles of beer.\n" n; print_string "Take one down and pass it around, "; Printf.printf "%d bottles of beer on the wall.\n\n" (n-1); bob (n - 1) in bob x;; let x = ref 0;; let hq9p (cmd:string) = let l =String.length cmd in let rec do_loop n = if n==l then Success(()) else if n>l then Failure("Internal error") else match (String.get cmd n) with 'H'|'h'-> print_endline "Hello, world!"; do_loop (n+1) | 'Q'|'q'-> print_endline cmd; do_loop (n+1) | '9' -> beers 9;(* 99 bottles are too much to test! *) do_loop (n+1) | '+' -> x:=!x+1; do_loop (n+1) | _ -> Failure("INVALID CHARCTER"); in do_loop 0;; let cov (cmd:string)= match hq9p cmd with Success(_) -> () |Failure(msg) -> print_endline msg;; Arg.parse ["--command",Arg.String(cov),"Parse and execute HQ9+ commands"] cov "Usage:hq9p [<options>] [<HQ9+ commands>]"
なにか新しい言語を習得しようとしたときには毎度作ってるHQ9+インタプリタ。
今回も今回とて作ってみたが、、、適当すぎ…
何も考えずに付け足していった結果、
- resultが邪魔だったり
- というかresultが意味をなしてなかったり
- そもそも例外使えよ、という話だったり
- オプションが適当過ぎたり
- 文法的にあっているのか怪しかったり
するが、警告すら出ずにコンパイル通ったので良いことにしとこう…本当に大丈夫かなぁ?
なお、``99 bottles of beer''の歌詞はcodegolfのやつのパクり。
しかし、酷い関数名だな…