(* CSE 341, Autumn 2010 Code written in lecture #2 (Fri 2010/10/01) *) (* Converts a single name from (last, first) to "first, last" format. *) fun singleName(first, last) = last ^ ", " ^ first; (* crappy version of singleName that treats the parameters as a tuple. *) fun singleName2(t : string * string) = #2(t) ^ ", " ^ #1(t); (* Converts a list of names from (last, first) format to a list of names in "first, last" format. *) fun convertNames(names) = if names = [] then [] else singleName(hd(names)) :: convertNames(tl(names)); (* test data for convertNames *) val test1 = [("Hillary", "Clinton"), ("Barack", "Obama"), ("Joe", "Biden"), ("John", "McCain"), ("Ron", "Paul")]; (* Produces the larger of the two values passed. *) fun max(a, b) = if a > b then a else b; (* alternative version of max that treats its parameters as a tuple. not recommended style; merely used to illustrate that all functions so far really take just a single parameter: a tuple. *) fun max2(twoInts : int * int) = if #1(twoInts) > #2(twoInts) then #1(twoInts) else #2(twoInts); (* Functions that simply return their parameters. These are used to illustrate the idea of parametric polymorphism. *) fun identity(x) = x; fun identity2(x, y) = (x, y); fun identity3(x, y) = [x, y]; (* Produces the last value from the given list. Precondition: List is non-empty. *) fun last(lst) = if length(lst) = 1 then hd(lst) else last(tl(lst)); (* Computes n!, or 1 * 2 * 3 * ... * n-1 * n. Precondition: n >= 0. *) fun factorial(n) = if n = 0 then 1 else n * factorial(n - 1);