Representing programs:
type expr = <arith> | <bool> | <compare> | <let> | <if>
type expType = IntT | BoolT
type result = IntR of int | BoolR of bool
Last time: expressions, types for imperative programs.
What about functions and recursion?
What if we add functions?
type expType = ... | FunT of expType*expType
type expr = ...
| Fun of string * expType * expr
| Apply of expr * expr
How does name analysis change? Type checking?
n : τ₁
) ⊦ b : τ₂
Fun (n:τ₁, b) : τ₁ -> τ₂
f : τ₁ -> τ₂
e : τ₁
Apply(f,e) : τ₂
Previous examples won’t work for recursion…
let p1 = Let ("fact",
Fun ("x",IntT,
If (Eq (Name "x", IntC 0),
IntC 1,
Apply (Name "fact", Sub (Name "x",IntC 1)))
),
Apply(Name "fact", IntC 3));;
eval p1 [];;
typeof p1 [];;
What would need to change?
Another way to implement evaluation:
and evalFunc func argexp env =
let Closure (body, argn, def_env) = func in
let bodyExp = subName body argn argexp in
eval bodyExp def_env
and subName exp nm sub = match exp with
| Name n -> if n = nm then sub else (Name n)
| Let (n,v,b) -> if n = nm then Let(n,subName v nm sub, b) else
Let (n, subName v nm, subName b nm)
| Fun (argn, argt, body) -> if argn = nm then exp else
Fun (argn, argt, subName body nm sub)
| IntC _ | BoolC _ -> exp
| Not e -> Not (subName e nm sub)
| Add (e1,e2) -> Add (subName e1 nm sub, subName e2 nm sub)
...
Would this change anything?
cs2041.org