Spring 2002, CSE 428: Solution of Final 1 (Section 1, 29 April 2002)

Question 1 (Java)

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

Question 2 (Memory management)

Question 3 (Basic ML programming)

datatype tree = Leaf of int | Node of tree * tree;

fun max(i,j) = if i > j then i else j;

fun maxtree(Leaf i) = i
  | maxtree(Node(Left, Right)) = max(maxtree Left, maxtree Right);

fun sumtree(Leaf i) = i
  | sumtree(Node(Left, Right)) = (sumtree Left) + (sumtree Right);

local
  fun aux(Leaf _, Count) = (Leaf Count, Count+1)
    | aux(Node(L,Rl), C) = 
       let val (LL, M) = aux(L, C) in
       let val (RR, O) = aux(Rl, M) in
           (Node(LL,RR), O)
       end end
   in
  fun counttree Tree = 
       let val (Result, _) = aux(Tree, 1) in Result end
  end;

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

fun compose_list nil    x = x
  | compose_list (f::k) x = (f (compose_list k x));

val compose_list = fn : ('a -> 'a) list -> 'a -> 'a

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

(* diag produces a type error *)

(* plus produces a Warning: match nonexhaustive and the following type
*)

val plus = fn : numb * numb -> numb

Question 5 (Basic Prolog programming)

firstlast([X], X, X).
firstlast([X|L],X,Last) :- firstlast(L,_,Last).

max(N,M,M) :- N < M.
max(N,M,N) :- N >= M.

maxlist([],0).
maxlist([N|L],Max) :- maxlist(L,M), max(N,M,Max).

selectalternate([],[]).
selectalternate([X],[X]).
selectalternate([X,Y|L],[X|K]):- selectalternate(L,K).