Spring 2002, CSE 428: Solution of Final 2 (Section 2, 2 May 2002)

Question 1 (Java)

  1. True
  2. False
  3. True
  4. False
  5. False
  6. True
  7. False
  8. True
  9. False
  10. False

Question 2 (Memory management)

Question 3 (Basic ML programming)

datatype mobile = Weight of int | Node of mobile * mobile;

fun weight (Weight n) = n
  | weight (Node(l,r)) = weight l + weight r;

fun balanced (Weight _) = true
  | balanced (Node(l,r)) =
      balanced l andalso balanced r andalso (weight l = weight r);

(* Some test cases *)
val m1 = Node (Node(Weight 2, Weight 2), Node(Weight 2, Weight 2));
val m2 = Node(Node(Weight 2, Node(Weight 1, Weight 1)),
              Node(Weight 2,Weight 2));
val m3 = Node(Node(Node(Weight 2, Weight 2), 
              Node(Weight 2, Node(Weight 1, Weight 1))),
              Node(Weight 4, Weight 4));
val m4 = Node(Node(Node(Weight 2, Weight 2), 
                   Node(Weight 1, Node(Weight 1, Weight 1))),
              Node(Weight 4, Weight 4));
val m5 = Node(Weight 2, Weight 3);
map balanced [m1,m2,m3,m4,m5];
(* returnss [true,true,true,false,false] *)

datatype exp = I of int | Plus of exp * exp
             | Times of exp * exp | Square of exp;

fun evaluate(I n) = n
  | evaluate(Plus (E1,E2)) = evaluate E1 + evaluate E2
  | evaluate(Times(E1,E2)) = evaluate E1 * evaluate E2
  | evaluate(Square E1) = let val x = (evaluate E1) in x * x end;

val expex = Square (Plus (Times (I 1, I 10), Times (I 3, I 2)));

evaluate expex;
(* returns   256 *)

Question 4 (Types and higher-order programming in ML)

fun iterate f 0 x = x
  | iterate f n x = f(iterate f (n - 1) x);

val iterate = fn : ('a -> 'a) -> int -> 'a -> 'a

val cases = fn : (real -> 'a) -> (real * real -> 'a) -> numb -> 'a

val project = fn : numb -> real
f2.sml:12.1-14.38 Warning: match nonexhaustive
          (R x,R y) => ...
          (R x,C (u,v)) => ...
          (C (x,y),C (u,v)) => ...
  
val plus = fn : numb * numb -> numb

Question 5 (Basic Prolog programming)

pick([],[],[]).
pick([X|L],[yes|K],[X|M]) :- pick(L,K,M).
pick([_|L],[no |K],M    ) :- pick(L,K,M).

union([],[]).
union([L|Ls],M) :- union(Ls,K), append(L,K,M).

minlist([],  1001).
minlist([X|L],Tmp) :- minlist(L,Tmp), Tmp <  X.
minlist([X|L],X  ) :- minlist(L,Tmp), Tmp >= X.

%% A more efficient solution would can be written as 
% minlist([X|L],Min) :- minlist(L,Tmp),
%                       (Tmp < X, Min = Tmp; Tmp >= X, Min = X).