(*world*) fun accumulate f a [] = a |accumulate f a (b::x) = accumulate f (f a b) x; (* For example: fun sum (i:int) (j:int) = i+j; accumulate sum 0 [1,2,3,4,5]; fun prod (i:int) (j:int) = i*j; accumulate prod 1 [1,2,3,4,5]; *) fun append x y = x @ y; infix mo; (* member of *) infix subset; infix superset; infix intersection; infix difference; fun e mo [] = false |e mo (a::x) = e=a orelse (e mo x); (* Is e a "member of" the set x? *) fun remove e [] = [] |remove e (a::x) = if e=a then remove e x else a::remove e x; fun x subset y = let fun subsetp [] y = true |subsetp (a::x) y = a mo y andalso subsetp x y in (length x) <= (length y) andalso subsetp x y end; fun x superset y = y subset x; (* Why is not the definition of superset as follows? fun superset x y = not(x subset y); As the chemist said "Suck it and see" *) fun [] intersection y = [] |(e::x) intersection y = if e mo y then e::(x intersection y) else x intersection y; (* "x intersection y" is the set of elements that are common to x and to y *) fun [] difference y = [] |(e::x) difference y = if e mo y then x difference y else e::(x difference y); (* "x difference y" is the set of elements in x that are not in y *) fun filter p [] = [] |filter p (a::x) = if p a then a::filter p x else filter p x; fun exists p [] = false |exists p (a::x) = p a orelse exists p x; fun all p [] = true |all p (a::x) = p a andalso all p x; fun zip f [] [] = [] |zip f [] (b::y) = [] |zip f (a::x) [] = [] |zip f (a::x) (b::y) = f a b::zip f x y; fun nth n [] = [] |nth 1 (a::x) = [a] |nth n (a::x) = nth (n-1) x; fun reverse [] = [] |reverse (a::x) = (reverse x) @ [a]; fun mapf [] x = [] |mapf (f::fs) x = (f x)::(mapf fs x); (* Given a list of functions [f1,f2,...,fn] and an argument x deliver a list of results [(f1 x),(f2 x),...,(fn x)] This may be used as follows: val fns = map remove [1,2,3]; mapf fns [1,2,3] This will deliver [[2,3],[1,3],[1,2]] *) fun collapse [] = [] |collapse (e::x) = e@(collapse x); (* Given a list of lists [[1,2,...,3],[9,6],....,[10,7]] Deliver [1,2,...3,9,6,....,10,7] as a result *) (* Use these functions to familiarise youself with what they do These are basic list handling functions, and may be considered as a functional programmer's primitive world.*)