(***********************************************************) (* Disclaimer: This code is not documented. *) (***********************************************************) (***********************************************************) (* LEN (Length) Note that it is polymorphic *) fun len [] = 0 | len (head::tail) = 1 + len tail; (* --- Example Applications -------------------------------- len [1,2,3]; len ["CSC", "324", "is", "fun"]; ---------------------------------------------------------- *) (***********************************************************) (***********************************************************) (***********************************************************) (* FIB (Fibonacci) *) fun fib 0 = 0 | fib 1 = 1 | fib n = fib(n-1) + fib(n-2); (* --- Example Applications -------------------------------- fib 0; ---------------------------------------------------------- *) (***********************************************************) (***********************************************************) (***********************************************************) (* LISTSUM1, LISTSUM2 Sums a list of integers - several alternatives *) fun listsum1 L = if (null L) then 0 else (hd L) + listsum1 (tl L); (* OR *) fun listsum2 [] = 0 | listsum2 (h::t) = h + listsum2 t; (* --- Example Applications -------------------------------- listsum [1,2,3]; ---------------------------------------------------------- *) (***********************************************************) (***********************************************************) (***********************************************************) (* REVERSE - Look at this! How to fix the problem? *) fun reverse (h::t) = reverse(t) @ [h]; (* --- Example Applications -------------------------------- reverse [1,2,3]; reverse ["I", "am", "hungry"]; ---------------------------------------------------------- *) (***********************************************************) (***********************************************************) (***********************************************************) (* EVEN - mutual recursion example *) (* The following doesn't work: fun even 0 = true | even x = odd (x-1); - can't type: odd not defined BUT this does. Note the multiple recursion *) fun even 0 = true | even x = odd (x-1) and odd 0 = false | odd x = even (x-1); (***********************************************************) (***********************************************************) (***********************************************************)