src/Pure/library.ML
author wenzelm
Mon Jan 13 18:20:35 1997 +0100 (1997-01-13)
changeset 2506 965127966331
parent 2471 09634c9cbf3c
child 2522 a1a18530c4ac
permissions -rw-r--r--
added datatype order;
     1 (*  Title:      Pure/library.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Copyright   1992  University of Cambridge
     5 
     6 Basic library: functions, options, pairs, booleans, lists, integers,
     7 strings, lists as sets, association lists, generic tables, balanced trees,
     8 orders, input / output, timing, filenames, misc functions.
     9 *)
    10 
    11 infix |> ~~ \ \\ orelf ins ins_string ins_int orf andf prefix upto downto
    12       mem mem_int mem_string union union_int union_string  
    13       inter inter_int inter_string subset subset_int subset_string subdir_of;
    14 
    15 
    16 structure Library =
    17 struct
    18 
    19 (** functions **)
    20 
    21 (*handy combinators*)
    22 fun curry f x y = f (x, y);
    23 fun uncurry f (x, y) = f x y;
    24 fun I x = x;
    25 fun K x y = x;
    26 
    27 (*reverse apply*)
    28 fun (x |> f) = f x;
    29 
    30 (*combine two functions forming the union of their domains*)
    31 fun (f orelf g) = fn x => f x handle Match => g x;
    32 
    33 (*application of (infix) operator to its left or right argument*)
    34 fun apl (x, f) y = f (x, y);
    35 fun apr (f, y) x = f (x, y);
    36 
    37 (*functional for pairs*)
    38 fun pairself f (x, y) = (f x, f y);
    39 
    40 (*function exponentiation: f(...(f x)...) with n applications of f*)
    41 fun funpow n f x =
    42   let fun rep (0, x) = x
    43         | rep (n, x) = rep (n - 1, f x)
    44   in rep (n, x) end;
    45 
    46 
    47 
    48 (** stamps **)
    49 
    50 type stamp = unit ref;
    51 val stamp: unit -> stamp = ref;
    52 
    53 
    54 
    55 (** options **)
    56 
    57 datatype 'a option = None | Some of 'a;
    58 
    59 exception OPTION of string;
    60 
    61 fun the (Some x) = x
    62   | the None = raise OPTION "the";
    63 
    64 fun if_none None y = y
    65   | if_none (Some x) _ = x;
    66 
    67 fun is_some (Some _) = true
    68   | is_some None = false;
    69 
    70 fun is_none (Some _) = false
    71   | is_none None = true;
    72 
    73 fun apsome f (Some x) = Some (f x)
    74   | apsome _ None = None;
    75 
    76 
    77 
    78 (** pairs **)
    79 
    80 fun pair x y = (x, y);
    81 fun rpair x y = (y, x);
    82 
    83 fun fst (x, y) = x;
    84 fun snd (x, y) = y;
    85 
    86 fun eq_fst ((x1, _), (x2, _)) = x1 = x2;
    87 fun eq_snd ((_, y1), (_, y2)) = y1 = y2;
    88 
    89 fun swap (x, y) = (y, x);
    90 
    91 (*apply the function to a component of a pair*)
    92 fun apfst f (x, y) = (f x, y);
    93 fun apsnd f (x, y) = (x, f y);
    94 
    95 
    96 
    97 (** booleans **)
    98 
    99 (* equality *)
   100 
   101 fun equal x y = x = y;
   102 fun not_equal x y = x <> y;
   103 
   104 
   105 (* operators for combining predicates *)
   106 
   107 fun (p orf q) = fn x => p x orelse q x;
   108 
   109 fun (p andf q) = fn x => p x andalso q x;
   110 
   111 fun notf p x = not (p x);
   112 
   113 
   114 (* predicates on lists *)
   115 
   116 fun orl [] = false
   117   | orl (x :: xs) = x orelse orl xs;
   118 
   119 fun andl [] = true
   120   | andl (x :: xs) = x andalso andl xs;
   121 
   122 (*Needed because several object-logics declare the theory, therefore structure,
   123   List.*)
   124 structure List_ = List;
   125 
   126 (*exists pred [x1, ..., xn] ===> pred x1 orelse ... orelse pred xn*)
   127 fun exists (pred: 'a -> bool) : 'a list -> bool =
   128   let fun boolf [] = false
   129         | boolf (x :: xs) = pred x orelse boolf xs
   130   in boolf end;
   131 
   132 (*forall pred [x1, ..., xn] ===> pred x1 andalso ... andalso pred xn*)
   133 fun forall (pred: 'a -> bool) : 'a list -> bool =
   134   let fun boolf [] = true
   135         | boolf (x :: xs) = pred x andalso boolf xs
   136   in boolf end;
   137 
   138 
   139 (* flags *)
   140 
   141 fun set flag = (flag := true; true);
   142 fun reset flag = (flag := false; false);
   143 fun toggle flag = (flag := not (! flag); ! flag);
   144 
   145 
   146 
   147 (** lists **)
   148 
   149 exception LIST of string;
   150 
   151 fun null [] = true
   152   | null (_ :: _) = false;
   153 
   154 fun hd [] = raise LIST "hd"
   155   | hd (x :: _) = x;
   156 
   157 fun tl [] = raise LIST "tl"
   158   | tl (_ :: xs) = xs;
   159 
   160 fun cons x xs = x :: xs;
   161 
   162 
   163 (* fold *)
   164 
   165 (*the following versions of fold are designed to fit nicely with infixes*)
   166 
   167 (*  (op @) (e, [x1, ..., xn])  ===>  ((e @ x1) @ x2) ... @ xn
   168     for operators that associate to the left (TAIL RECURSIVE)*)
   169 fun foldl (f: 'a * 'b -> 'a) : 'a * 'b list -> 'a =
   170   let fun itl (e, [])  = e
   171         | itl (e, a::l) = itl (f(e, a), l)
   172   in  itl end;
   173 
   174 (*  (op @) ([x1, ..., xn], e)  ===>   x1 @ (x2 ... @ (xn @ e))
   175     for operators that associate to the right (not tail recursive)*)
   176 fun foldr f (l, e) =
   177   let fun itr [] = e
   178         | itr (a::l) = f(a, itr l)
   179   in  itr l  end;
   180 
   181 (*  (op @) [x1, ..., xn]  ===>   x1 @ (x2 ... @ (x[n-1] @ xn))
   182     for n > 0, operators that associate to the right (not tail recursive)*)
   183 fun foldr1 f l =
   184   let fun itr [x] = x                       (* FIXME [] case: elim warn (?) *)
   185         | itr (x::l) = f(x, itr l)
   186   in  itr l  end;
   187 
   188 
   189 (* basic list functions *)
   190 
   191 (*length of a list, should unquestionably be a standard function*)
   192 local fun length1 (n, [])  = n   (*TAIL RECURSIVE*)
   193         | length1 (n, x :: xs) = length1 (n + 1, xs)
   194 in  fun length l = length1 (0, l) end;
   195 
   196 (*take the first n elements from a list*)
   197 fun take (n, []) = []
   198   | take (n, x :: xs) =
   199       if n > 0 then x :: take (n - 1, xs) else [];
   200 
   201 (*drop the first n elements from a list*)
   202 fun drop (n, []) = []
   203   | drop (n, x :: xs) =
   204       if n > 0 then drop (n - 1, xs) else x :: xs;
   205 
   206 (*return nth element of a list, where 0 designates the first element;
   207   raise EXCEPTION if list too short*)
   208 fun nth_elem NL =
   209   (case drop NL of
   210     [] => raise LIST "nth_elem"
   211   | x :: _ => x);
   212 
   213 (*last element of a list*)
   214 fun last_elem [] = raise LIST "last_elem"
   215   | last_elem [x] = x
   216   | last_elem (_ :: xs) = last_elem xs;
   217 
   218 (*find the position of an element in a list*)
   219 fun find (x, ys) =
   220   let fun f (y :: ys, i) = if x = y then i else f (ys, i + 1)
   221         | f (_, _) = raise LIST "find"
   222   in f (ys, 0) end;
   223 
   224 (*flatten a list of lists to a list*)
   225 fun flat (ls: 'c list list) : 'c list = foldr (op @) (ls, []);
   226 
   227 
   228 (*like Lisp's MAPC -- seq proc [x1, ..., xn] evaluates
   229   (proc x1; ...; proc xn) for side effects*)
   230 fun seq (proc: 'a -> unit) : 'a list -> unit =
   231   let fun seqf [] = ()
   232         | seqf (x :: xs) = (proc x; seqf xs)
   233   in seqf end;
   234 
   235 
   236 (*separate s [x1, x2, ..., xn]  ===>  [x1, s, x2, s, ..., s, xn]*)
   237 fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
   238   | separate _ xs = xs;
   239 
   240 (*make the list [x, x, ..., x] of length n*)
   241 fun replicate n (x: 'a) : 'a list =
   242   let fun rep (0, xs) = xs
   243         | rep (n, xs) = rep (n - 1, x :: xs)
   244   in
   245     if n < 0 then raise LIST "replicate"
   246     else rep (n, [])
   247   end;
   248 
   249 
   250 (* filter *)
   251 
   252 (*copy the list preserving elements that satisfy the predicate*)
   253 fun filter (pred: 'a->bool) : 'a list -> 'a list =
   254   let fun filt [] = []
   255         | filt (x :: xs) = if pred x then x :: filt xs else filt xs
   256   in filt end;
   257 
   258 fun filter_out f = filter (not o f);
   259 
   260 
   261 fun mapfilter (f: 'a -> 'b option) ([]: 'a list) = [] : 'b list
   262   | mapfilter f (x :: xs) =
   263       (case f x of
   264         None => mapfilter f xs
   265       | Some y => y :: mapfilter f xs);
   266 
   267 
   268 fun find_first _ [] = None
   269   | find_first pred (x :: xs) =
   270       if pred x then Some x else find_first pred xs;
   271 
   272 
   273 (* lists of pairs *)
   274 
   275 fun map2 _ ([], []) = []
   276   | map2 f (x :: xs, y :: ys) = (f (x, y) :: map2 f (xs, ys))
   277   | map2 _ _ = raise LIST "map2";
   278 
   279 fun exists2 _ ([], []) = false
   280   | exists2 pred (x :: xs, y :: ys) = pred (x, y) orelse exists2 pred (xs, ys)
   281   | exists2 _ _ = raise LIST "exists2";
   282 
   283 fun forall2 _ ([], []) = true
   284   | forall2 pred (x :: xs, y :: ys) = pred (x, y) andalso forall2 pred (xs, ys)
   285   | forall2 _ _ = raise LIST "forall2";
   286 
   287 (*combine two lists forming a list of pairs:
   288   [x1, ..., xn] ~~ [y1, ..., yn]  ===>  [(x1, y1), ..., (xn, yn)]*)
   289 fun [] ~~ [] = []
   290   | (x :: xs) ~~ (y :: ys) = (x, y) :: (xs ~~ ys)
   291   | _ ~~ _ = raise LIST "~~";
   292 
   293 
   294 (*inverse of ~~; the old 'split':
   295   [(x1, y1), ..., (xn, yn)]  ===>  ([x1, ..., xn], [y1, ..., yn])*)
   296 fun split_list (l: ('a * 'b) list) = (map #1 l, map #2 l);
   297 
   298 
   299 (* prefixes, suffixes *)
   300 
   301 fun [] prefix _ = true
   302   | (x :: xs) prefix (y :: ys) = x = y andalso (xs prefix ys)
   303   | _ prefix _ = false;
   304 
   305 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., x(i-1)], [xi, ..., xn])
   306    where xi is the first element that does not satisfy the predicate*)
   307 fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
   308   let fun take (rxs, []) = (rev rxs, [])
   309         | take (rxs, x :: xs) =
   310             if  pred x  then  take(x :: rxs, xs)  else  (rev rxs, x :: xs)
   311   in  take([], xs)  end;
   312 
   313 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., xi], [x(i+1), ..., xn])
   314    where xi is the last element that does not satisfy the predicate*)
   315 fun take_suffix _ [] = ([], [])
   316   | take_suffix pred (x :: xs) =
   317       (case take_suffix pred xs of
   318         ([], sffx) => if pred x then ([], x :: sffx) else ([x], sffx)
   319       | (prfx, sffx) => (x :: prfx, sffx));
   320 
   321 
   322 
   323 (** integers **)
   324 
   325 fun inc i = i := ! i + 1;
   326 fun dec i = i := ! i - 1;
   327 
   328 
   329 (* lists of integers *)
   330 
   331 (*make the list [from, from + 1, ..., to]*)
   332 fun (from upto to) =
   333   if from > to then [] else from :: ((from + 1) upto to);
   334 
   335 (*make the list [from, from - 1, ..., to]*)
   336 fun (from downto to) =
   337   if from < to then [] else from :: ((from - 1) downto to);
   338 
   339 (*predicate: downto0 (is, n) <=> is = [n, n - 1, ..., 0]*)
   340 fun downto0 (i :: is, n) = i = n andalso downto0 (is, n - 1)
   341   | downto0 ([], n) = n = ~1;
   342 
   343 
   344 (* convert integers to strings *)
   345 
   346 (*expand the number in the given base;
   347   example: radixpand (2, 8) gives [1, 0, 0, 0]*)
   348 fun radixpand (base, num) : int list =
   349   let
   350     fun radix (n, tail) =
   351       if n < base then n :: tail
   352       else radix (n div base, (n mod base) :: tail)
   353   in radix (num, []) end;
   354 
   355 (*expands a number into a string of characters starting from "zerochar";
   356   example: radixstring (2, "0", 8) gives "1000"*)
   357 fun radixstring (base, zerochar, num) =
   358   let val offset = ord zerochar;
   359       fun chrof n = chr (offset + n)
   360   in implode (map chrof (radixpand (base, num))) end;
   361 
   362 
   363 fun string_of_int n =
   364   if n < 0 then "~" ^ radixstring (10, "0", ~n) else radixstring (10, "0", n);
   365 
   366 
   367 
   368 (** strings **)
   369 
   370 fun is_letter ch =
   371   ord "A" <= ord ch andalso ord ch <= ord "Z" orelse
   372   ord "a" <= ord ch andalso ord ch <= ord "z";
   373 
   374 fun is_digit ch =
   375   ord "0" <= ord ch andalso ord ch <= ord "9";
   376 
   377 (*letter or _ or prime (')*)
   378 fun is_quasi_letter "_" = true
   379   | is_quasi_letter "'" = true
   380   | is_quasi_letter ch = is_letter ch;
   381 
   382 (*white space: blanks, tabs, newlines, formfeeds*)
   383 val is_blank : string -> bool =
   384   fn " " => true | "\t" => true | "\n" => true | "\^L" => true | _ => false;
   385 
   386 val is_letdig = is_quasi_letter orf is_digit;
   387 
   388 (*printable chars*)
   389 fun is_printable c = ord c > ord " " andalso ord c <= ord "~";
   390 
   391 
   392 (*lower all chars of string*)
   393 val to_lower =
   394   let
   395     fun lower ch =
   396       if ch >= "A" andalso ch <= "Z" then
   397         chr (ord ch - ord "A" + ord "a")
   398       else ch;
   399   in implode o (map lower) o explode end;
   400 
   401 
   402 (*enclose in brackets*)
   403 fun enclose lpar rpar str = lpar ^ str ^ rpar;
   404 
   405 (*simple quoting (does not escape special chars)*)
   406 val quote = enclose "\"" "\"";
   407 
   408 (*space_implode "..." (explode "hello"); gives "h...e...l...l...o"*)
   409 fun space_implode a bs = implode (separate a bs);
   410 
   411 val commas = space_implode ", ";
   412 val commas_quote = commas o map quote;
   413 
   414 (*concatenate messages, one per line, into a string*)
   415 val cat_lines = space_implode "\n";
   416 
   417 (*space_explode "." "h.e..l.lo"; gives ["h", "e", "l", "lo"]*)
   418 fun space_explode sep s =
   419   let fun divide [] "" = []
   420         | divide [] part = [part]
   421         | divide (c::s) part =
   422             if c = sep then
   423               (if part = "" then divide s "" else part :: divide s "")
   424             else divide s (part ^ c)
   425   in divide (explode s) "" end;
   426 
   427 
   428 (** lists as sets **)
   429 
   430 (*membership in a list*)
   431 fun x mem [] = false
   432   | x mem (y :: ys) = x = y orelse x mem ys;
   433 
   434 (*membership in a list, optimized version for ints*)
   435 fun (x:int) mem_int [] = false
   436   | x mem_int (y :: ys) = x = y orelse x mem_int ys;
   437 
   438 (*membership in a list, optimized version for strings*)
   439 fun (x:string) mem_string [] = false
   440   | x mem_string (y :: ys) = x = y orelse x mem_string ys;
   441 
   442 (*generalized membership test*)
   443 fun gen_mem eq (x, []) = false
   444   | gen_mem eq (x, y :: ys) = eq (x, y) orelse gen_mem eq (x, ys);
   445 
   446 
   447 (*insertion into list if not already there*)
   448 fun (x ins xs) = if x mem xs then xs else x :: xs;
   449 
   450 (*insertion into list, optimized version for ints*)
   451 fun (x ins_int xs) = if x mem_int xs then xs else x :: xs;
   452 
   453 (*insertion into list, optimized version for strings*)
   454 fun (x ins_string xs) = if x mem_string xs then xs else x :: xs;
   455 
   456 (*generalized insertion*)
   457 fun gen_ins eq (x, xs) = if gen_mem eq (x, xs) then xs else x :: xs;
   458 
   459 
   460 (*union of sets represented as lists: no repetitions*)
   461 fun xs union [] = xs
   462   | [] union ys = ys
   463   | (x :: xs) union ys = xs union (x ins ys);
   464 
   465 (*union of sets, optimized version for ints*)
   466 fun (xs:int list) union_int [] = xs
   467   | [] union_int ys = ys
   468   | (x :: xs) union_int ys = xs union_int (x ins_int ys);
   469 
   470 (*union of sets, optimized version for strings*)
   471 fun (xs:string list) union_string [] = xs
   472   | [] union_string ys = ys
   473   | (x :: xs) union_string ys = xs union_string (x ins_string ys);
   474 
   475 (*generalized union*)
   476 fun gen_union eq (xs, []) = xs
   477   | gen_union eq ([], ys) = ys
   478   | gen_union eq (x :: xs, ys) = gen_union eq (xs, gen_ins eq (x, ys));
   479 
   480 
   481 (*intersection*)
   482 fun [] inter ys = []
   483   | (x :: xs) inter ys =
   484       if x mem ys then x :: (xs inter ys) else xs inter ys;
   485 
   486 (*intersection, optimized version for ints*)
   487 fun ([]:int list) inter_int ys = []
   488   | (x :: xs) inter_int ys =
   489       if x mem_int ys then x :: (xs inter_int ys) else xs inter_int ys;
   490 
   491 (*intersection, optimized version for strings *)
   492 fun ([]:string list) inter_string ys = []
   493   | (x :: xs) inter_string ys =
   494       if x mem_string ys then x :: (xs inter_string ys) else xs inter_string ys;
   495 
   496 
   497 (*subset*)
   498 fun [] subset ys = true
   499   | (x :: xs) subset ys = x mem ys andalso xs subset ys;
   500 
   501 (*subset, optimized version for ints*)
   502 fun ([]:int list) subset_int ys = true
   503   | (x :: xs) subset_int ys = x mem_int ys andalso xs subset_int ys;
   504 
   505 (*subset, optimized version for strings*)
   506 fun ([]:string list) subset_string ys = true
   507   | (x :: xs) subset_string ys = x mem_string ys andalso xs subset_string ys;
   508 
   509 (*set equality for strings*)
   510 fun eq_set_string ((xs:string list), ys) =
   511   xs = ys orelse (xs subset_string ys andalso ys subset_string xs);
   512 
   513 fun gen_subset eq (xs, ys) = forall (fn x => gen_mem eq (x, ys)) xs;
   514 
   515 
   516 (*removing an element from a list WITHOUT duplicates*)
   517 fun (y :: ys) \ x = if x = y then ys else y :: (ys \ x)
   518   | [] \ x = [];
   519 
   520 fun ys \\ xs = foldl (op \) (ys,xs);
   521 
   522 (*removing an element from a list -- possibly WITH duplicates*)
   523 fun gen_rem eq (xs, y) = filter_out (fn x => eq (x, y)) xs;
   524 
   525 fun gen_rems eq = foldl (gen_rem eq);
   526 
   527 
   528 (*makes a list of the distinct members of the input; preserves order, takes
   529   first of equal elements*)
   530 fun gen_distinct eq lst =
   531   let
   532     val memb = gen_mem eq;
   533 
   534     fun dist (rev_seen, []) = rev rev_seen
   535       | dist (rev_seen, x :: xs) =
   536           if memb (x, rev_seen) then dist (rev_seen, xs)
   537           else dist (x :: rev_seen, xs);
   538   in
   539     dist ([], lst)
   540   end;
   541 
   542 fun distinct l = gen_distinct (op =) l;
   543 
   544 
   545 (*returns the tail beginning with the first repeated element, or []*)
   546 fun findrep [] = []
   547   | findrep (x :: xs) = if x mem xs then x :: xs else findrep xs;
   548 
   549 
   550 (*returns a list containing all repeated elements exactly once; preserves
   551   order, takes first of equal elements*)
   552 fun gen_duplicates eq lst =
   553   let
   554     val memb = gen_mem eq;
   555 
   556     fun dups (rev_dups, []) = rev rev_dups
   557       | dups (rev_dups, x :: xs) =
   558           if memb (x, rev_dups) orelse not (memb (x, xs)) then
   559             dups (rev_dups, xs)
   560           else dups (x :: rev_dups, xs);
   561   in
   562     dups ([], lst)
   563   end;
   564 
   565 fun duplicates l = gen_duplicates (op =) l;
   566 
   567 
   568 
   569 (** association lists **)
   570 
   571 (*association list lookup*)
   572 fun assoc ([], key) = None
   573   | assoc ((keyi, xi) :: pairs, key) =
   574       if key = keyi then Some xi else assoc (pairs, key);
   575 
   576 (*association list lookup, optimized version for ints*)
   577 fun assoc_int ([], (key:int)) = None
   578   | assoc_int ((keyi, xi) :: pairs, key) =
   579       if key = keyi then Some xi else assoc_int (pairs, key);
   580 
   581 (*association list lookup, optimized version for strings*)
   582 fun assoc_string ([], (key:string)) = None
   583   | assoc_string ((keyi, xi) :: pairs, key) =
   584       if key = keyi then Some xi else assoc_string (pairs, key);
   585 
   586 (*association list lookup, optimized version for string*ints*)
   587 fun assoc_string_int ([], (key:string*int)) = None
   588   | assoc_string_int ((keyi, xi) :: pairs, key) =
   589       if key = keyi then Some xi else assoc_string_int (pairs, key);
   590 
   591 fun assocs ps x =
   592   (case assoc (ps, x) of
   593     None => []
   594   | Some ys => ys);
   595 
   596 (*two-fold association list lookup*)
   597 fun assoc2 (aal, (key1, key2)) =
   598   (case assoc (aal, key1) of
   599     Some al => assoc (al, key2)
   600   | None => None);
   601 
   602 (*generalized association list lookup*)
   603 fun gen_assoc eq ([], key) = None
   604   | gen_assoc eq ((keyi, xi) :: pairs, key) =
   605       if eq (key, keyi) then Some xi else gen_assoc eq (pairs, key);
   606 
   607 (*association list update*)
   608 fun overwrite (al, p as (key, _)) =
   609   let fun over ((q as (keyi, _)) :: pairs) =
   610             if keyi = key then p :: pairs else q :: (over pairs)
   611         | over [] = [p]
   612   in over al end;
   613 
   614 
   615 
   616 (** generic tables **)
   617 
   618 (*Tables are supposed to be 'efficient' encodings of lists of elements distinct
   619   wrt. an equality "eq". The extend and merge operations below are optimized
   620   for long-term space efficiency.*)
   621 
   622 (*append (new) elements to a table*)
   623 fun generic_extend _ _ _ tab [] = tab
   624   | generic_extend eq dest_tab mk_tab tab1 lst2 =
   625       let
   626         val lst1 = dest_tab tab1;
   627         val new_lst2 = gen_rems eq (lst2, lst1);
   628       in
   629         if null new_lst2 then tab1
   630         else mk_tab (lst1 @ new_lst2)
   631       end;
   632 
   633 (*append (new) elements of 2nd table to 1st table*)
   634 fun generic_merge eq dest_tab mk_tab tab1 tab2 =
   635   let
   636     val lst1 = dest_tab tab1;
   637     val lst2 = dest_tab tab2;
   638     val new_lst2 = gen_rems eq (lst2, lst1);
   639   in
   640     if null new_lst2 then tab1
   641     else if gen_subset eq (lst1, lst2) then tab2
   642     else mk_tab (lst1 @ new_lst2)
   643   end;
   644 
   645 
   646 (*lists as tables*)
   647 fun extend_list tab = generic_extend (op =) I I tab;
   648 fun merge_lists tab = generic_merge (op =) I I tab;
   649 
   650 fun merge_rev_lists xs [] = xs
   651   | merge_rev_lists [] ys = ys
   652   | merge_rev_lists xs (y :: ys) =
   653       (if y mem xs then I else cons y) (merge_rev_lists xs ys);
   654 
   655 
   656 
   657 (** balanced trees **)
   658 
   659 exception Balance;      (*indicates non-positive argument to balancing fun*)
   660 
   661 (*balanced folding; avoids deep nesting*)
   662 fun fold_bal f [x] = x
   663   | fold_bal f [] = raise Balance
   664   | fold_bal f xs =
   665       let val k = length xs div 2
   666       in  f (fold_bal f (take(k, xs)),
   667              fold_bal f (drop(k, xs)))
   668       end;
   669 
   670 (*construct something of the form f(...g(...(x)...)) for balanced access*)
   671 fun access_bal (f, g, x) n i =
   672   let fun acc n i =     (*1<=i<=n*)
   673           if n=1 then x else
   674           let val n2 = n div 2
   675           in  if i<=n2 then f (acc n2 i)
   676                        else g (acc (n-n2) (i-n2))
   677           end
   678   in  if 1<=i andalso i<=n then acc n i else raise Balance  end;
   679 
   680 (*construct ALL such accesses; could try harder to share recursive calls!*)
   681 fun accesses_bal (f, g, x) n =
   682   let fun acc n =
   683           if n=1 then [x] else
   684           let val n2 = n div 2
   685               val acc2 = acc n2
   686           in  if n-n2=n2 then map f acc2 @ map g acc2
   687                          else map f acc2 @ map g (acc (n-n2)) end
   688   in  if 1<=n then acc n else raise Balance  end;
   689 
   690 
   691 
   692 (** orders **)
   693 
   694 datatype order = LESS | EQUAL | GREATER;
   695 
   696 fun intord (i, j: int) =
   697   if i < j then LESS
   698   else if i = j then EQUAL
   699   else GREATER;
   700 
   701 fun stringord (a, b: string) =
   702   if a < b then LESS
   703   else if a = b then EQUAL
   704   else GREATER;
   705 
   706 
   707 
   708 (** input / output **)
   709 
   710 val cd = OS.FileSys.chDir;
   711 val pwd = OS.FileSys.getDir;
   712 
   713 val prs_fn = ref(fn s => TextIO.output (TextIO.stdOut, s));
   714 
   715 fun prs s = !prs_fn s;
   716 fun writeln s = prs (s ^ "\n");
   717 
   718 (* TextIO.output to LaTeX / xdvi *)
   719 fun latex s = 
   720         execute ( "( cd /tmp ; echo \"" ^ s ^
   721         "\" | isa2latex -s > $$.tex ; latex $$.tex ; xdvi $$.dvi ; rm $$.* ) > /dev/null &" ) ;
   722 
   723 (*print warning*)
   724 val warning_fn = ref(fn s => TextIO.output (TextIO.stdOut, s ^ "\n"));
   725 fun warning s = !warning_fn ("Warning: " ^ s);
   726 
   727 (*print error message and abort to top level*)
   728 
   729 val error_fn = ref(fn s => TextIO.output (TextIO.stdOut, s ^ "\n"));
   730 
   731 exception ERROR;
   732 fun error msg = (!error_fn msg; raise ERROR);
   733 fun sys_error msg = (!error_fn "*** SYSTEM ERROR ***"; error msg);
   734 
   735 fun assert p msg = if p then () else error msg;
   736 fun deny p msg = if p then error msg else ();
   737 
   738 (*Assert pred for every member of l, generating a message if pred fails*)
   739 fun assert_all pred l msg_fn = 
   740   let fun asl [] = ()
   741         | asl (x::xs) = if pred x then asl xs
   742                         else error (msg_fn x)
   743   in  asl l  end;
   744 
   745 (*for the "test" target in Makefiles -- signifies successful termination*)
   746 fun maketest msg =
   747   (writeln msg; 
   748    let val os = TextIO.openOut "test" 
   749    in  TextIO.output (os, "Test examples ran successfully\n");
   750        TextIO.closeOut os
   751    end);
   752 
   753 
   754 (*print a list surrounded by the brackets lpar and rpar, with comma separator
   755   print nothing for empty list*)
   756 fun print_list (lpar, rpar, pre: 'a -> unit) (l : 'a list) =
   757   let fun prec x = (prs ","; pre x)
   758   in
   759     (case l of
   760       [] => ()
   761     | x::l => (prs lpar; pre x; seq prec l; prs rpar))
   762   end;
   763 
   764 (*print a list of items separated by newlines*)
   765 fun print_list_ln (pre: 'a -> unit) : 'a list -> unit =
   766   seq (fn x => (pre x; writeln ""));
   767 
   768 
   769 val print_int = prs o string_of_int;
   770 
   771 
   772 
   773 (** timing **)
   774 
   775 (*unconditional timing function*)
   776 fun timeit x = cond_timeit true x;
   777 
   778 (*timed application function*)
   779 fun timeap f x = timeit (fn () => f x);
   780 
   781 (*timed "use" function, printing filenames*)
   782 fun time_use fname = timeit (fn () =>
   783   (writeln ("\n**** Starting " ^ fname ^ " ****"); use fname;
   784    writeln ("\n**** Finished " ^ fname ^ " ****")));
   785 
   786 (*For Makefiles: use the file, but exit with error code if errors found.*)
   787 fun exit_use fname = use fname handle _ => exit 1;
   788 
   789 
   790 (** filenames and paths **)
   791 
   792 (*Convert UNIX filename of the form "path/file" to "path/" and "file";
   793   if filename contains no slash, then it returns "" and "file"*)
   794 val split_filename =
   795   (pairself implode) o take_suffix (not_equal "/") o explode;
   796 
   797 val base_name = #2 o split_filename;
   798 
   799 (*Merge splitted filename (path and file);
   800   if path does not end with one a slash is appended*)
   801 fun tack_on "" name = name
   802   | tack_on path name =
   803       if last_elem (explode path) = "/" then path ^ name
   804       else path ^ "/" ^ name;
   805 
   806 (*Remove the extension of a filename, i.e. the part after the last '.'*)
   807 val remove_ext = implode o #1 o take_suffix (not_equal ".") o explode;
   808 
   809 (*Make relative path to reach an absolute location from a different one*)
   810 fun relative_path cur_path dest_path =
   811   let (*Remove common beginning of both paths and make relative path*)
   812       fun mk_relative [] [] = []
   813         | mk_relative [] ds = ds
   814         | mk_relative cs [] = map (fn _ => "..") cs
   815         | mk_relative (c::cs) (d::ds) =
   816             if c = d then mk_relative cs ds
   817             else ".." :: map (fn _ => "..") cs @ (d::ds);
   818   in if cur_path = "" orelse hd (explode cur_path) <> "/" orelse
   819         dest_path = "" orelse hd (explode dest_path) <> "/" then
   820        error "Relative or empty path passed to relative_path"
   821      else ();
   822      space_implode "/" (mk_relative (space_explode "/" cur_path)
   823                                     (space_explode "/" dest_path))
   824   end;
   825 
   826 (*Determine if absolute path1 is a subdirectory of absolute path2*)
   827 fun path1 subdir_of path2 =
   828   if hd (explode path1) <> "/" orelse hd (explode path2) <> "/" then
   829     error "Relative or empty path passed to subdir_of"
   830   else (space_explode "/" path2) prefix (space_explode "/" path1);
   831 
   832 fun absolute_path cwd file =
   833   let fun rm_points [] result = rev result
   834         | rm_points (".."::ds) result = rm_points ds (tl result)
   835         | rm_points ("."::ds) result = rm_points ds result
   836         | rm_points (d::ds) result = rm_points ds (d::result);
   837   in if file = "" then ""
   838      else if hd (explode file) = "/" then file
   839      else "/" ^ space_implode "/"
   840                   (rm_points (space_explode "/" (tack_on cwd file)) [])
   841   end;
   842 
   843 
   844 (** misc functions **)
   845 
   846 (*use the keyfun to make a list of (x, key) pairs*)
   847 fun make_keylist (keyfun: 'a->'b) : 'a list -> ('a * 'b) list =
   848   let fun keypair x = (x, keyfun x)
   849   in map keypair end;
   850 
   851 (*given a list of (x, key) pairs and a searchkey
   852   return the list of xs from each pair whose key equals searchkey*)
   853 fun keyfilter [] searchkey = []
   854   | keyfilter ((x, key) :: pairs) searchkey =
   855       if key = searchkey then x :: keyfilter pairs searchkey
   856       else keyfilter pairs searchkey;
   857 
   858 
   859 (*Partition list into elements that satisfy predicate and those that don't.
   860   Preserves order of elements in both lists.*)
   861 fun partition (pred: 'a->bool) (ys: 'a list) : ('a list * 'a list) =
   862     let fun part ([], answer) = answer
   863           | part (x::xs, (ys, ns)) = if pred(x)
   864             then  part (xs, (x::ys, ns))
   865             else  part (xs, (ys, x::ns))
   866     in  part (rev ys, ([], []))  end;
   867 
   868 
   869 fun partition_eq (eq:'a * 'a -> bool) =
   870     let fun part [] = []
   871           | part (x::ys) = let val (xs, xs') = partition (apl(x, eq)) ys
   872                            in (x::xs)::(part xs') end
   873     in part end;
   874 
   875 
   876 (*Partition a list into buckets  [ bi, b(i+1), ..., bj ]
   877    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
   878 fun partition_list p i j =
   879   let fun part k xs =
   880             if k>j then
   881               (case xs of [] => []
   882                          | _ => raise LIST "partition_list")
   883             else
   884             let val (ns, rest) = partition (p k) xs;
   885             in  ns :: part(k+1)rest  end
   886   in  part i end;
   887 
   888 
   889 (* sorting *)
   890 
   891 (*insertion sort; stable (does not reorder equal elements)
   892   'less' is less-than test on type 'a*)
   893 fun sort (less: 'a*'a -> bool) =
   894   let fun insert (x, []) = [x]
   895         | insert (x, y::ys) =
   896               if less(y, x) then y :: insert (x, ys) else x::y::ys;
   897       fun sort1 [] = []
   898         | sort1 (x::xs) = insert (x, sort1 xs)
   899   in  sort1  end;
   900 
   901 (*sort strings*)
   902 val sort_strings = sort (op <= : string * string -> bool);
   903 
   904 
   905 (* transitive closure (not Warshall's algorithm) *)
   906 
   907 fun transitive_closure [] = []
   908   | transitive_closure ((x, ys)::ps) =
   909       let val qs = transitive_closure ps
   910           val zs = foldl (fn (zs, y) => assocs qs y union_string zs) (ys, ys)
   911           fun step(u, us) = (u, if x mem_string us then zs union_string us 
   912                                 else us)
   913       in (x, zs) :: map step qs end;
   914 
   915 
   916 (** Simple random number generator; not guaranteed to be good, because modulus
   917     has been reduced from 2^31-1 to 2^29-1 to prevent integer overflows
   918 **)
   919 local val a = 16807.0  and  m = 536870911.0  (* 2^29 - 1 *)
   920 in  fun nextrandom seed =
   921           let val t = a*seed
   922           in  t - m * real(floor(t/m))  end
   923 end;
   924 
   925 (* generating identifiers *)
   926 
   927 local
   928   val a = ord "a" and z = ord "z" and A = ord "A" and Z = ord "Z"
   929   and k0 = ord "0" and k9 = ord "9"
   930 
   931   val seedr = ref 10000.0;
   932 in
   933 
   934 (*Maps 0-63 to A-Z, a-z, 0-9 or _ or ' for generating random identifiers*)
   935 fun newid n = 
   936   let fun char i =
   937                if i<26 then chr (A+i)
   938           else if i<52 then chr (a+i-26)
   939           else if i<62 then chr (k0+i-52)
   940           else if i=62 then "_"
   941           else  (*i=63*)    "'"
   942   in  implode (map char (radixpand (64,n)))  end;
   943 
   944 (*Randomly generated identifiers with given prefix; MUST start with a letter*)
   945 fun gensym pre = pre ^ 
   946                  (#1(newid (floor (!seedr)), 
   947                      seedr := nextrandom (!seedr)))
   948 
   949 (*Increment a list of letters like a reversed base 26 number.
   950   If head is "z", bumps chars in tail.
   951   Digits are incremented as if they were integers.
   952   "_" and "'" are not changed.
   953   For making variants of identifiers.*)
   954 
   955 fun bump_int_list(c::cs) = if c="9" then "0" :: bump_int_list cs else
   956         if k0 <= ord(c) andalso ord(c) < k9 then chr(ord(c)+1) :: cs
   957         else "1" :: c :: cs
   958   | bump_int_list([]) = error("bump_int_list: not an identifier");
   959 
   960 fun bump_list([], d) = [d]
   961   | bump_list(["'"], d) = [d, "'"]
   962   | bump_list("z"::cs, _) = "a" :: bump_list(cs, "a")
   963   | bump_list("Z"::cs, _) = "A" :: bump_list(cs, "A")
   964   | bump_list("9"::cs, _) = "0" :: bump_int_list cs
   965   | bump_list(c::cs, _) = let val k = ord(c)
   966         in if (a <= k andalso k < z) orelse (A <= k andalso k < Z) orelse
   967               (k0 <= k andalso k < k9) then chr(k+1) :: cs else
   968            if c="'" orelse c="_" then c :: bump_list(cs, "") else
   969                 error("bump_list: not legal in identifier: " ^
   970                         implode(rev(c::cs)))
   971         end;
   972 
   973 end;
   974 
   975 fun bump_string s : string = implode (rev (bump_list(rev(explode s), "")));
   976 
   977 
   978 (* lexical scanning *)
   979 
   980 (*scan a list of characters into "words" composed of "letters" (recognized by
   981   is_let) and separated by any number of non-"letters"*)
   982 fun scanwords is_let cs =
   983   let fun scan1 [] = []
   984         | scan1 cs =
   985             let val (lets, rest) = take_prefix is_let cs
   986             in implode lets :: scanwords is_let rest end;
   987   in scan1 (#2 (take_prefix (not o is_let) cs)) end;
   988 
   989 end;
   990 
   991 (*Variable-branching trees: for proof terms*)
   992 datatype 'a mtree = Join of 'a * 'a mtree list;
   993 
   994 open Library;