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