diff -r b655ce68983f -r df8660143051 progs/fun/simple-cps.sc --- a/progs/fun/simple-cps.sc Fri Jun 02 15:58:57 2023 +0100 +++ b/progs/fun/simple-cps.sc Sun Jun 04 23:59:19 2023 +0100 @@ -23,6 +23,11 @@ } import KExp._ +def pexp(e: KExp): String = e match { + case KReturn(v) => s"KReturn($v)" + case KLet(x,e1,e2) => s"KLet($x = ${e1} \n in ${pexp(e2)})" +} + var cnt = -1 def Fresh(s: String) = { cnt = cnt + 1 @@ -60,4 +65,26 @@ Num(3), Call("id", List(Num(12)))))) -println(CPSi(etest)) +println(pexp(CPSi(etest))) + +// Constant Folding +def opt(v: KVal, env: Map[String, Int]) : KVal = v match { + case KVar(s) => if (env.isDefinedAt(s)) KNum(env(s)) else KVar(s) + case KNum(n) => KNum(n) + case KAop(op, v1, v2) => (op, opt(v1, env), opt(v2, env)) match { + case ("+", KNum(n1), KNum(n2)) => KNum(n1 + n2) + case ("*", KNum(n1), KNum(n2)) => KNum(n1 * n2) + case (_, v1o, v2o) => KAop(op, v1o, v2o) + } + case KCall(fname, args) => KCall(fname, args.map(opt(_, env))) +} + +def Koptimise(ke: KExp, env: Map[String, Int] = Map()) : KExp = ke match { + case KReturn(v) => KReturn(opt(v, env)) + case KLet(x, v, e) => opt(v, env) match { + case KNum(n) => Koptimise(e, env + (x -> n)) + case vo => KLet(x, vo, Koptimise(e, env)) + } +} + +println("\n" ++ pexp(Koptimise(CPSi(etest))))