Created
April 27, 2014 05:19
-
-
Save jkrems/11338116 to your computer and use it in GitHub Desktop.
First OCaml program
This file contains hidden or 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
type id = string | |
type binop = Plus | Minus | Times | Div | |
type stm = CompoundStm of stm * stm | |
| AssignStm of id * exp | |
| PrintStm of exp list | |
and exp = IdExp of id | |
| NumExp of int | |
| OpExp of exp * binop * exp | |
| EseqExp of stm * exp | |
let prog1 = | |
CompoundStm( | |
AssignStm("a", OpExp(NumExp 5, Plus, NumExp 3)), | |
CompoundStm( | |
AssignStm( | |
"b", | |
EseqExp( | |
PrintStm[ | |
IdExp "a"; | |
OpExp(IdExp "a", Minus, NumExp 1) | |
], | |
OpExp(NumExp 10, Times, IdExp "a") | |
) | |
), | |
PrintStm[IdExp "b"] | |
) | |
) | |
(* Print maximum number of arguments to a print statement *) | |
let rec maxargs prog = | |
let rec maxargs_exp e = | |
match e with | |
| IdExp name -> 0 | |
| NumExp n -> 0 | |
| OpExp (x, op, y) -> max (maxargs_exp x) (maxargs_exp y) | |
| EseqExp (s, sub_expression) -> max (maxargs s) (maxargs_exp sub_expression) | |
in | |
match prog with | |
| CompoundStm (first, second) -> max (maxargs first) (maxargs second) | |
| AssignStm (name, value) -> maxargs_exp value | |
| PrintStm (expressions) -> List.length expressions | |
let () = | |
print_int (maxargs prog1); | |
print_newline () |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment