The order of a function is defined by the following induction : Basis : A function is "first-order" if its arguments and result are all "data", that is, not functions. Induction: A function is of order one more than the largest of the orders of its arguments and result.
Some common Higher-Order Functions
fun map (F, nil) = nil | map(F, x::xs) = F(x) :: map(F,xs) val map = fn : ( 'a -> 'b) * 'a list -> 'b list
exception EmptyList; fun reduce(F, nil) = raise EmptyList | reduce(F,[a]) = a | reduce(F,x::xs) = F(x,reduce(F,xs)) ; val reduce = fn : ('a * 'a -> 'a) * 'a list -> 'a another defintion of reduce : fun reduce f [] v = v | reduce f (a::y) v = f(a, reduce f y v) ; val reduce = fn : ( 'a * 'b -> 'b) -> 'a list -> 'b -> 'b
fun filter(P,nil) = nil | filter(P,x::xs) = if P(x) then x::filter(P,xs) else filter(P,xs) ; val filter = fn : ('a -> bool) * 'a list -> 'a list
fun foldr F y nil = y | foldr F y (x::xs) = F(x, foldr F y xs) ; val foldr = fn : ('a * 'b) -> 'b -> 'b -> 'a list -> 'b
List.take([1,2,3,4,5],3) ; val it = [1,2,3] : int list
List.drop([1,2,3,4,5],3) ; val it = [4,5] : int list
List.nth([1,2,3,4,5],3) ; val it = 4: int
List.tabulate(5, fn x => x*x) ; val it = [0,1,4,9,16] : int list
fun empty(x) = if x = [] then true else false; fun singleton (x) = if x = [] then false else if tl(x) = [] then true else false ; fun member(x,s) = if s = [] then false else if x = hd(s) then true else member(x,tl(s)) ; fun insert(x,s) = if member(x,s) then s else x::s ; fun delete(_,[]) = [] | delete (x, y::ys) = if x = y then ys else y::delete(x,ys) ; fun intersection(xs,ys) = List.filter (fn x =>member(x,ys)) xs ; fun union(xs, ys) = List.foldl insert ys xs ; fun diff(xs,ys) = List.filter(fn x => not (member(x,ys))) xs ; fun distinct(xs) = if xs = [] then [] else if member(hd(xs),tl(xs)) then distinct(tl(xs)) else hd(xs)::distinct(tl(xs)) ; fun union1(xs,ys) = List.foldr insert ys xs ; fun subset(xs,ys) = List.all(fn x => member(x,ys)) xs ; fun equal(xs , ys ) = subset(xs,ys) andalso subset(ys,xs) ; fun insertAll(a,nil) = nil | insertAll(a,L::Ls) = (a::L)::insertAll(a,Ls); fun powerSet(nil) = [nil] | powerSet(x::xs) = powerSet(xs)@insertAll(x,powerSet(xs));
fun reduce f [] v = v | reduce f (a::y) v = f(a, reduce f y v) ; fun length(x) = reduce (fn (_,y) => 1 + y) x 0 ; fun append(x,z) = reduce (fn(h,t)=>h::t) x z ; fun remove_if f x = reduce (fn (h,x)=> if f(h) then t else (h::t)) x [] ; fun map f x = reduce (fn(h,t)=> (f(h)::t)) x [] ;
fun sum_aux(L,res) = if L = nil then res else sum_aux(tl(L), res + hd(L)) ; fun sumList_tr(L) = sum_aux(L,0) ;
fun mulList_aux(L,res) = if L = nil then res else mulList_aux(tl(L), hd(L)* res) ; fun mulList_tr(L) = mulList_aux(L,1) ;
fun fact1(n,result) = if n = 0 then result else fact1(n-1,n*result) ; fun fact2(n) = fact1(n,1) ;
fun fib_aux(n,fn1,fn2) = if n = 0 orelse n = 1 then n else if n = 2 then fn1 + fn2 else fib_aux(n-1,fn1+fn2 , fn1) ; fun fib_tr(n) = fib_aux(n,1,0) ;