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