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