Exercise 2          Name _____________________  Pts ___/20

Translate into patterns or if-then statements:  
1. fun insert a [] = [a]
|    insert a (h::t) = if a<h then a::h::t else h::insert a t;
  fun insert a L = if null L then [a]
                          else if a<hd L then a::L
                                 else hd L::insert a (tl L);
2. fun f2 L = if null L then []
                     else if null (tl L) then L
                             else [hd (tl L)];
  fun f2 [] =[]
|     f2 [a] = [a]
|     f2 (_::b::_) = [b];
3. fun map(f,L) = if null L then []                     
                         else f (hd L)::map(f, (tl L));
  fun map (_,[]) = []
|     map (f,h::t) = f h::map(f,t);
4. fun filter f L = if null L then []
                       else if f (hd L) then hd L::filter f (tl L)
                              else filter f (tl L);
  fun filter _ [] = []
|    filter f (h::t) = if f h then h::filter f t
                              else filter f t;
5. fun reduce (_,a,[]) = a
|    reduce(f,a,h::t) = f h (reduce(f,a,t));
  fun reduce(f,a,L) = if null L then a
                               else f (hd L) (reduce(f,a,(tl L)));

Determine the result, given the above and the following definitions; indicate those in error.

fun min a b = if a<b then a else b;

fun prime n =
  let
      fun remainder 0 = true
      |    remainder 1 = true
      |    remainder m = if (n mod m) = 0 then false else remainder(m-1)
  in
      remainder (n-1)
 end;

6. reduce( insert, [], [5,3,1,7]); [1, 2, 5, 7]
7. reduce( min, 9999999, [5,3,1,7]); 1
8. prime 9; false
9. filter prime [17, 11, 12, 3, 6];              [17, 11, 3]
10. insert(1,[2,3]); Error