
Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An analysis of the sequence of events that occur during the evaluation of functions with exceptions and tail recursion in ml. It also demonstrates the conversion of a non-tail recursive function to tail recursion using continuation passing style. Exception handling, function calls, and tail recursion using examples and code snippets.
Typology: Lab Reports
1 / 1
This page cannot be seen from the preview
Don't miss anything!

CS 3721: Programming Languages Lab Lab #11: Exceptions and tail recursion
Exceptions(Adapted from JM 8.1). Consider the following ML code.
exception Excpt of int; 1: fun twice(f,x) = f(f(x)) handle Excpt(x) => x; 2: fun pred(x) = if x = 0 then raise Excpt(x) else x - 1; 3: fun dumb(x) = raise Excpt(x); 4: fun smart(x) = pred(x) - 1 handle Excpt(x) => 1;
The following list the sequence of events occured during the evaluation of twice(dumb, 1). In particular, it lists which function is called with what ar- guments, which funtion call returns with what value, what exception gets raised in which function call, and what exception is handled in which function call.
twice(dumb, 1) called; twice function entered at line 1; dumb(1) called at line 1; dumb function entered at line 3; Excpt(1) raised at line 3; dumb function exits; Excpt(1) handled at line 1; twice(dumb,1) returns 1.
Continuation Passing Suppose we have the following function definition length in ML.
fun length(y) = if null y then 0 else 1 + length(tl(y));
It is converted to tail recursion using continuation passing in the following.
fun length2(y,K) = if null y then K 0 else length2(tl(y), fn res => K(res+1));
datatype tree = LEAF of int | NODE of tree*tree
fun inTree(x, LEAF(y)) = x = y | inTree(x, NODE(y,z)) = inTree(x,y) orelse inTree(x,z);
Test your implementation with the following invocations (first return true, second return false).
inTree(3, NODE(LEAF(5),NODE(LEAF(6),LEAF(3))), fn x=>x); inTree(3, NODE(LEAF(5),NODE(LEAF(6),LEAF(7))), fn x=>x);