Docsity

ML Programming Homework Solutions: Tail Recursion vs Loops and Continuation Passing Style, Assignments of Programming Languages

Toggle sidebar
bg1
Homework 6 (30pts)
Due Nov 7, 2008 (electronic submission)
1. Translate the following tail recursive function in ML to an equivalent implementation
using loops.
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;
2. Translate the following ML code to tail recursion using continuation passing style.
(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)));
1

Partial preview of the text

Download ML Programming Homework Solutions: Tail Recursion vs Loops and Continuation Passing Style and more Assignments Programming Languages in PDF only on Docsity!

Homework 6 (30pts)

Due Nov 7, 2008 (electronic submission)

  1. Translate the following tail recursive function in ML to an equivalent implementation using loops.

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;

  1. Translate the following ML code to tail recursion using continuation passing style.

(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)));