0

1 
(* Title: library


2 
ID: $Id$


3 
Author: Lawrence C Paulson, Cambridge University Computer Laboratory


4 
Copyright 1992 University of Cambridge


5 


6 
Basic library: booleans, lists, pairs, input/output, etc.


7 
*)


8 


9 


10 
(**** Booleans: operators for combining predicates ****)


11 


12 
infix orf;


13 
fun p orf q = fn x => p x orelse q x ;


14 


15 
infix andf;


16 
fun p andf q = fn x => p x andalso q x ;


17 


18 
fun notf p x = not (p x) ;


19 


20 
fun orl [] = false


21 
 orl (x::l) = x orelse orl l;


22 


23 
fun andl [] = true


24 
 andl (x::l) = x andalso andl l;


25 


26 
(*exists pred [x1,...,xn] ======> pred(x1) orelse ... orelse pred(xn)*)


27 
fun exists (pred: 'a > bool) : 'a list > bool =


28 
let fun boolf [] = false


29 
 boolf (x::l) = (pred x) orelse boolf l


30 
in boolf end;


31 


32 
(*forall pred [x1,...,xn] ======> pred(x1) andalso ... andalso pred(xn)*)


33 
fun forall (pred: 'a > bool) : 'a list > bool =


34 
let fun boolf [] = true


35 
 boolf (x::l) = (pred x) andalso (boolf l)


36 
in boolf end;


37 


38 


39 
(*** Lists ***)


40 


41 
exception LIST of string;


42 


43 
(*discriminator and selectors for lists. *)


44 
fun null [] = true


45 
 null (_::_) = false;


46 


47 
fun hd [] = raise LIST "hd"


48 
 hd (a::_) = a;


49 


50 
fun tl [] = raise LIST "tl"


51 
 tl (_::l) = l;


52 


53 


54 
(*curried functions for pairing and reversed pairing*)


55 
fun pair x y = (x,y);


56 
fun rpair x y = (y,x);


57 


58 
fun fst(x,y) = x and snd(x,y) = y;


59 


60 
(*Handy combinators*)


61 
fun curry f x y = f(x,y);


62 
fun uncurry f(x,y) = f x y;


63 
fun I x = x and K x y = x;


64 


65 
(*Combine two functions forming the union of their domains*)


66 
infix orelf;


67 
fun f orelf g = fn x => f x handle Match=> g x;


68 


69 


70 
(*Application of (infix) operator to its left or right argument*)


71 
fun apl (x,f) y = f(x,y);


72 
fun apr (f,y) x = f(x,y);


73 


74 


75 
(*functional for pairs*)


76 
fun pairself f (x,y) = (f x, f y);


77 


78 
(*Apply the function to a component of a pair*)


79 
fun apfst f (x, y) = (f x, y);


80 
fun apsnd f (x, y) = (x, f y);


81 


82 
fun square (n: int) = n*n;


83 


84 
fun fact 0 = 1


85 
 fact n = n * fact(n1);


86 


87 


88 
(*The following versions of fold are designed to fit nicely with infixes.*)


89 


90 
(* (op @) (e, [x1,...,xn]) ======> ((e @ x1) @ x2) ... @ xn


91 
for operators that associate to the left. TAIL RECURSIVE*)


92 
fun foldl (f: 'a * 'b > 'a) : 'a * 'b list > 'a =


93 
let fun itl (e, []) = e


94 
 itl (e, a::l) = itl (f(e,a), l)


95 
in itl end;


96 


97 
(* (op @) ([x1,...,xn], e) ======> x1 @ (x2 ... @ (xn @ e))


98 
for operators that associate to the right. Not tail recursive.*)


99 
fun foldr f (l,e) =


100 
let fun itr [] = e


101 
 itr (a::l) = f(a, itr l)


102 
in itr l end;


103 


104 
(* (op @) [x1,...,xn] ======> x1 @ (x2 ..(x[n1]. @ xn))


105 
for n>0, operators that associate to the right. Not tail recursive.*)


106 
fun foldr1 f l =


107 
let fun itr [x] = x


108 
 itr (x::l) = f(x, itr l)


109 
in itr l end;


110 


111 


112 
(*Length of a list. Should unquestionably be a standard function*)


113 
local fun length1 (n, [ ]) = n (*TAIL RECURSIVE*)


114 
 length1 (n, x::l) = length1 (n+1, l)


115 
in fun length l = length1 (0,l) end;


116 


117 


118 
(*Take the first n elements from l.*)


119 
fun take (n, []) = []


120 
 take (n, x::xs) = if n>0 then x::take(n1,xs)


121 
else [];


122 


123 
(*Drop the first n elements from l.*)


124 
fun drop (_, []) = []


125 
 drop (n, x::xs) = if n>0 then drop (n1, xs)


126 
else x::xs;


127 


128 
(*Return nth element of l, where 0 designates the first element;


129 
raise EXCEPTION if list too short.*)


130 
fun nth_elem NL = case (drop NL) of


131 
[] => raise LIST "nth_elem"


132 
 x::l => x;


133 


134 


135 
(*make the list [from, from+1, ..., to]*)


136 
infix upto;


137 
fun from upto to =


138 
if from>to then [] else from :: ((from+1) upto to);


139 


140 
(*make the list [from, from1, ..., to]*)


141 
infix downto;


142 
fun from downto to =


143 
if from<to then [] else from :: ((from1) downto to);


144 


145 
(* predicate: downto0(is,n) <=> is = [n,n1,...,0] *)


146 
fun downto0(i::is,n) = i=n andalso downto0(is,n1)


147 
 downto0([],n) = n = ~1;


148 


149 
(*Like Lisp's MAPC  seq proc [x1,...,xn] evaluates


150 
proc(x1); ... ; proc(xn) for side effects.*)


151 
fun seq (proc: 'a > unit) : 'a list > unit =


152 
let fun seqf [] = ()


153 
 seqf (x::l) = (proc x; seqf l)


154 
in seqf end;


155 


156 


157 
(*** Balanced folding; access to balanced trees ***)


158 


159 
exception Balance; (*indicates nonpositive argument to balancing fun*)


160 


161 
(*Balanced folding; avoids deep nesting*)


162 
fun fold_bal f [x] = x


163 
 fold_bal f [] = raise Balance


164 
 fold_bal f xs =


165 
let val k = length xs div 2


166 
in f (fold_bal f (take(k,xs)),


167 
fold_bal f (drop(k,xs)))


168 
end;


169 


170 
(*Construct something of the form f(...g(...(x)...)) for balanced access*)


171 
fun access_bal (f,g,x) n i =


172 
let fun acc n i = (* 1<=i<=n*)


173 
if n=1 then x else


174 
let val n2 = n div 2


175 
in if i<=n2 then f (acc n2 i)


176 
else g (acc (nn2) (in2))


177 
end


178 
in if 1<=i andalso i<=n then acc n i else raise Balance end;


179 


180 
(*Construct ALL such accesses; could try harder to share recursive calls!*)


181 
fun accesses_bal (f,g,x) n =


182 
let fun acc n =


183 
if n=1 then [x] else


184 
let val n2 = n div 2


185 
val acc2 = acc n2


186 
in if nn2=n2 then map f acc2 @ map g acc2


187 
else map f acc2 @ map g (acc (nn2)) end


188 
in if 1<=n then acc n else raise Balance end;


189 


190 


191 
(*** Input/Output ***)


192 


193 
fun prs s = output(std_out,s);


194 
fun writeln s = prs (s ^ "\n");


195 


196 
(*Print error message and abort to top level*)


197 
exception ERROR;


198 
fun error (msg) = (writeln msg; raise ERROR);


199 


200 
fun assert p msg = if p then () else error msg;


201 
fun deny p msg = if p then error msg else ();


202 


203 
(*For the "test" target in Makefiles  signifies successful termination*)


204 
fun maketest msg =


205 
(writeln msg;


206 
output(open_out "test", "Test examples ran successfully\n"));


207 


208 
(*print a list surrounded by the brackets lpar and rpar, with comma separator


209 
print nothing for empty list*)


210 
fun print_list (lpar, rpar, pre: 'a > unit) (l : 'a list) =


211 
let fun prec(x) = (prs","; pre(x))


212 
in case l of


213 
[] => ()


214 
 x::l => (prs lpar; pre x; seq prec l; prs rpar)


215 
end;


216 


217 
(*print a list of items separated by newlines*)


218 
fun print_list_ln (pre: 'a > unit) : 'a list > unit =


219 
seq (fn x => (pre x; writeln""));


220 


221 
fun is_letter ch =


222 
(ord"A" <= ord ch) andalso (ord ch <= ord"Z") orelse


223 
(ord"a" <= ord ch) andalso (ord ch <= ord"z");


224 


225 
fun is_digit ch =


226 
(ord"0" <= ord ch) andalso (ord ch <= ord"9");


227 


228 
(*letter or _ or prime (') *)


229 
fun is_quasi_letter "_" = true


230 
 is_quasi_letter "'" = true


231 
 is_quasi_letter ch = is_letter ch;


232 


233 
(*white space: blanks, tabs, newlines*)


234 
val is_blank : string > bool = fn


235 
" " => true  "\t" => true  "\n" => true  _ => false;


236 


237 
val is_letdig = is_quasi_letter orf is_digit;


238 


239 
val to_lower =


240 
let


241 
fun lower ch =


242 
if ch >= "A" andalso ch <= "Z" then


243 
chr (ord ch  ord "A" + ord "a")


244 
else ch;


245 
in


246 
implode o (map lower) o explode


247 
end;


248 


249 


250 
(*** Timing ***)


251 


252 
(*Unconditional timing function*)


253 
val timeit = cond_timeit true;


254 


255 
(*Timed application function*)


256 
fun timeap f x = timeit(fn()=> f x);


257 


258 
(*Timed "use" function, printing filenames*)


259 
fun time_use fname = timeit(fn()=>


260 
(writeln("\n**** Starting " ^ fname ^ " ****"); use fname;


261 
writeln("\n**** Finished " ^ fname ^ " ****")));


262 


263 


264 
(*** Misc functions ***)


265 


266 
(*Function exponentiation: f(...(f x)...) with n applications of f *)


267 
fun funpow n f x =


268 
let fun rep (0,x) = x


269 
 rep (n,x) = rep (n1, f x)


270 
in rep (n,x) end;


271 


272 
(*Combine two lists forming a list of pairs:


273 
[x1,...,xn] ~~ [y1,...,yn] ======> [(x1,y1), ..., (xn,yn)] *)


274 
infix ~~;


275 
fun [] ~~ [] = []


276 
 (x::xs) ~~ (y::ys) = (x,y) :: (xs ~~ ys)


277 
 _ ~~ _ = raise LIST "~~";


278 


279 
(*Inverse of ~~; the old 'split'.


280 
[(x1,y1), ..., (xn,yn)] ======> ( [x1,...,xn] , [y1,...,yn] ) *)


281 
fun split_list (l: ('a*'b)list) = (map #1 l, map #2 l);


282 


283 
(*make the list [x; x; ...; x] of length n*)


284 
fun replicate n (x: 'a) : 'a list =


285 
let fun rep (0,xs) = xs


286 
 rep (n,xs) = rep(n1, x::xs)


287 
in if n<0 then raise LIST "replicate"


288 
else rep (n,[])


289 
end;


290 


291 
(*Flatten a list of lists to a list.*)


292 
fun flat (ls: 'c list list) : 'c list = foldr (op @) (ls,[]);


293 


294 


295 
(*** polymorphic set operations ***)


296 


297 
(*membership in a list*)


298 
infix mem;


299 
fun x mem [] = false


300 
 x mem (y::l) = (x=y) orelse (x mem l);


301 


302 
(*insertion into list if not already there*)


303 
infix ins;


304 
fun x ins xs = if x mem xs then xs else x::xs;


305 


306 
(*union of sets represented as lists: no repetitions*)


307 
infix union;


308 
fun xs union [] = xs


309 
 [] union ys = ys


310 
 (x::xs) union ys = xs union (x ins ys);


311 


312 
infix inter;


313 
fun [] inter ys = []


314 
 (x::xs) inter ys = if x mem ys then x::(xs inter ys)


315 
else xs inter ys;


316 


317 
infix subset;


318 
fun [] subset ys = true


319 
 (x::xs) subset ys = x mem ys andalso xs subset ys;


320 


321 
(*removing an element from a list WITHOUT duplicates*)


322 
infix \;


323 
fun (y::ys) \ x = if x=y then ys else y::(ys \ x)


324 
 [] \ x = [];


325 


326 
infix \\;


327 
val op \\ = foldl (op \);


328 


329 
(*** option stuff ***)


330 


331 
datatype 'a option = None  Some of 'a;


332 


333 
exception OPTION of string;


334 


335 
fun the (Some x) = x


336 
 the None = raise OPTION "the";


337 


338 
fun is_some (Some _) = true


339 
 is_some None = false;


340 


341 
fun is_none (Some _) = false


342 
 is_none None = true;


343 


344 


345 
(*** Association lists ***)


346 


347 
(*Association list lookup*)


348 
fun assoc ([], key) = None


349 
 assoc ((keyi,xi)::pairs, key) =


350 
if key=keyi then Some xi else assoc (pairs,key);


351 


352 
fun assocs ps x = case assoc(ps,x) of None => []  Some(ys) => ys;


353 


354 
(*Association list update*)


355 
fun overwrite(al,p as (key,_)) =


356 
let fun over((q as (keyi,_))::pairs) =


357 
if keyi=key then p::pairs else q::(over pairs)


358 
 over[] = [p]


359 
in over al end;


360 


361 
(*Copy the list preserving elements that satisfy the predicate*)


362 
fun filter (pred: 'a>bool) : 'a list > 'a list =


363 
let fun filt [] = []


364 
 filt (x::xs) = if pred(x) then x :: filt xs else filt xs


365 
in filt end;


366 


367 
fun filter_out f = filter (not o f);


368 


369 


370 
(*** List operations, generalized to an arbitrary equality function "eq"


371 
 so what good are equality types?? ***)


372 


373 
(*removing an element from a list  possibly WITH duplicates*)


374 
fun gen_rem eq (xs,y) = filter_out (fn x => eq(x,y)) xs;


375 


376 
(*generalized membership test*)


377 
fun gen_mem eq (x, []) = false


378 
 gen_mem eq (x, y::ys) = eq(x,y) orelse gen_mem eq (x,ys);


379 


380 
(*generalized insertion*)


381 
fun gen_ins eq (x,xs) = if gen_mem eq (x,xs) then xs else x::xs;


382 


383 
(*generalized union*)


384 
fun gen_union eq (xs,[]) = xs


385 
 gen_union eq ([],ys) = ys


386 
 gen_union eq (x::xs,ys) = gen_union eq (xs, gen_ins eq (x,ys));


387 


388 
(*Generalized association list lookup*)


389 
fun gen_assoc eq ([], key) = None


390 
 gen_assoc eq ((keyi,xi)::pairs, key) =


391 
if eq(key,keyi) then Some xi else gen_assoc eq (pairs,key);


392 


393 
(** Finding list elements and duplicates **)


394 


395 
(* find the position of an element in a list *)


396 
fun find(x,ys) =


397 
let fun f(y::ys,i) = if x=y then i else f(ys,i+1)


398 
 f(_,_) = raise LIST "find"


399 
in f(ys,0) end;


400 


401 
(*Returns the tail beginning with the first repeated element, or []. *)


402 
fun findrep [] = []


403 
 findrep (x::xs) = if x mem xs then x::xs else findrep xs;


404 


405 
fun distinct1 (seen, []) = rev seen


406 
 distinct1 (seen, x::xs) =


407 
if x mem seen then distinct1 (seen, xs)


408 
else distinct1 (x::seen, xs);


409 


410 
(*Makes a list of the distinct members of the input*)


411 
fun distinct xs = distinct1([],xs);


412 


413 


414 
(*Use the keyfun to make a list of (x,key) pairs.*)


415 
fun make_keylist (keyfun: 'a>'b) : 'a list > ('a * 'b) list =


416 
let fun keypair x = (x, keyfun x)


417 
in map keypair end;


418 


419 
(*Given a list of (x,key) pairs and a searchkey


420 
return the list of xs from each pair whose key equals searchkey*)


421 
fun keyfilter [] searchkey = []


422 
 keyfilter ((x,key)::pairs) searchkey =


423 
if key=searchkey then x :: keyfilter pairs searchkey


424 
else keyfilter pairs searchkey;


425 


426 
fun mapfilter (f: 'a > 'b option) ([]: 'a list) = [] : 'b list


427 
 mapfilter f (x::xs) =


428 
case (f x) of


429 
None => mapfilter f xs


430 
 Some y => y :: mapfilter f xs;


431 


432 


433 
(*Partition list into elements that satisfy predicate and those that don't.


434 
Preserves order of elements in both lists. *)


435 
fun partition (pred: 'a>bool) (ys: 'a list) : ('a list * 'a list) =


436 
let fun part ([], answer) = answer


437 
 part (x::xs, (ys, ns)) = if pred(x)


438 
then part (xs, (x::ys, ns))


439 
else part (xs, (ys, x::ns))


440 
in part (rev ys, ([],[])) end;


441 


442 


443 
fun partition_eq (eq:'a * 'a > bool) =


444 
let fun part [] = []


445 
 part (x::ys) = let val (xs,xs') = partition (apl(x,eq)) ys


446 
in (x::xs)::(part xs') end


447 
in part end;


448 


449 


450 
(*Partition a list into buckets [ bi, b(i+1),...,bj ]


451 
putting x in bk if p(k)(x) holds. Preserve order of elements if possible.*)


452 
fun partition_list p i j =


453 
let fun part k xs =


454 
if k>j then


455 
(case xs of [] => []


456 
 _ => raise LIST "partition_list")


457 
else


458 
let val (ns,rest) = partition (p k) xs;


459 
in ns :: part(k+1)rest end


460 
in part i end;


461 


462 


463 
(*Insertion sort. Stable (does not reorder equal elements)


464 
'less' is lessthan test on type 'a. *)


465 
fun sort (less: 'a*'a > bool) =


466 
let fun insert (x, []) = [x]


467 
 insert (x, y::ys) =


468 
if less(y,x) then y :: insert (x,ys) else x::y::ys;


469 
fun sort1 [] = []


470 
 sort1 (x::xs) = insert (x, sort1 xs)


471 
in sort1 end;


472 


473 
(*Transitive Closure. Not Warshall's algorithm*)


474 
fun transitive_closure [] = []


475 
 transitive_closure ((x,ys)::ps) =


476 
let val qs = transitive_closure ps


477 
val zs = foldl (fn (zs,y) => assocs qs y union zs) (ys,ys)


478 
fun step(u,us) = (u, if x mem us then zs union us else us)


479 
in (x,zs) :: map step qs end;


480 


481 
(*** Converting integers to strings, generating identifiers, etc. ***)


482 


483 
(*Expand the number in the given base


484 
example: radixpand(2, 8) gives [1, 0, 0, 0] *)


485 
fun radixpand (base,num) : int list =


486 
let fun radix (n,tail) =


487 
if n<base then n :: tail


488 
else radix (n div base, (n mod base) :: tail)


489 
in radix (num,[]) end;


490 


491 
(*Expands a number into a string of characters starting from "zerochar"


492 
example: radixstring(2,"0", 8) gives "1000" *)


493 
fun radixstring (base,zerochar,num) =


494 
let val offset = ord(zerochar);


495 
fun chrof n = chr(offset+n)


496 
in implode (map chrof (radixpand (base,num))) end;


497 


498 
fun string_of_int n =


499 
if n < 0 then "~" ^ radixstring(10,"0",~n) else radixstring(10,"0",n);


500 


501 
val print_int = prs o string_of_int;


502 


503 
local


504 
val a = ord("a") and z = ord("z") and A = ord("A") and Z = ord("Z")


505 
and k0 = ord("0") and k9 = ord("9")


506 
in


507 


508 
(*Increment a list of letters like a reversed base 26 number.


509 
If head is "z", bumps chars in tail.


510 
Digits are incremented as if they were integers.


511 
"_" and "'" are not changed.


512 
For making variants of identifiers. *)


513 


514 
fun bump_int_list(c::cs) = if c="9" then "0" :: bump_int_list cs else


515 
if k0 <= ord(c) andalso ord(c) < k9 then chr(ord(c)+1) :: cs


516 
else "1" :: c :: cs


517 
 bump_int_list([]) = error("bump_int_list: not an identifier");


518 


519 
fun bump_list([],d) = [d]


520 
 bump_list(["'"],d) = [d,"'"]


521 
 bump_list("z"::cs,_) = "a" :: bump_list(cs,"a")


522 
 bump_list("Z"::cs,_) = "A" :: bump_list(cs,"A")


523 
 bump_list("9"::cs,_) = "0" :: bump_int_list cs


524 
 bump_list(c::cs,_) = let val k = ord(c)


525 
in if (a <= k andalso k < z) orelse (A <= k andalso k < Z) orelse


526 
(k0 <= k andalso k < k9) then chr(k+1) :: cs else


527 
if c="'" orelse c="_" then c :: bump_list(cs,"") else


528 
error("bump_list: not legal in identifier: " ^


529 
implode(rev(c::cs)))


530 
end;


531 


532 
end;


533 


534 
fun bump_string s : string = implode (rev (bump_list(rev(explode s),"")));


535 


536 


537 
(*** Operations on integer lists ***)


538 


539 
fun sum [] = 0


540 
 sum (n::ns) = n + sum ns;


541 


542 
fun max[m : int] = m


543 
 max(m::n::ns) = if m>n then max(m::ns) else max(n::ns)


544 
 max [] = raise LIST "max";


545 


546 
fun min[m : int] = m


547 
 min(m::n::ns) = if m<n then min(m::ns) else min(n::ns)


548 
 min [] = raise LIST "min";


549 


550 


551 
(*** Lexical scanning ***)


552 


553 
(* [x1,...,xi,...,xn] > ([x1,...,x(i1)], [xi,..., xn])


554 
where xi is the first element that does not satisfy the predicate*)


555 
fun take_prefix (pred : 'a > bool) (xs: 'a list) : 'a list * 'a list =


556 
let fun take (rxs, []) = (rev rxs, [])


557 
 take (rxs, x::xs) =


558 
if pred x then take(x::rxs, xs) else (rev rxs, x::xs)


559 
in take([],xs) end;


560 


561 
infix prefix;


562 
fun [] prefix _ = true


563 
 (x::xs) prefix (y::ys) = (x=y) andalso (xs prefix ys)


564 
 _ prefix _ = false;


565 


566 
(* [x1, x2, ..., xn] > [x1, s, x2, s, ..., s, xn] *)


567 
fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs


568 
 separate _ xs = xs;


569 


570 
(*space_implode "..." (explode "hello"); gives "h...e...l...l...o" *)


571 
fun space_implode a bs = implode (separate a bs);


572 


573 
fun quote s = "\"" ^ s ^ "\"";


574 


575 
(*Concatenate messages, one per line, into a string*)


576 
val cat_lines = implode o (map (apr(op^,"\n")));


577 


578 
(*Scan a list of characters into "words" composed of "letters" (recognized


579 
by is_let) and separated by any number of non"letters".*)


580 
fun scanwords is_let cs =


581 
let fun scan1 [] = []


582 
 scan1 cs =


583 
let val (lets, rest) = take_prefix is_let cs


584 
in implode lets :: scanwords is_let rest end;


585 
in scan1 (#2 (take_prefix (not o is_let) cs)) end;
