(* CSE341, Spring 2008, Lecture 8 *)
(* Create similar functions *)
val addn = fn n => fn m => n+m
val increment = addn 1
val add_two = addn 2
fun f n =
if n=0
then []
else (addn n)::(f (n-1))
(* Combine functions *)
fun f1 (g,h) = fn x => g (h x)
(* f1 is actually in ML's standard library as infix o (composition) *)
(* but that is just syntax -- the result of g o h is a closure that
"remembers" g and h in its environment *)
fun sqrt_of_abs1 i = Math.sqrt(Real.fromInt (abs i))
fun sqrt_of_abs2 i = (Math.sqrt o Real.fromInt o abs) i
val sqrt_of_abs3 = Math.sqrt o Real.fromInt o abs
(* another combining-fuctions function *)
fun f2 (g,h) = fn x =>
case g x of NONE => h x | SOME y => y
(* Private data, for map/fold *)
(* Earlier we saw map: *)
fun map (f,l) =
case l of
[] => []
| fst::rest => (f fst)::(map(f,rest))
(* This fold function is at least as useful *)
fun fold (f,acc,l) =
case l of
[] => acc
| fst::rest => fold (f, f(acc,fst), rest)
(* fold is actually in ML's standard library as List.foldl, but
List.foldl is "curried" (explanation soon).
You will use List.foldl in homework 3 *)
(* Example uses that do not use private data *)
fun f3 l = fold ((fn (x,y) => x+y), 0, l)
fun f4 l = fold ((fn (x,y) => x andalso y >= 0), true, l)
(* Examples that use that uses private data *)
fun f5 (l,lo,hi) =
fold ((fn (x,y) =>
if y >= lo andalso y <= hi then x+1 else x),
0, l)
fun f6 (lst,hi) = map((fn x => if x > hi then hi else x), lst)