src/Pure/library.ML
 author paulson Sat Nov 01 13:01:57 1997 +0100 (1997-11-01) changeset 4063 0b19014b9155 parent 4046 f89dbf002604 child 4102 f746af27164b permissions -rw-r--r--
Faster lexing
1 (*  Title:      Pure/library.ML
2     ID:         \$Id\$
3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
4     Copyright   1992  University of Cambridge
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 *)
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;
16 structure Library =
17 struct
19 (** functions **)
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;
27 (*reverse apply*)
28 fun (x |> f) = f x;
30 (*combine two functions forming the union of their domains*)
31 fun (f orelf g) = fn x => f x handle Match => g x;
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);
37 (*functional for pairs*)
38 fun pairself f (x, y) = (f x, f y);
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;
48 (** stamps **)
50 type stamp = unit ref;
51 val stamp: unit -> stamp = ref;
55 (** options **)
57 datatype 'a option = None | Some of 'a;
59 exception OPTION of string;
61 fun the (Some x) = x
62   | the None = raise OPTION "the";
64 fun if_none None y = y
65   | if_none (Some x) _ = x;
67 fun is_some (Some _) = true
68   | is_some None = false;
70 fun is_none (Some _) = false
71   | is_none None = true;
73 fun apsome f (Some x) = Some (f x)
74   | apsome _ None = None;
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));
81 (** pairs **)
83 fun pair x y = (x, y);
84 fun rpair x y = (y, x);
86 fun fst (x, y) = x;
87 fun snd (x, y) = y;
89 fun eq_fst ((x1, _), (x2, _)) = x1 = x2;
90 fun eq_snd ((_, y1), (_, y2)) = y1 = y2;
92 fun swap (x, y) = (y, x);
94 (*apply the function to a component of a pair*)
95 fun apfst f (x, y) = (f x, y);
96 fun apsnd f (x, y) = (x, f y);
100 (** booleans **)
102 (* equality *)
104 fun equal x y = x = y;
105 fun not_equal x y = x <> y;
108 (* operators for combining predicates *)
110 fun (p orf q) = fn x => p x orelse q x;
112 fun (p andf q) = fn x => p x andalso q x;
114 fun notf p x = not (p x);
117 (* predicates on lists *)
119 fun orl [] = false
120   | orl (x :: xs) = x orelse orl xs;
122 fun andl [] = true
123   | andl (x :: xs) = x andalso andl xs;
125 (*Several object-logics declare theories named List or Option, hiding the
126   eponymous basis library structures.*)
127 structure Basis_Library =
128     struct
129     structure List = List
130     and       Option = Option
131     end;
134 (*exists pred [x1, ..., xn] ===> pred x1 orelse ... orelse pred xn*)
135 fun exists (pred: 'a -> bool) : 'a list -> bool =
136   let fun boolf [] = false
137         | boolf (x :: xs) = pred x orelse boolf xs
138   in boolf end;
140 (*forall pred [x1, ..., xn] ===> pred x1 andalso ... andalso pred xn*)
141 fun forall (pred: 'a -> bool) : 'a list -> bool =
142   let fun boolf [] = true
143         | boolf (x :: xs) = pred x andalso boolf xs
144   in boolf end;
147 (* flags *)
149 fun set flag = (flag := true; true);
150 fun reset flag = (flag := false; false);
151 fun toggle flag = (flag := not (! flag); ! flag);
153 fun setmp flag value f x =
154   let
155     val orig_value = ! flag;
156     fun return y = (flag := orig_value; y);
157   in
158     flag := value;
159     return (f x handle exn => (return (); raise exn))
160   end;
164 (** lists **)
166 exception LIST of string;
168 fun null [] = true
169   | null (_ :: _) = false;
171 fun hd [] = raise LIST "hd"
172   | hd (x :: _) = x;
174 fun tl [] = raise LIST "tl"
175   | tl (_ :: xs) = xs;
177 fun cons x xs = x :: xs;
180 (* fold *)
182 (*the following versions of fold are designed to fit nicely with infixes*)
184 (*  (op @) (e, [x1, ..., xn])  ===>  ((e @ x1) @ x2) ... @ xn
185     for operators that associate to the left (TAIL RECURSIVE)*)
186 fun foldl (f: 'a * 'b -> 'a) : 'a * 'b list -> 'a =
187   let fun itl (e, [])  = e
188         | itl (e, a::l) = itl (f(e, a), l)
189   in  itl end;
191 (*  (op @) ([x1, ..., xn], e)  ===>   x1 @ (x2 ... @ (xn @ e))
192     for operators that associate to the right (not tail recursive)*)
193 fun foldr f (l, e) =
194   let fun itr [] = e
195         | itr (a::l) = f(a, itr l)
196   in  itr l  end;
198 (*  (op @) [x1, ..., xn]  ===>   x1 @ (x2 ... @ (x[n-1] @ xn))
199     for n > 0, operators that associate to the right (not tail recursive)*)
200 fun foldr1 f l =
201   let fun itr [x] = x                       (* FIXME [] case: elim warn (?) *)
202         | itr (x::l) = f(x, itr l)
203   in  itr l  end;
206 (* basic list functions *)
208 (*length of a list, should unquestionably be a standard function*)
209 local fun length1 (n, [])  = n   (*TAIL RECURSIVE*)
210         | length1 (n, x :: xs) = length1 (n + 1, xs)
211 in  fun length l = length1 (0, l) end;
213 (*take the first n elements from a list*)
214 fun take (n, []) = []
215   | take (n, x :: xs) =
216       if n > 0 then x :: take (n - 1, xs) else [];
218 (*drop the first n elements from a list*)
219 fun drop (n, []) = []
220   | drop (n, x :: xs) =
221       if n > 0 then drop (n - 1, xs) else x :: xs;
223 (*return nth element of a list, where 0 designates the first element;
224   raise EXCEPTION if list too short*)
225 fun nth_elem NL =
226   (case drop NL of
227     [] => raise LIST "nth_elem"
228   | x :: _ => x);
230 (*last element of a list*)
231 fun last_elem [] = raise LIST "last_elem"
232   | last_elem [x] = x
233   | last_elem (_ :: xs) = last_elem xs;
235 (*rear decomposition*)
236 fun split_last [] = raise LIST "split_last"
237   | split_last [x] = ([], x)
238   | split_last (x :: xs) = apfst (cons x) (split_last xs);
241 (*find the position of an element in a list*)
242 fun find (x, ys) =
243   let fun f (y :: ys, i) = if x = y then i else f (ys, i + 1)
244         | f (_, _) = raise LIST "find"
245   in f (ys, 0) end;
247 (*flatten a list of lists to a list*)
248 fun flat (ls: 'c list list) : 'c list = foldr (op @) (ls, []);
251 (*like Lisp's MAPC -- seq proc [x1, ..., xn] evaluates
252   (proc x1; ...; proc xn) for side effects*)
253 fun seq (proc: 'a -> unit) : 'a list -> unit =
254   let fun seqf [] = ()
255         | seqf (x :: xs) = (proc x; seqf xs)
256   in seqf end;
259 (*separate s [x1, x2, ..., xn]  ===>  [x1, s, x2, s, ..., s, xn]*)
260 fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
261   | separate _ xs = xs;
263 (*make the list [x, x, ..., x] of length n*)
264 fun replicate n (x: 'a) : 'a list =
265   let fun rep (0, xs) = xs
266         | rep (n, xs) = rep (n - 1, x :: xs)
267   in
268     if n < 0 then raise LIST "replicate"
269     else rep (n, [])
270   end;
273 (* filter *)
275 (*copy the list preserving elements that satisfy the predicate*)
276 fun filter (pred: 'a->bool) : 'a list -> 'a list =
277   let fun filt [] = []
278         | filt (x :: xs) = if pred x then x :: filt xs else filt xs
279   in filt end;
281 fun filter_out f = filter (not o f);
284 fun mapfilter (f: 'a -> 'b option) ([]: 'a list) = [] : 'b list
285   | mapfilter f (x :: xs) =
286       (case f x of
287         None => mapfilter f xs
288       | Some y => y :: mapfilter f xs);
291 fun find_first _ [] = None
292   | find_first pred (x :: xs) =
293       if pred x then Some x else find_first pred xs;
296 (* lists of pairs *)
298 fun map2 _ ([], []) = []
299   | map2 f (x :: xs, y :: ys) = (f (x, y) :: map2 f (xs, ys))
300   | map2 _ _ = raise LIST "map2";
302 fun exists2 _ ([], []) = false
303   | exists2 pred (x :: xs, y :: ys) = pred (x, y) orelse exists2 pred (xs, ys)
304   | exists2 _ _ = raise LIST "exists2";
306 fun forall2 _ ([], []) = true
307   | forall2 pred (x :: xs, y :: ys) = pred (x, y) andalso forall2 pred (xs, ys)
308   | forall2 _ _ = raise LIST "forall2";
310 (*combine two lists forming a list of pairs:
311   [x1, ..., xn] ~~ [y1, ..., yn]  ===>  [(x1, y1), ..., (xn, yn)]*)
312 fun [] ~~ [] = []
313   | (x :: xs) ~~ (y :: ys) = (x, y) :: (xs ~~ ys)
314   | _ ~~ _ = raise LIST "~~";
317 (*inverse of ~~; the old 'split':
318   [(x1, y1), ..., (xn, yn)]  ===>  ([x1, ..., xn], [y1, ..., yn])*)
319 fun split_list (l: ('a * 'b) list) = (map #1 l, map #2 l);
322 (* prefixes, suffixes *)
324 fun [] prefix _ = true
325   | (x :: xs) prefix (y :: ys) = x = y andalso (xs prefix ys)
326   | _ prefix _ = false;
328 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., x(i-1)], [xi, ..., xn])
329    where xi is the first element that does not satisfy the predicate*)
330 fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
331   let fun take (rxs, []) = (rev rxs, [])
332         | take (rxs, x :: xs) =
333             if  pred x  then  take(x :: rxs, xs)  else  (rev rxs, x :: xs)
334   in  take([], xs)  end;
336 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., xi], [x(i+1), ..., xn])
337    where xi is the last element that does not satisfy the predicate*)
338 fun take_suffix _ [] = ([], [])
339   | take_suffix pred (x :: xs) =
340       (case take_suffix pred xs of
341         ([], sffx) => if pred x then ([], x :: sffx) else ([x], sffx)
342       | (prfx, sffx) => (x :: prfx, sffx));
346 (** integers **)
348 fun inc i = (i := ! i + 1; ! i);
349 fun dec i = (i := ! i - 1; ! i);
352 (* lists of integers *)
354 (*make the list [from, from + 1, ..., to]*)
355 fun (from upto to) =
356   if from > to then [] else from :: ((from + 1) upto to);
358 (*make the list [from, from - 1, ..., to]*)
359 fun (from downto to) =
360   if from < to then [] else from :: ((from - 1) downto to);
362 (*predicate: downto0 (is, n) <=> is = [n, n - 1, ..., 0]*)
363 fun downto0 (i :: is, n) = i = n andalso downto0 (is, n - 1)
364   | downto0 ([], n) = n = ~1;
367 (* convert integers to strings *)
369 (*expand the number in the given base;
370   example: radixpand (2, 8) gives [1, 0, 0, 0]*)
371 fun radixpand (base, num) : int list =
372   let
373     fun radix (n, tail) =
374       if n < base then n :: tail
375       else radix (n div base, (n mod base) :: tail)
376   in radix (num, []) end;
378 (*expands a number into a string of characters starting from "zerochar";
379   example: radixstring (2, "0", 8) gives "1000"*)
380 fun radixstring (base, zerochar, num) =
381   let val offset = ord zerochar;
382       fun chrof n = chr (offset + n)
383   in implode (map chrof (radixpand (base, num))) end;
386 val string_of_int = Int.toString;
388 fun string_of_indexname (a,0) = a
389   | string_of_indexname (a,i) = a ^ "_" ^ Int.toString i;
392 (** strings **)
394 fun is_letter ch =
395   ord "A" <= ord ch andalso ord ch <= ord "Z" orelse
396   ord "a" <= ord ch andalso ord ch <= ord "z";
398 fun is_digit ch =
399   ord "0" <= ord ch andalso ord ch <= ord "9";
401 (*letter or _ or prime (')*)
402 fun is_quasi_letter "_" = true
403   | is_quasi_letter "'" = true
404   | is_quasi_letter ch = is_letter ch;
406 (*white space: blanks, tabs, newlines, formfeeds*)
407 val is_blank : string -> bool =
408   fn " " => true | "\t" => true | "\n" => true | "\^L" => true | "\160" => true
409     | _ => false;
411 val is_letdig = is_quasi_letter orf is_digit;
413 (*printable chars*)
414 fun is_printable c = ord c > ord " " andalso ord c <= ord "~";
417 (*lower all chars of string*)
418 val to_lower =
419   let
420     fun lower ch =
421       if ch >= "A" andalso ch <= "Z" then
422         chr (ord ch - ord "A" + ord "a")
423       else ch;
424   in implode o (map lower) o explode end;
427 (*enclose in brackets*)
428 fun enclose lpar rpar str = lpar ^ str ^ rpar;
430 (*simple quoting (does not escape special chars)*)
431 val quote = enclose "\"" "\"";
433 (*space_implode "..." (explode "hello"); gives "h...e...l...l...o"*)
434 fun space_implode a bs = implode (separate a bs);
436 val commas = space_implode ", ";
437 val commas_quote = commas o map quote;
439 (*concatenate messages, one per line, into a string*)
440 val cat_lines = space_implode "\n";
442 (*BAD_space_explode "." "h.e..l.lo"; gives ["h", "e", "l", "lo"]*)
443 fun BAD_space_explode sep s =
444   let fun divide [] "" = []
445         | divide [] part = [part]
446         | divide (c::s) part =
447             if c = sep then
448               (if part = "" then divide s "" else part :: divide s "")
449             else divide s (part ^ c)
450   in divide (explode s) "" end;
452 (*space_explode "." "h.e..l.lo"; gives ["h", "e", "", "l", "lo"]*)
453 fun space_explode _ "" = []
454   | space_explode sep str =
455       let
456         fun expl chs =
457           (case take_prefix (not_equal sep) chs of
458             (cs, []) => [implode cs]
459           | (cs, _ :: cs') => implode cs :: expl cs');
460       in expl (explode str) end;
462 val split_lines = space_explode "\n";
466 (** lists as sets **)
468 (*membership in a list*)
469 fun x mem [] = false
470   | x mem (y :: ys) = x = y orelse x mem ys;
472 (*membership in a list, optimized version for ints*)
473 fun (x:int) mem_int [] = false
474   | x mem_int (y :: ys) = x = y orelse x mem_int ys;
476 (*membership in a list, optimized version for strings*)
477 fun (x:string) mem_string [] = false
478   | x mem_string (y :: ys) = x = y orelse x mem_string ys;
480 (*generalized membership test*)
481 fun gen_mem eq (x, []) = false
482   | gen_mem eq (x, y :: ys) = eq (x, y) orelse gen_mem eq (x, ys);
485 (*insertion into list if not already there*)
486 fun (x ins xs) = if x mem xs then xs else x :: xs;
488 (*insertion into list, optimized version for ints*)
489 fun (x ins_int xs) = if x mem_int xs then xs else x :: xs;
491 (*insertion into list, optimized version for strings*)
492 fun (x ins_string xs) = if x mem_string xs then xs else x :: xs;
494 (*generalized insertion*)
495 fun gen_ins eq (x, xs) = if gen_mem eq (x, xs) then xs else x :: xs;
498 (*union of sets represented as lists: no repetitions*)
499 fun xs union [] = xs
500   | [] union ys = ys
501   | (x :: xs) union ys = xs union (x ins ys);
503 (*union of sets, optimized version for ints*)
504 fun (xs:int list) union_int [] = xs
505   | [] union_int ys = ys
506   | (x :: xs) union_int ys = xs union_int (x ins_int ys);
508 (*union of sets, optimized version for strings*)
509 fun (xs:string list) union_string [] = xs
510   | [] union_string ys = ys
511   | (x :: xs) union_string ys = xs union_string (x ins_string ys);
513 (*generalized union*)
514 fun gen_union eq (xs, []) = xs
515   | gen_union eq ([], ys) = ys
516   | gen_union eq (x :: xs, ys) = gen_union eq (xs, gen_ins eq (x, ys));
519 (*intersection*)
520 fun [] inter ys = []
521   | (x :: xs) inter ys =
522       if x mem ys then x :: (xs inter ys) else xs inter ys;
524 (*intersection, optimized version for ints*)
525 fun ([]:int list) inter_int ys = []
526   | (x :: xs) inter_int ys =
527       if x mem_int ys then x :: (xs inter_int ys) else xs inter_int ys;
529 (*intersection, optimized version for strings *)
530 fun ([]:string list) inter_string ys = []
531   | (x :: xs) inter_string ys =
532       if x mem_string ys then x :: (xs inter_string ys) else xs inter_string ys;
535 (*subset*)
536 fun [] subset ys = true
537   | (x :: xs) subset ys = x mem ys andalso xs subset ys;
539 (*subset, optimized version for ints*)
540 fun ([]:int list) subset_int ys = true
541   | (x :: xs) subset_int ys = x mem_int ys andalso xs subset_int ys;
543 (*subset, optimized version for strings*)
544 fun ([]:string list) subset_string ys = true
545   | (x :: xs) subset_string ys = x mem_string ys andalso xs subset_string ys;
547 (*set equality for strings*)
548 fun eq_set_string ((xs:string list), ys) =
549   xs = ys orelse (xs subset_string ys andalso ys subset_string xs);
551 fun gen_subset eq (xs, ys) = forall (fn x => gen_mem eq (x, ys)) xs;
554 (*removing an element from a list WITHOUT duplicates*)
555 fun (y :: ys) \ x = if x = y then ys else y :: (ys \ x)
556   | [] \ x = [];
558 fun ys \\ xs = foldl (op \) (ys,xs);
560 (*removing an element from a list -- possibly WITH duplicates*)
561 fun gen_rem eq (xs, y) = filter_out (fn x => eq (x, y)) xs;
563 fun gen_rems eq = foldl (gen_rem eq);
566 (*makes a list of the distinct members of the input; preserves order, takes
567   first of equal elements*)
568 fun gen_distinct eq lst =
569   let
570     val memb = gen_mem eq;
572     fun dist (rev_seen, []) = rev rev_seen
573       | dist (rev_seen, x :: xs) =
574           if memb (x, rev_seen) then dist (rev_seen, xs)
575           else dist (x :: rev_seen, xs);
576   in
577     dist ([], lst)
578   end;
580 fun distinct l = gen_distinct (op =) l;
583 (*returns the tail beginning with the first repeated element, or []*)
584 fun findrep [] = []
585   | findrep (x :: xs) = if x mem xs then x :: xs else findrep xs;
588 (*returns a list containing all repeated elements exactly once; preserves
589   order, takes first of equal elements*)
590 fun gen_duplicates eq lst =
591   let
592     val memb = gen_mem eq;
594     fun dups (rev_dups, []) = rev rev_dups
595       | dups (rev_dups, x :: xs) =
596           if memb (x, rev_dups) orelse not (memb (x, xs)) then
597             dups (rev_dups, xs)
598           else dups (x :: rev_dups, xs);
599   in
600     dups ([], lst)
601   end;
603 fun duplicates l = gen_duplicates (op =) l;
607 (** association lists **)
609 (*association list lookup*)
610 fun assoc ([], key) = None
611   | assoc ((keyi, xi) :: pairs, key) =
612       if key = keyi then Some xi else assoc (pairs, key);
614 (*association list lookup, optimized version for ints*)
615 fun assoc_int ([], (key:int)) = None
616   | assoc_int ((keyi, xi) :: pairs, key) =
617       if key = keyi then Some xi else assoc_int (pairs, key);
619 (*association list lookup, optimized version for strings*)
620 fun assoc_string ([], (key:string)) = None
621   | assoc_string ((keyi, xi) :: pairs, key) =
622       if key = keyi then Some xi else assoc_string (pairs, key);
624 (*association list lookup, optimized version for string*ints*)
625 fun assoc_string_int ([], (key:string*int)) = None
626   | assoc_string_int ((keyi, xi) :: pairs, key) =
627       if key = keyi then Some xi else assoc_string_int (pairs, key);
629 fun assocs ps x =
630   (case assoc (ps, x) of
631     None => []
632   | Some ys => ys);
634 (*two-fold association list lookup*)
635 fun assoc2 (aal, (key1, key2)) =
636   (case assoc (aal, key1) of
637     Some al => assoc (al, key2)
638   | None => None);
640 (*generalized association list lookup*)
641 fun gen_assoc eq ([], key) = None
642   | gen_assoc eq ((keyi, xi) :: pairs, key) =
643       if eq (key, keyi) then Some xi else gen_assoc eq (pairs, key);
645 (*association list update*)
646 fun overwrite (al, p as (key, _)) =
647   let fun over ((q as (keyi, _)) :: pairs) =
648             if keyi = key then p :: pairs else q :: (over pairs)
649         | over [] = [p]
650   in over al end;
652 fun gen_overwrite eq (al, p as (key, _)) =
653   let fun over ((q as (keyi, _)) :: pairs) =
654             if eq (keyi, key) then p :: pairs else q :: (over pairs)
655         | over [] = [p]
656   in over al end;
660 (** generic tables **)
662 (*Tables are supposed to be 'efficient' encodings of lists of elements distinct
663   wrt. an equality "eq". The extend and merge operations below are optimized
664   for long-term space efficiency.*)
666 (*append (new) elements to a table*)
667 fun generic_extend _ _ _ tab [] = tab
668   | generic_extend eq dest_tab mk_tab tab1 lst2 =
669       let
670         val lst1 = dest_tab tab1;
671         val new_lst2 = gen_rems eq (lst2, lst1);
672       in
673         if null new_lst2 then tab1
674         else mk_tab (lst1 @ new_lst2)
675       end;
677 (*append (new) elements of 2nd table to 1st table*)
678 fun generic_merge eq dest_tab mk_tab tab1 tab2 =
679   let
680     val lst1 = dest_tab tab1;
681     val lst2 = dest_tab tab2;
682     val new_lst2 = gen_rems eq (lst2, lst1);
683   in
684     if null new_lst2 then tab1
685     else if gen_subset eq (lst1, lst2) then tab2
686     else mk_tab (lst1 @ new_lst2)
687   end;
690 (*lists as tables*)
691 fun extend_list tab = generic_extend (op =) I I tab;
692 fun merge_lists tab = generic_merge (op =) I I tab;
694 fun merge_rev_lists xs [] = xs
695   | merge_rev_lists [] ys = ys
696   | merge_rev_lists xs (y :: ys) =
697       (if y mem xs then I else cons y) (merge_rev_lists xs ys);
701 (** balanced trees **)
703 exception Balance;      (*indicates non-positive argument to balancing fun*)
705 (*balanced folding; avoids deep nesting*)
706 fun fold_bal f [x] = x
707   | fold_bal f [] = raise Balance
708   | fold_bal f xs =
709       let val k = length xs div 2
710       in  f (fold_bal f (take(k, xs)),
711              fold_bal f (drop(k, xs)))
712       end;
714 (*construct something of the form f(...g(...(x)...)) for balanced access*)
715 fun access_bal (f, g, x) n i =
716   let fun acc n i =     (*1<=i<=n*)
717           if n=1 then x else
718           let val n2 = n div 2
719           in  if i<=n2 then f (acc n2 i)
720                        else g (acc (n-n2) (i-n2))
721           end
722   in  if 1<=i andalso i<=n then acc n i else raise Balance  end;
724 (*construct ALL such accesses; could try harder to share recursive calls!*)
725 fun accesses_bal (f, g, x) n =
726   let fun acc n =
727           if n=1 then [x] else
728           let val n2 = n div 2
729               val acc2 = acc n2
730           in  if n-n2=n2 then map f acc2 @ map g acc2
731                          else map f acc2 @ map g (acc (n-n2)) end
732   in  if 1<=n then acc n else raise Balance  end;
736 (** orders **)
738 datatype order = LESS | EQUAL | GREATER;
740 fun intord (i, j: int) =
741   if i < j then LESS
742   else if i = j then EQUAL
743   else GREATER;
745 fun stringord (a, b: string) =
746   if a < b then LESS
747   else if a = b then EQUAL
748   else GREATER;
752 (** input / output and diagnostics **)
754 val cd = OS.FileSys.chDir;
755 val pwd = OS.FileSys.getDir;
758 local
759   fun out s =
760     (TextIO.output (TextIO.stdOut, s); TextIO.flushOut TextIO.stdOut);
762   fun prefix_lines prfx txt =
763     txt |> split_lines |> map (fn s => prfx ^ s ^ "\n") |> implode;
764 in
766 (*hooks for output channels: normal, warning, error*)
767 val prs_fn = ref (fn s => out s);
768 val warning_fn = ref (fn s => out (prefix_lines "### " s));
769 val error_fn = ref (fn s => out (prefix_lines "*** " s));
771 end;
773 fun prs s = !prs_fn s;
774 fun writeln s = prs (s ^ "\n");
776 fun warning s = !warning_fn s;
778 (*print error message and abort to top level*)
779 exception ERROR;
780 fun error_msg s = !error_fn s;			(*promise to raise ERROR later!*)
781 fun error s = (error_msg s; raise ERROR);
782 fun sys_error msg = (error_msg " !! SYSTEM ERROR !!\n"; error msg);
784 fun assert p msg = if p then () else error msg;
785 fun deny p msg = if p then error msg else ();
787 (*Assert pred for every member of l, generating a message if pred fails*)
788 fun assert_all pred l msg_fn =
789   let fun asl [] = ()
790         | asl (x::xs) = if pred x then asl xs
791                         else error (msg_fn x)
792   in  asl l  end;
795 (* handle errors (capturing messages) *)
797 datatype 'a error =
798   Error of string |
799   OK of 'a;
801 fun handle_error f x =
802   let
803     val buffer = ref "";
804     fun capture s = buffer := ! buffer ^ s ^ "\n";
805     val result = Some (setmp error_fn capture f x) handle ERROR => None;
806   in
807     case result of
808       None => Error (! buffer)
809     | Some y => OK y
810   end;
813 (* read / write files *)
815 fun read_file name =
816   let
817     val instream  = TextIO.openIn name;
818     val intext = TextIO.inputAll instream;
819   in
820     TextIO.closeIn instream;
821     intext
822   end;
824 fun write_file name txt =
825   let val outstream = TextIO.openOut name in
826     TextIO.output (outstream, txt);
827     TextIO.closeOut outstream
828   end;
830 fun append_file name txt =
831   let val outstream = TextIO.openAppend name in
832     TextIO.output (outstream, txt);
833     TextIO.closeOut outstream
834   end;
837 (*for the "test" target in IsaMakefiles -- signifies successful termination*)
838 fun maketest msg =
839   (writeln msg; write_file "test" "Test examples ran successfully\n");
842 (*print a list surrounded by the brackets lpar and rpar, with comma separator
843   print nothing for empty list*)
844 fun print_list (lpar, rpar, pre: 'a -> unit) (l : 'a list) =
845   let fun prec x = (prs ","; pre x)
846   in
847     (case l of
848       [] => ()
849     | x::l => (prs lpar; pre x; seq prec l; prs rpar))
850   end;
852 (*print a list of items separated by newlines*)
853 fun print_list_ln (pre: 'a -> unit) : 'a list -> unit =
854   seq (fn x => (pre x; writeln ""));
857 val print_int = prs o string_of_int;
860 (* output to LaTeX / xdvi *)
861 fun latex s =
862   execute ("( cd /tmp ; echo \"" ^ s ^
863     "\" | isa2latex -s > \$\$.tex ; latex \$\$.tex ; xdvi \$\$.dvi ; rm \$\$.* ) > /dev/null &");
866 (** timing **)
868 (*unconditional timing function*)
869 fun timeit x = cond_timeit true x;
871 (*timed application function*)
872 fun timeap f x = timeit (fn () => f x);
874 (*timed "use" function, printing filenames*)
875 fun time_use fname = timeit (fn () =>
876   (writeln ("\n**** Starting " ^ fname ^ " ****"); use fname;
877    writeln ("\n**** Finished " ^ fname ^ " ****")));
879 (*use the file, but exit with error code if errors found.*)
880 fun exit_use fname = use fname handle _ => exit 1;
883 (** filenames and paths **)
885 (*Convert UNIX filename of the form "path/file" to "path/" and "file";
886   if filename contains no slash, then it returns "" and "file"*)
887 val split_filename =
888   (pairself implode) o take_suffix (not_equal "/") o explode;
890 val base_name = #2 o split_filename;
892 (*Merge splitted filename (path and file);
893   if path does not end with one a slash is appended*)
894 fun tack_on "" name = name
895   | tack_on path name =
896       if last_elem (explode path) = "/" then path ^ name
897       else path ^ "/" ^ name;
899 (*Remove the extension of a filename, i.e. the part after the last '.'*)
900 val remove_ext = implode o #1 o take_suffix (not_equal ".") o explode;
902 (*Make relative path to reach an absolute location from a different one*)
903 fun relative_path cur_path dest_path =
904   let (*Remove common beginning of both paths and make relative path*)
905       fun mk_relative [] [] = []
906         | mk_relative [] ds = ds
907         | mk_relative cs [] = map (fn _ => "..") cs
908         | mk_relative (c::cs) (d::ds) =
909             if c = d then mk_relative cs ds
910             else ".." :: map (fn _ => "..") cs @ (d::ds);
911   in if cur_path = "" orelse hd (explode cur_path) <> "/" orelse
912         dest_path = "" orelse hd (explode dest_path) <> "/" then
913        error "Relative or empty path passed to relative_path"
914      else ();
915      space_implode "/" (mk_relative (BAD_space_explode "/" cur_path)
916                                     (BAD_space_explode "/" dest_path))
917   end;
919 (*Determine if absolute path1 is a subdirectory of absolute path2*)
920 fun path1 subdir_of path2 =
921   if hd (explode path1) <> "/" orelse hd (explode path2) <> "/" then
922     error "Relative or empty path passed to subdir_of"
923   else (BAD_space_explode "/" path2) prefix (BAD_space_explode "/" path1);
925 fun absolute_path cwd file =
926   let fun rm_points [] result = rev result
927         | rm_points (".."::ds) result = rm_points ds (tl result)
928         | rm_points ("."::ds) result = rm_points ds result
929         | rm_points (d::ds) result = rm_points ds (d::result);
930   in if file = "" then ""
931      else if hd (explode file) = "/" then file
932      else "/" ^ space_implode "/"
933                   (rm_points (BAD_space_explode "/" (tack_on cwd file)) [])
934   end;
936 fun file_exists file = (file_info file <> "");
939 (** misc functions **)
941 (*use the keyfun to make a list of (x, key) pairs*)
942 fun make_keylist (keyfun: 'a->'b) : 'a list -> ('a * 'b) list =
943   let fun keypair x = (x, keyfun x)
944   in map keypair end;
946 (*given a list of (x, key) pairs and a searchkey
947   return the list of xs from each pair whose key equals searchkey*)
948 fun keyfilter [] searchkey = []
949   | keyfilter ((x, key) :: pairs) searchkey =
950       if key = searchkey then x :: keyfilter pairs searchkey
951       else keyfilter pairs searchkey;
954 (*Partition list into elements that satisfy predicate and those that don't.
955   Preserves order of elements in both lists.*)
956 fun partition (pred: 'a->bool) (ys: 'a list) : ('a list * 'a list) =
957     let fun part ([], answer) = answer
958           | part (x::xs, (ys, ns)) = if pred(x)
959             then  part (xs, (x::ys, ns))
960             else  part (xs, (ys, x::ns))
961     in  part (rev ys, ([], []))  end;
964 fun partition_eq (eq:'a * 'a -> bool) =
965     let fun part [] = []
966           | part (x::ys) = let val (xs, xs') = partition (apl(x, eq)) ys
967                            in (x::xs)::(part xs') end
968     in part end;
971 (*Partition a list into buckets  [ bi, b(i+1), ..., bj ]
972    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
973 fun partition_list p i j =
974   let fun part k xs =
975             if k>j then
976               (case xs of [] => []
977                          | _ => raise LIST "partition_list")
978             else
979             let val (ns, rest) = partition (p k) xs;
980             in  ns :: part(k+1)rest  end
981   in  part i end;
984 (* sorting *)
986 (*insertion sort; stable (does not reorder equal elements)
987   'less' is less-than test on type 'a*)
988 fun sort (less: 'a*'a -> bool) =
989   let fun insert (x, []) = [x]
990         | insert (x, y::ys) =
991               if less(y, x) then y :: insert (x, ys) else x::y::ys;
992       fun sort1 [] = []
993         | sort1 (x::xs) = insert (x, sort1 xs)
994   in  sort1  end;
996 (*sort strings*)
997 fun sort_wrt sel xs = sort (op <= o pairself (sel: 'a -> string)) xs;
998 val sort_strings = sort_wrt I;
1001 (* transitive closure (not Warshall's algorithm) *)
1003 fun transitive_closure [] = []
1004   | transitive_closure ((x, ys)::ps) =
1005       let val qs = transitive_closure ps
1006           val zs = foldl (fn (zs, y) => assocs qs y union_string zs) (ys, ys)
1007           fun step(u, us) = (u, if x mem_string us then zs union_string us
1008                                 else us)
1009       in (x, zs) :: map step qs end;
1012 (* generating identifiers *)
1014 (** Freshly generated identifiers; supplied prefix MUST start with a letter **)
1015 local
1016 (*Maps 0-63 to A-Z, a-z, 0-9 or _ or ' for generating random identifiers*)
1017 fun char i =      if i<26 then chr (ord "A" + i)
1018 	     else if i<52 then chr (ord "a" + i - 26)
1019 	     else if i<62 then chr (ord"0" + i - 52)
1020 	     else if i=62 then "_"
1021 	     else  (*i=63*)    "'";
1023 val charVec = Vector.tabulate (64, char);
1025 fun newid n =
1026   let
1027   in  implode (map (fn i => Vector.sub(charVec,i)) (radixpand (64,n)))  end
1029   val seedr = ref 0;
1031 in
1032 fun init_gensym() = (seedr := 0);
1034 fun gensym pre = pre ^
1035                  (#1(newid (!seedr),
1036                      seedr := 1+ !seedr))
1037 end;
1040 local
1041 (*Identifies those character codes legal in identifiers.
1042   chould use Basis Library character functions if Poly/ML provided characters*)
1043 fun idCode k = (ord "a" <= k andalso k < ord "z") orelse
1044                (ord "A" <= k andalso k < ord "Z") orelse
1045                (ord "0" <= k andalso k < ord "9");
1047 val idCodeVec = Vector.tabulate (256, idCode);
1049 in
1051 (*Increment a list of letters like a reversed base 26 number.
1052   If head is "z", bumps chars in tail.
1053   Digits are incremented as if they were integers.
1054   "_" and "'" are not changed.
1055   For making variants of identifiers.*)
1057 fun bump_int_list(c::cs) =
1058 	if c="9" then "0" :: bump_int_list cs
1059 	else
1060         if "0" <= c andalso c < "9" then chr(ord(c)+1) :: cs
1061         else "1" :: c :: cs
1062   | bump_int_list([]) = error("bump_int_list: not an identifier");
1064 fun bump_list([], d) = [d]
1065   | bump_list(["'"], d) = [d, "'"]
1066   | bump_list("z"::cs, _) = "a" :: bump_list(cs, "a")
1067   | bump_list("Z"::cs, _) = "A" :: bump_list(cs, "A")
1068   | bump_list("9"::cs, _) = "0" :: bump_int_list cs
1069   | bump_list(c::cs, _) =
1070         let val k = ord(c)
1071         in if Vector.sub(idCodeVec,k) then chr(k+1) :: cs
1072 	   else
1073            if c="'" orelse c="_" then c :: bump_list(cs, "")
1074 	   else error("bump_list: not legal in identifier: " ^
1075 		      implode(rev(c::cs)))
1076         end;
1078 end;
1080 fun bump_string s : string = implode (rev (bump_list(rev(explode s), "")));
1083 (* lexical scanning *)
1085 (*scan a list of characters into "words" composed of "letters" (recognized by
1086   is_let) and separated by any number of non-"letters"*)
1087 fun scanwords is_let cs =
1088   let fun scan1 [] = []
1089         | scan1 cs =
1090             let val (lets, rest) = take_prefix is_let cs
1091             in implode lets :: scanwords is_let rest end;
1092   in scan1 (#2 (take_prefix (not o is_let) cs)) end;
1094 end;
1096 (*Variable-branching trees: for proof terms*)
1097 datatype 'a mtree = Join of 'a * 'a mtree list;
1099 open Library;