(* left-associative fold *) (* foldl : ('a * 'b -> 'a) -> 'a -> 'b list -> 'a *) fun foldl f z [] = z | foldl f z (x::xs) = foldl f (f(z,x)) xs; (* NB. The standard SML foldl seems to have the wrong type! *) (* right-associative fold *) (* foldr : ('a * 'b -> 'b) -> 'b -> 'a list -> 'b *) fun foldr f z [] = z | foldr f z (x::xs) = f(x, (foldr f z xs)) (* equivalent to standard SML foldr *) (* find the smallest value in an int list *) fun smallestVal (x::xs) = foldl Int.min x xs; (* find the position of the smallest value in an int list *) fun smallestPos (x::xs) = #2(foldl (fn ((i,p,v),x) => if v>x then (i+1,i,x) else (i+1,p,v)) (1,0,x) xs) (* -------------------------------------------------------e.g.-- *) val xs = [10,11,12,9,10,11,9]; smallestVal xs; smallestPos xs; (* High-order functions, LA, CSSE, Monash U., 7/2005 *)