Skip to content

Instantly share code, notes, and snippets.

@jkrems
Created April 27, 2014 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkrems/11338116 to your computer and use it in GitHub Desktop.
Save jkrems/11338116 to your computer and use it in GitHub Desktop.
First OCaml program
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