Created
August 17, 2025 20:30
-
-
Save vitorsouzaalmeida/987ab5186b84e91bdc27b0487eb04840 to your computer and use it in GitHub Desktop.
Modern compiler implementation in ML - Intro ex. 1
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 | |
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 prog = 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")]))) | |
let maxargs (stm: stm) : int = | |
let rec aux (s: stm) : int = | |
match s with | |
| CompoundStm(s1, s2) -> max (aux s1) (aux s2) | |
| AssignStm(_, e) -> aux_exp e | |
| PrintStm(exps) -> | |
let count = List.length exps in | |
let max_in_reps = List.fold_left (fun acc e -> max acc (aux_exp e)) 0 exps in | |
max count max_in_reps | |
and aux_exp (e: exp) : int = | |
match e with | |
| IdExp _ -> 0 | |
| NumExp _ -> 0 | |
| OpExp(e1, _, e2) -> max (aux_exp e1) (aux_exp e2) | |
| EseqExp(s, e) -> max (aux s) (aux_exp e) | |
in | |
aux stm | |
let () = Printf.printf "Max args: %d\n" (maxargs prog) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment