src/Pure/library.ML
author wenzelm
Wed Apr 16 18:16:02 1997 +0200 (1997-04-16)
changeset 2958 7837471d2f27
parent 2806 772f6bba48a1
child 2978 83a4c4f79dcd
permissions -rw-r--r--
improved inc, dec;
added set_ap;
     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 set_ap 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 | _ => false;
   394 
   395 val is_letdig = is_quasi_letter orf is_digit;
   396 
   397 (*printable chars*)
   398 fun is_printable c = ord c > ord " " andalso ord c <= ord "~";
   399 
   400 
   401 (*lower all chars of string*)
   402 val to_lower =
   403   let
   404     fun lower ch =
   405       if ch >= "A" andalso ch <= "Z" then
   406         chr (ord ch - ord "A" + ord "a")
   407       else ch;
   408   in implode o (map lower) o explode end;
   409 
   410 
   411 (*enclose in brackets*)
   412 fun enclose lpar rpar str = lpar ^ str ^ rpar;
   413 
   414 (*simple quoting (does not escape special chars)*)
   415 val quote = enclose "\"" "\"";
   416 
   417 (*space_implode "..." (explode "hello"); gives "h...e...l...l...o"*)
   418 fun space_implode a bs = implode (separate a bs);
   419 
   420 val commas = space_implode ", ";
   421 val commas_quote = commas o map quote;
   422 
   423 (*concatenate messages, one per line, into a string*)
   424 val cat_lines = space_implode "\n";
   425 
   426 (*space_explode "." "h.e..l.lo"; gives ["h", "e", "l", "lo"]*)
   427 fun space_explode sep s =
   428   let fun divide [] "" = []
   429         | divide [] part = [part]
   430         | divide (c::s) part =
   431             if c = sep then
   432               (if part = "" then divide s "" else part :: divide s "")
   433             else divide s (part ^ c)
   434   in divide (explode s) "" end;
   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 
   554 (*returns the tail beginning with the first repeated element, or []*)
   555 fun findrep [] = []
   556   | findrep (x :: xs) = if x mem xs then x :: xs else findrep xs;
   557 
   558 
   559 (*returns a list containing all repeated elements exactly once; preserves
   560   order, takes first of equal elements*)
   561 fun gen_duplicates eq lst =
   562   let
   563     val memb = gen_mem eq;
   564 
   565     fun dups (rev_dups, []) = rev rev_dups
   566       | dups (rev_dups, x :: xs) =
   567           if memb (x, rev_dups) orelse not (memb (x, xs)) then
   568             dups (rev_dups, xs)
   569           else dups (x :: rev_dups, xs);
   570   in
   571     dups ([], lst)
   572   end;
   573 
   574 fun duplicates l = gen_duplicates (op =) l;
   575 
   576 
   577 
   578 (** association lists **)
   579 
   580 (*association list lookup*)
   581 fun assoc ([], key) = None
   582   | assoc ((keyi, xi) :: pairs, key) =
   583       if key = keyi then Some xi else assoc (pairs, key);
   584 
   585 (*association list lookup, optimized version for ints*)
   586 fun assoc_int ([], (key:int)) = None
   587   | assoc_int ((keyi, xi) :: pairs, key) =
   588       if key = keyi then Some xi else assoc_int (pairs, key);
   589 
   590 (*association list lookup, optimized version for strings*)
   591 fun assoc_string ([], (key:string)) = None
   592   | assoc_string ((keyi, xi) :: pairs, key) =
   593       if key = keyi then Some xi else assoc_string (pairs, key);
   594 
   595 (*association list lookup, optimized version for string*ints*)
   596 fun assoc_string_int ([], (key:string*int)) = None
   597   | assoc_string_int ((keyi, xi) :: pairs, key) =
   598       if key = keyi then Some xi else assoc_string_int (pairs, key);
   599 
   600 fun assocs ps x =
   601   (case assoc (ps, x) of
   602     None => []
   603   | Some ys => ys);
   604 
   605 (*two-fold association list lookup*)
   606 fun assoc2 (aal, (key1, key2)) =
   607   (case assoc (aal, key1) of
   608     Some al => assoc (al, key2)
   609   | None => None);
   610 
   611 (*generalized association list lookup*)
   612 fun gen_assoc eq ([], key) = None
   613   | gen_assoc eq ((keyi, xi) :: pairs, key) =
   614       if eq (key, keyi) then Some xi else gen_assoc eq (pairs, key);
   615 
   616 (*association list update*)
   617 fun overwrite (al, p as (key, _)) =
   618   let fun over ((q as (keyi, _)) :: pairs) =
   619             if keyi = key then p :: pairs else q :: (over pairs)
   620         | over [] = [p]
   621   in over al end;
   622 
   623 fun gen_overwrite eq (al, p as (key, _)) =
   624   let fun over ((q as (keyi, _)) :: pairs) =
   625             if eq (keyi, key) then p :: pairs else q :: (over pairs)
   626         | over [] = [p]
   627   in over al end;
   628 
   629 
   630 
   631 (** generic tables **)
   632 
   633 (*Tables are supposed to be 'efficient' encodings of lists of elements distinct
   634   wrt. an equality "eq". The extend and merge operations below are optimized
   635   for long-term space efficiency.*)
   636 
   637 (*append (new) elements to a table*)
   638 fun generic_extend _ _ _ tab [] = tab
   639   | generic_extend eq dest_tab mk_tab tab1 lst2 =
   640       let
   641         val lst1 = dest_tab tab1;
   642         val new_lst2 = gen_rems eq (lst2, lst1);
   643       in
   644         if null new_lst2 then tab1
   645         else mk_tab (lst1 @ new_lst2)
   646       end;
   647 
   648 (*append (new) elements of 2nd table to 1st table*)
   649 fun generic_merge eq dest_tab mk_tab tab1 tab2 =
   650   let
   651     val lst1 = dest_tab tab1;
   652     val lst2 = dest_tab tab2;
   653     val new_lst2 = gen_rems eq (lst2, lst1);
   654   in
   655     if null new_lst2 then tab1
   656     else if gen_subset eq (lst1, lst2) then tab2
   657     else mk_tab (lst1 @ new_lst2)
   658   end;
   659 
   660 
   661 (*lists as tables*)
   662 fun extend_list tab = generic_extend (op =) I I tab;
   663 fun merge_lists tab = generic_merge (op =) I I tab;
   664 
   665 fun merge_rev_lists xs [] = xs
   666   | merge_rev_lists [] ys = ys
   667   | merge_rev_lists xs (y :: ys) =
   668       (if y mem xs then I else cons y) (merge_rev_lists xs ys);
   669 
   670 
   671 
   672 (** balanced trees **)
   673 
   674 exception Balance;      (*indicates non-positive argument to balancing fun*)
   675 
   676 (*balanced folding; avoids deep nesting*)
   677 fun fold_bal f [x] = x
   678   | fold_bal f [] = raise Balance
   679   | fold_bal f xs =
   680       let val k = length xs div 2
   681       in  f (fold_bal f (take(k, xs)),
   682              fold_bal f (drop(k, xs)))
   683       end;
   684 
   685 (*construct something of the form f(...g(...(x)...)) for balanced access*)
   686 fun access_bal (f, g, x) n i =
   687   let fun acc n i =     (*1<=i<=n*)
   688           if n=1 then x else
   689           let val n2 = n div 2
   690           in  if i<=n2 then f (acc n2 i)
   691                        else g (acc (n-n2) (i-n2))
   692           end
   693   in  if 1<=i andalso i<=n then acc n i else raise Balance  end;
   694 
   695 (*construct ALL such accesses; could try harder to share recursive calls!*)
   696 fun accesses_bal (f, g, x) n =
   697   let fun acc n =
   698           if n=1 then [x] else
   699           let val n2 = n div 2
   700               val acc2 = acc n2
   701           in  if n-n2=n2 then map f acc2 @ map g acc2
   702                          else map f acc2 @ map g (acc (n-n2)) end
   703   in  if 1<=n then acc n else raise Balance  end;
   704 
   705 
   706 
   707 (** orders **)
   708 
   709 datatype order = LESS | EQUAL | GREATER;
   710 
   711 fun intord (i, j: int) =
   712   if i < j then LESS
   713   else if i = j then EQUAL
   714   else GREATER;
   715 
   716 fun stringord (a, b: string) =
   717   if a < b then LESS
   718   else if a = b then EQUAL
   719   else GREATER;
   720 
   721 
   722 
   723 (** input / output **)
   724 
   725 val cd = OS.FileSys.chDir;
   726 val pwd = OS.FileSys.getDir;
   727 
   728 val prs_fn = ref(fn s => TextIO.output (TextIO.stdOut, s));
   729 
   730 fun prs s = !prs_fn s;
   731 fun writeln s = prs (s ^ "\n");
   732 
   733 (* TextIO.output to LaTeX / xdvi *)
   734 fun latex s = 
   735         execute ( "( cd /tmp ; echo \"" ^ s ^
   736         "\" | isa2latex -s > $$.tex ; latex $$.tex ; xdvi $$.dvi ; rm $$.* ) > /dev/null &" ) ;
   737 
   738 (*print warning*)
   739 val warning_fn = ref(fn s => TextIO.output (TextIO.stdOut, s ^ "\n"));
   740 fun warning s = !warning_fn ("Warning: " ^ s);
   741 
   742 (*print error message and abort to top level*)
   743 
   744 val error_fn = ref(fn s => TextIO.output (TextIO.stdOut, s ^ "\n"));
   745 
   746 exception ERROR;
   747 fun error msg = (!error_fn msg; raise ERROR);
   748 fun sys_error msg = (!error_fn "*** SYSTEM ERROR ***"; error msg);
   749 
   750 fun assert p msg = if p then () else error msg;
   751 fun deny p msg = if p then error msg else ();
   752 
   753 (*Assert pred for every member of l, generating a message if pred fails*)
   754 fun assert_all pred l msg_fn = 
   755   let fun asl [] = ()
   756         | asl (x::xs) = if pred x then asl xs
   757                         else error (msg_fn x)
   758   in  asl l  end;
   759 
   760 (*for the "test" target in Makefiles -- signifies successful termination*)
   761 fun maketest msg =
   762   (writeln msg; 
   763    let val os = TextIO.openOut "test" 
   764    in  TextIO.output (os, "Test examples ran successfully\n");
   765        TextIO.closeOut os
   766    end);
   767 
   768 
   769 (*print a list surrounded by the brackets lpar and rpar, with comma separator
   770   print nothing for empty list*)
   771 fun print_list (lpar, rpar, pre: 'a -> unit) (l : 'a list) =
   772   let fun prec x = (prs ","; pre x)
   773   in
   774     (case l of
   775       [] => ()
   776     | x::l => (prs lpar; pre x; seq prec l; prs rpar))
   777   end;
   778 
   779 (*print a list of items separated by newlines*)
   780 fun print_list_ln (pre: 'a -> unit) : 'a list -> unit =
   781   seq (fn x => (pre x; writeln ""));
   782 
   783 
   784 val print_int = prs o string_of_int;
   785 
   786 
   787 
   788 (** timing **)
   789 
   790 (*unconditional timing function*)
   791 fun timeit x = cond_timeit true x;
   792 
   793 (*timed application function*)
   794 fun timeap f x = timeit (fn () => f x);
   795 
   796 (*timed "use" function, printing filenames*)
   797 fun time_use fname = timeit (fn () =>
   798   (writeln ("\n**** Starting " ^ fname ^ " ****"); use fname;
   799    writeln ("\n**** Finished " ^ fname ^ " ****")));
   800 
   801 (*For Makefiles: use the file, but exit with error code if errors found.*)
   802 fun exit_use fname = use fname handle _ => exit 1;
   803 
   804 
   805 (** filenames and paths **)
   806 
   807 (*Convert UNIX filename of the form "path/file" to "path/" and "file";
   808   if filename contains no slash, then it returns "" and "file"*)
   809 val split_filename =
   810   (pairself implode) o take_suffix (not_equal "/") o explode;
   811 
   812 val base_name = #2 o split_filename;
   813 
   814 (*Merge splitted filename (path and file);
   815   if path does not end with one a slash is appended*)
   816 fun tack_on "" name = name
   817   | tack_on path name =
   818       if last_elem (explode path) = "/" then path ^ name
   819       else path ^ "/" ^ name;
   820 
   821 (*Remove the extension of a filename, i.e. the part after the last '.'*)
   822 val remove_ext = implode o #1 o take_suffix (not_equal ".") o explode;
   823 
   824 (*Make relative path to reach an absolute location from a different one*)
   825 fun relative_path cur_path dest_path =
   826   let (*Remove common beginning of both paths and make relative path*)
   827       fun mk_relative [] [] = []
   828         | mk_relative [] ds = ds
   829         | mk_relative cs [] = map (fn _ => "..") cs
   830         | mk_relative (c::cs) (d::ds) =
   831             if c = d then mk_relative cs ds
   832             else ".." :: map (fn _ => "..") cs @ (d::ds);
   833   in if cur_path = "" orelse hd (explode cur_path) <> "/" orelse
   834         dest_path = "" orelse hd (explode dest_path) <> "/" then
   835        error "Relative or empty path passed to relative_path"
   836      else ();
   837      space_implode "/" (mk_relative (space_explode "/" cur_path)
   838                                     (space_explode "/" dest_path))
   839   end;
   840 
   841 (*Determine if absolute path1 is a subdirectory of absolute path2*)
   842 fun path1 subdir_of path2 =
   843   if hd (explode path1) <> "/" orelse hd (explode path2) <> "/" then
   844     error "Relative or empty path passed to subdir_of"
   845   else (space_explode "/" path2) prefix (space_explode "/" path1);
   846 
   847 fun absolute_path cwd file =
   848   let fun rm_points [] result = rev result
   849         | rm_points (".."::ds) result = rm_points ds (tl result)
   850         | rm_points ("."::ds) result = rm_points ds result
   851         | rm_points (d::ds) result = rm_points ds (d::result);
   852   in if file = "" then ""
   853      else if hd (explode file) = "/" then file
   854      else "/" ^ space_implode "/"
   855                   (rm_points (space_explode "/" (tack_on cwd file)) [])
   856   end;
   857 
   858 
   859 (** misc functions **)
   860 
   861 (*use the keyfun to make a list of (x, key) pairs*)
   862 fun make_keylist (keyfun: 'a->'b) : 'a list -> ('a * 'b) list =
   863   let fun keypair x = (x, keyfun x)
   864   in map keypair end;
   865 
   866 (*given a list of (x, key) pairs and a searchkey
   867   return the list of xs from each pair whose key equals searchkey*)
   868 fun keyfilter [] searchkey = []
   869   | keyfilter ((x, key) :: pairs) searchkey =
   870       if key = searchkey then x :: keyfilter pairs searchkey
   871       else keyfilter pairs searchkey;
   872 
   873 
   874 (*Partition list into elements that satisfy predicate and those that don't.
   875   Preserves order of elements in both lists.*)
   876 fun partition (pred: 'a->bool) (ys: 'a list) : ('a list * 'a list) =
   877     let fun part ([], answer) = answer
   878           | part (x::xs, (ys, ns)) = if pred(x)
   879             then  part (xs, (x::ys, ns))
   880             else  part (xs, (ys, x::ns))
   881     in  part (rev ys, ([], []))  end;
   882 
   883 
   884 fun partition_eq (eq:'a * 'a -> bool) =
   885     let fun part [] = []
   886           | part (x::ys) = let val (xs, xs') = partition (apl(x, eq)) ys
   887                            in (x::xs)::(part xs') end
   888     in part end;
   889 
   890 
   891 (*Partition a list into buckets  [ bi, b(i+1), ..., bj ]
   892    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
   893 fun partition_list p i j =
   894   let fun part k xs =
   895             if k>j then
   896               (case xs of [] => []
   897                          | _ => raise LIST "partition_list")
   898             else
   899             let val (ns, rest) = partition (p k) xs;
   900             in  ns :: part(k+1)rest  end
   901   in  part i end;
   902 
   903 
   904 (* sorting *)
   905 
   906 (*insertion sort; stable (does not reorder equal elements)
   907   'less' is less-than test on type 'a*)
   908 fun sort (less: 'a*'a -> bool) =
   909   let fun insert (x, []) = [x]
   910         | insert (x, y::ys) =
   911               if less(y, x) then y :: insert (x, ys) else x::y::ys;
   912       fun sort1 [] = []
   913         | sort1 (x::xs) = insert (x, sort1 xs)
   914   in  sort1  end;
   915 
   916 (*sort strings*)
   917 val sort_strings = sort (op <= : string * string -> bool);
   918 
   919 
   920 (* transitive closure (not Warshall's algorithm) *)
   921 
   922 fun transitive_closure [] = []
   923   | transitive_closure ((x, ys)::ps) =
   924       let val qs = transitive_closure ps
   925           val zs = foldl (fn (zs, y) => assocs qs y union_string zs) (ys, ys)
   926           fun step(u, us) = (u, if x mem_string us then zs union_string us 
   927                                 else us)
   928       in (x, zs) :: map step qs end;
   929 
   930 
   931 (* generating identifiers *)
   932 
   933 local
   934   val a = ord "a" and z = ord "z" and A = ord "A" and Z = ord "Z"
   935   and k0 = ord "0" and k9 = ord "9"
   936 
   937   val seedr = ref 0;
   938 in
   939 
   940 (*Maps 0-63 to A-Z, a-z, 0-9 or _ or ' for generating random identifiers*)
   941 fun newid n = 
   942   let fun char i =
   943                if i<26 then chr (A+i)
   944           else if i<52 then chr (a+i-26)
   945           else if i<62 then chr (k0+i-52)
   946           else if i=62 then "_"
   947           else  (*i=63*)    "'"
   948   in  implode (map char (radixpand (64,n)))  end;
   949 
   950 (*Freshly generated identifiers with given prefix; MUST start with a letter*)
   951 fun gensym pre = pre ^ 
   952                  (#1(newid (!seedr), 
   953                      seedr := 1+ !seedr))
   954 
   955 (*Increment a list of letters like a reversed base 26 number.
   956   If head is "z", bumps chars in tail.
   957   Digits are incremented as if they were integers.
   958   "_" and "'" are not changed.
   959   For making variants of identifiers.*)
   960 
   961 fun bump_int_list(c::cs) = if c="9" then "0" :: bump_int_list cs else
   962         if k0 <= ord(c) andalso ord(c) < k9 then chr(ord(c)+1) :: cs
   963         else "1" :: c :: cs
   964   | bump_int_list([]) = error("bump_int_list: not an identifier");
   965 
   966 fun bump_list([], d) = [d]
   967   | bump_list(["'"], d) = [d, "'"]
   968   | bump_list("z"::cs, _) = "a" :: bump_list(cs, "a")
   969   | bump_list("Z"::cs, _) = "A" :: bump_list(cs, "A")
   970   | bump_list("9"::cs, _) = "0" :: bump_int_list cs
   971   | bump_list(c::cs, _) = let val k = ord(c)
   972         in if (a <= k andalso k < z) orelse (A <= k andalso k < Z) orelse
   973               (k0 <= k andalso k < k9) then chr(k+1) :: cs else
   974            if c="'" orelse c="_" then c :: bump_list(cs, "") else
   975                 error("bump_list: not legal in identifier: " ^
   976                         implode(rev(c::cs)))
   977         end;
   978 
   979 end;
   980 
   981 fun bump_string s : string = implode (rev (bump_list(rev(explode s), "")));
   982 
   983 
   984 (* lexical scanning *)
   985 
   986 (*scan a list of characters into "words" composed of "letters" (recognized by
   987   is_let) and separated by any number of non-"letters"*)
   988 fun scanwords is_let cs =
   989   let fun scan1 [] = []
   990         | scan1 cs =
   991             let val (lets, rest) = take_prefix is_let cs
   992             in implode lets :: scanwords is_let rest end;
   993   in scan1 (#2 (take_prefix (not o is_let) cs)) end;
   994 
   995 end;
   996 
   997 (*Variable-branching trees: for proof terms*)
   998 datatype 'a mtree = Join of 'a * 'a mtree list;
   999 
  1000 open Library;