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