Docsity

Practice Questions for Programming Languages - Assignment 9 | CS 3723, Assignments of Programming Languages

Toggle sidebar
bg1
Homework 9 (30pts)
Due Apr 8, 2009 (electronic submission)
1. Given the following code.
1: exception MultBy0 of int;
2: fun global(x,y) =
3: let fun compose(f, g) =
4: f(g(x) handle MultBy0(z) => z+1)
5: handle MultBy0(z)=>z+1;
6: fun mult(x) = if (y = 0) then raise MultBy0(x)
7: else if (x=0) then raise MultBy0(y) else x*y;
8: in let val x = 3 in
9: compose(mult,mult)
10: end
11: end;
List the events occurred when global(0,5) is called.
global(0,5) called
compose(mult,mult) called at line 9
compose(mult,mult) entered at line 4
mult(0) called at line 4
mult(0) entered at line 6
MultBy0(5) raised at line 7
mult(0) exits
MultBy0(5) handled at line 4
mult(6) called
mult(6) entered at line 6
mult(6) returns 30
mult(6) exits
compose(mult,mult) returns 30
global returns 30
2. Translate the following ML code to tail recursion using continuation passing style.
(a) fun maplist (f,[]) = []
| maplist(f, x::y) = f(x) :: maplist(f,y);
fun maplist(f,[],K) = K []
| maplist(f, x::y, K) = maplist(f, y, fn z=> f(x) :: z);
1
pf2

Partial preview of the text

Download Practice Questions for Programming Languages - Assignment 9 | CS 3723 and more Assignments Programming Languages in PDF only on Docsity!

Homework 9 (30pts)

Due Apr 8, 2009 (electronic submission)

  1. Given the following code.

1: exception MultBy0 of int; 2: fun global(x,y) = 3: let fun compose(f, g) = 4: f(g(x) handle MultBy0(z) => z+1) 5: handle MultBy0(z)=>z+1; 6: fun mult(x) = if (y = 0) then raise MultBy0(x) 7: else if (x=0) then raise MultBy0(y) else x*y; 8: in let val x = 3 in 9: compose(mult,mult) 10: end 11: end;

List the events occurred when global(0, 5) is called.

global(0,5) called compose(mult,mult) called at line 9 compose(mult,mult) entered at line 4 mult(0) called at line 4 mult(0) entered at line 6 MultBy0(5) raised at line 7 mult(0) exits MultBy0(5) handled at line 4 mult(6) called mult(6) entered at line 6 mult(6) returns 30 mult(6) exits compose(mult,mult) returns 30 global returns 30

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

(a) fun maplist (f,[]) = [] | maplist(f, x::y) = f(x) :: maplist(f,y);

fun maplist(f,[],K) = K [] | maplist(f, x::y, K) = maplist(f, y, fn z=> f(x) :: z);

(b) datatype InputType = NULL | Symbol of string | Number of int | Cons of InputType*InputType; fun count_symbols(Symbol(y)) = 1 | count_symbols(Number(y)) = 0 | count_symbols(Cons(car,cdr)) = count_symbols(car) + count_symbols(cdr);

fun count_symbols(Symbol(y),K) = K(1) | count_symbols(Number(y),K) = K(0) | count_symbols(Cons(car,cdr),K) = count_symbols(car, fn a=>count_symbols(cdr, fn b=>a+b));