
Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!

fun Max(x::nil) = x | Max(x :: y::z) = if (x < y) then Max(y::z) else Max(x::z);
Solution:
fun Max(x) = let val p_x = ref x in while (not (tl(!p_x) = nil)) do let val x1 = hd(!p_x); val y = hd(tl(!p_x)); val z = tl(tl(!p_x)) in if (x1 < y) then p_x := y::z else p_x := x1::z end; hd(!p_x) end;
(a) fun sum(nil) = 0 | sum(x::y) = x + sum(y); Solution: fun sum(nil,K) = K(0) | sum(x::y, K) = sum(y, fn res=>K(x+res)); (b) datatype AST = Number of int | Plus of AST * AST ;
fun EvalExp (Number(x)) = x | EvalExp (Plus(opd1,opd2)) = EvalExp(opd1) + EvalExp(opd2); Solution: fun EvalExp(Number(x), K) = K(x) | EvalExp(Plus(opd1,opd2),K) = EvalExp(opd1, fn res1 => EvalExp(opd2, fn res2=> K(res1+res2)));