src/Pure/library.ML
 author wenzelm Wed Nov 05 11:33:05 1997 +0100 (1997-11-05) changeset 4139 e1659fd7a221 parent 4102 f746af27164b child 4181 fcc8b47e4c49 permissions -rw-r--r--
fixed exception OPTION;
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;
61 fun the (Some x) = x
62   | the None = raise OPTION;
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 (*handle partial functions*)
82 fun try f x = Some (f x) handle _ => None;
83 fun can f x = is_some (try f x);
87 (** pairs **)
89 fun pair x y = (x, y);
90 fun rpair x y = (y, x);
92 fun fst (x, y) = x;
93 fun snd (x, y) = y;
95 fun eq_fst ((x1, _), (x2, _)) = x1 = x2;
96 fun eq_snd ((_, y1), (_, y2)) = y1 = y2;
98 fun swap (x, y) = (y, x);
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);
106 (** booleans **)
108 (* equality *)
110 fun equal x y = x = y;
111 fun not_equal x y = x <> y;
114 (* operators for combining predicates *)
116 fun (p orf q) = fn x => p x orelse q x;
118 fun (p andf q) = fn x => p x andalso q x;
120 fun notf p x = not (p x);
123 (* predicates on lists *)
125 fun orl [] = false
126   | orl (x :: xs) = x orelse orl xs;
128 fun andl [] = true
129   | andl (x :: xs) = x andalso andl xs;
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;
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;
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;
153 (* flags *)
155 fun set flag = (flag := true; true);
156 fun reset flag = (flag := false; false);
157 fun toggle flag = (flag := not (! flag); ! flag);
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;
170 (** lists **)
172 exception LIST of string;
174 fun null [] = true
175   | null (_ :: _) = false;
177 fun hd [] = raise LIST "hd"
178   | hd (x :: _) = x;
180 fun tl [] = raise LIST "tl"
181   | tl (_ :: xs) = xs;
183 fun cons x xs = x :: xs;
186 (* fold *)
188 (*the following versions of fold are designed to fit nicely with infixes*)
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;
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;
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                       (* FIXME [] case: elim warn (?) *)
208         | itr (x::l) = f(x, itr l)
209   in  itr l  end;
212 (* basic list functions *)
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;
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 [];
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;
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);
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;
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);
247 (*find the position of an element in a list*)
248 fun find (x, ys) =
249   let fun f (y :: ys, i) = if x = y then i else f (ys, i + 1)
250         | f (_, _) = raise LIST "find"
251   in f (ys, 0) end;
253 (*flatten a list of lists to a list*)
254 fun flat (ls: 'c list list) : 'c list = foldr (op @) (ls, []);
257 (*like Lisp's MAPC -- seq proc [x1, ..., xn] evaluates
258   (proc x1; ...; proc xn) for side effects*)
259 fun seq (proc: 'a -> unit) : 'a list -> unit =
260   let fun seqf [] = ()
261         | seqf (x :: xs) = (proc x; seqf xs)
262   in seqf end;
265 (*separate s [x1, x2, ..., xn]  ===>  [x1, s, x2, s, ..., s, xn]*)
266 fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
267   | separate _ xs = xs;
269 (*make the list [x, x, ..., x] of length n*)
270 fun replicate n (x: 'a) : 'a list =
271   let fun rep (0, xs) = xs
272         | rep (n, xs) = rep (n - 1, x :: xs)
273   in
274     if n < 0 then raise LIST "replicate"
275     else rep (n, [])
276   end;
279 (* filter *)
281 (*copy the list preserving elements that satisfy the predicate*)
282 fun filter (pred: 'a->bool) : 'a list -> 'a list =
283   let fun filt [] = []
284         | filt (x :: xs) = if pred x then x :: filt xs else filt xs
285   in filt end;
287 fun filter_out f = filter (not o f);
290 fun mapfilter (f: 'a -> 'b option) ([]: 'a list) = [] : 'b list
291   | mapfilter f (x :: xs) =
292       (case f x of
293         None => mapfilter f xs
294       | Some y => y :: mapfilter f xs);
297 fun find_first _ [] = None
298   | find_first pred (x :: xs) =
299       if pred x then Some x else find_first pred xs;
302 (* lists of pairs *)
304 fun map2 _ ([], []) = []
305   | map2 f (x :: xs, y :: ys) = (f (x, y) :: map2 f (xs, ys))
306   | map2 _ _ = raise LIST "map2";
308 fun exists2 _ ([], []) = false
309   | exists2 pred (x :: xs, y :: ys) = pred (x, y) orelse exists2 pred (xs, ys)
310   | exists2 _ _ = raise LIST "exists2";
312 fun forall2 _ ([], []) = true
313   | forall2 pred (x :: xs, y :: ys) = pred (x, y) andalso forall2 pred (xs, ys)
314   | forall2 _ _ = raise LIST "forall2";
316 (*combine two lists forming a list of pairs:
317   [x1, ..., xn] ~~ [y1, ..., yn]  ===>  [(x1, y1), ..., (xn, yn)]*)
318 fun [] ~~ [] = []
319   | (x :: xs) ~~ (y :: ys) = (x, y) :: (xs ~~ ys)
320   | _ ~~ _ = raise LIST "~~";
323 (*inverse of ~~; the old 'split':
324   [(x1, y1), ..., (xn, yn)]  ===>  ([x1, ..., xn], [y1, ..., yn])*)
325 fun split_list (l: ('a * 'b) list) = (map #1 l, map #2 l);
328 (* prefixes, suffixes *)
330 fun [] prefix _ = true
331   | (x :: xs) prefix (y :: ys) = x = y andalso (xs prefix ys)
332   | _ prefix _ = false;
334 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., x(i-1)], [xi, ..., xn])
335    where xi is the first element that does not satisfy the predicate*)
336 fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
337   let fun take (rxs, []) = (rev rxs, [])
338         | take (rxs, x :: xs) =
339             if  pred x  then  take(x :: rxs, xs)  else  (rev rxs, x :: xs)
340   in  take([], xs)  end;
342 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., xi], [x(i+1), ..., xn])
343    where xi is the last element that does not satisfy the predicate*)
344 fun take_suffix _ [] = ([], [])
345   | take_suffix pred (x :: xs) =
346       (case take_suffix pred xs of
347         ([], sffx) => if pred x then ([], x :: sffx) else ([x], sffx)
348       | (prfx, sffx) => (x :: prfx, sffx));
352 (** integers **)
354 fun inc i = (i := ! i + 1; ! i);
355 fun dec i = (i := ! i - 1; ! i);
358 (* lists of integers *)
360 (*make the list [from, from + 1, ..., to]*)
361 fun (from upto to) =
362   if from > to then [] else from :: ((from + 1) upto to);
364 (*make the list [from, from - 1, ..., to]*)
365 fun (from downto to) =
366   if from < to then [] else from :: ((from - 1) downto to);
368 (*predicate: downto0 (is, n) <=> is = [n, n - 1, ..., 0]*)
369 fun downto0 (i :: is, n) = i = n andalso downto0 (is, n - 1)
370   | downto0 ([], n) = n = ~1;
373 (* convert integers to strings *)
375 (*expand the number in the given base;
376   example: radixpand (2, 8) gives [1, 0, 0, 0]*)
377 fun radixpand (base, num) : int list =
378   let
379     fun radix (n, tail) =
380       if n < base then n :: tail
381       else radix (n div base, (n mod base) :: tail)
382   in radix (num, []) end;
384 (*expands a number into a string of characters starting from "zerochar";
385   example: radixstring (2, "0", 8) gives "1000"*)
386 fun radixstring (base, zerochar, num) =
387   let val offset = ord zerochar;
388       fun chrof n = chr (offset + n)
389   in implode (map chrof (radixpand (base, num))) end;
392 val string_of_int = Int.toString;
394 fun string_of_indexname (a,0) = a
395   | string_of_indexname (a,i) = a ^ "_" ^ Int.toString i;
398 (** strings **)
400 fun is_letter ch =
401   ord "A" <= ord ch andalso ord ch <= ord "Z" orelse
402   ord "a" <= ord ch andalso ord ch <= ord "z";
404 fun is_digit ch =
405   ord "0" <= ord ch andalso ord ch <= ord "9";
407 (*letter or _ or prime (')*)
408 fun is_quasi_letter "_" = true
409   | is_quasi_letter "'" = true
410   | is_quasi_letter ch = is_letter ch;
412 (*white space: blanks, tabs, newlines, formfeeds*)
413 val is_blank : string -> bool =
414   fn " " => true | "\t" => true | "\n" => true | "\^L" => true | "\160" => true
415     | _ => false;
417 val is_letdig = is_quasi_letter orf is_digit;
419 (*printable chars*)
420 fun is_printable c = ord c > ord " " andalso ord c <= ord "~";
423 (*lower all chars of string*)
424 val to_lower =
425   let
426     fun lower ch =
427       if ch >= "A" andalso ch <= "Z" then
428         chr (ord ch - ord "A" + ord "a")
429       else ch;
430   in implode o (map lower) o explode end;
433 (*enclose in brackets*)
434 fun enclose lpar rpar str = lpar ^ str ^ rpar;
436 (*simple quoting (does not escape special chars)*)
437 val quote = enclose "\"" "\"";
439 (*space_implode "..." (explode "hello"); gives "h...e...l...l...o"*)
440 fun space_implode a bs = implode (separate a bs);
442 val commas = space_implode ", ";
443 val commas_quote = commas o map quote;
445 (*concatenate messages, one per line, into a string*)
446 val cat_lines = space_implode "\n";
448 (*BAD_space_explode "." "h.e..l.lo"; gives ["h", "e", "l", "lo"]*)
449 fun BAD_space_explode sep s =
450   let fun divide [] "" = []
451         | divide [] part = [part]
452         | divide (c::s) part =
453             if c = sep then
454               (if part = "" then divide s "" else part :: divide s "")
455             else divide s (part ^ c)
456   in divide (explode s) "" end;
458 (*space_explode "." "h.e..l.lo"; gives ["h", "e", "", "l", "lo"]*)
459 fun space_explode _ "" = []
460   | space_explode sep str =
461       let
462         fun expl chs =
463           (case take_prefix (not_equal sep) chs of
464             (cs, []) => [implode cs]
465           | (cs, _ :: cs') => implode cs :: expl cs');
466       in expl (explode str) end;
468 val split_lines = space_explode "\n";
472 (** lists as sets **)
474 (*membership in a list*)
475 fun x mem [] = false
476   | x mem (y :: ys) = x = y orelse x mem ys;
478 (*membership in a list, optimized version for ints*)
479 fun (x:int) mem_int [] = false
480   | x mem_int (y :: ys) = x = y orelse x mem_int ys;
482 (*membership in a list, optimized version for strings*)
483 fun (x:string) mem_string [] = false
484   | x mem_string (y :: ys) = x = y orelse x mem_string ys;
486 (*generalized membership test*)
487 fun gen_mem eq (x, []) = false
488   | gen_mem eq (x, y :: ys) = eq (x, y) orelse gen_mem eq (x, ys);
491 (*insertion into list if not already there*)
492 fun (x ins xs) = if x mem xs then xs else x :: xs;
494 (*insertion into list, optimized version for ints*)
495 fun (x ins_int xs) = if x mem_int xs then xs else x :: xs;
497 (*insertion into list, optimized version for strings*)
498 fun (x ins_string xs) = if x mem_string xs then xs else x :: xs;
500 (*generalized insertion*)
501 fun gen_ins eq (x, xs) = if gen_mem eq (x, xs) then xs else x :: xs;
504 (*union of sets represented as lists: no repetitions*)
505 fun xs union [] = xs
506   | [] union ys = ys
507   | (x :: xs) union ys = xs union (x ins ys);
509 (*union of sets, optimized version for ints*)
510 fun (xs:int list) union_int [] = xs
511   | [] union_int ys = ys
512   | (x :: xs) union_int ys = xs union_int (x ins_int ys);
514 (*union of sets, optimized version for strings*)
515 fun (xs:string list) union_string [] = xs
516   | [] union_string ys = ys
517   | (x :: xs) union_string ys = xs union_string (x ins_string ys);
519 (*generalized union*)
520 fun gen_union eq (xs, []) = xs
521   | gen_union eq ([], ys) = ys
522   | gen_union eq (x :: xs, ys) = gen_union eq (xs, gen_ins eq (x, ys));
525 (*intersection*)
526 fun [] inter ys = []
527   | (x :: xs) inter ys =
528       if x mem ys then x :: (xs inter ys) else xs inter ys;
530 (*intersection, optimized version for ints*)
531 fun ([]:int list) inter_int ys = []
532   | (x :: xs) inter_int ys =
533       if x mem_int ys then x :: (xs inter_int ys) else xs inter_int ys;
535 (*intersection, optimized version for strings *)
536 fun ([]:string list) inter_string ys = []
537   | (x :: xs) inter_string ys =
538       if x mem_string ys then x :: (xs inter_string ys) else xs inter_string ys;
541 (*subset*)
542 fun [] subset ys = true
543   | (x :: xs) subset ys = x mem ys andalso xs subset ys;
545 (*subset, optimized version for ints*)
546 fun ([]:int list) subset_int ys = true
547   | (x :: xs) subset_int ys = x mem_int ys andalso xs subset_int ys;
549 (*subset, optimized version for strings*)
550 fun ([]:string list) subset_string ys = true
551   | (x :: xs) subset_string ys = x mem_string ys andalso xs subset_string ys;
553 (*set equality for strings*)
554 fun eq_set_string ((xs:string list), ys) =
555   xs = ys orelse (xs subset_string ys andalso ys subset_string xs);
557 fun gen_subset eq (xs, ys) = forall (fn x => gen_mem eq (x, ys)) xs;
560 (*removing an element from a list WITHOUT duplicates*)
561 fun (y :: ys) \ x = if x = y then ys else y :: (ys \ x)
562   | [] \ x = [];
564 fun ys \\ xs = foldl (op \) (ys,xs);
566 (*removing an element from a list -- possibly WITH duplicates*)
567 fun gen_rem eq (xs, y) = filter_out (fn x => eq (x, y)) xs;
569 fun gen_rems eq = foldl (gen_rem eq);
572 (*makes a list of the distinct members of the input; preserves order, takes
573   first of equal elements*)
574 fun gen_distinct eq lst =
575   let
576     val memb = gen_mem eq;
578     fun dist (rev_seen, []) = rev rev_seen
579       | dist (rev_seen, x :: xs) =
580           if memb (x, rev_seen) then dist (rev_seen, xs)
581           else dist (x :: rev_seen, xs);
582   in
583     dist ([], lst)
584   end;
586 fun distinct l = gen_distinct (op =) l;
588 (*tuned version of distinct -- eq wrt. strings in fst component*)
589 fun distinct_fst_string lst =
590   let
591     fun mem_str ((_:string, _), []) = false
592       | mem_str (p as (x, _), ((y, _) :: qs)) = x = y orelse mem_str (p, qs);
594     fun dist (rev_seen, []) = rev rev_seen
595       | dist (rev_seen, p :: ps) =
596           if mem_str (p, rev_seen) then dist (rev_seen, ps)
597           else dist (p :: rev_seen, ps);
598   in
599     dist ([], lst)
600   end;
603 (*returns the tail beginning with the first repeated element, or []*)
604 fun findrep [] = []
605   | findrep (x :: xs) = if x mem xs then x :: xs else findrep xs;
608 (*returns a list containing all repeated elements exactly once; preserves
609   order, takes first of equal elements*)
610 fun gen_duplicates eq lst =
611   let
612     val memb = gen_mem eq;
614     fun dups (rev_dups, []) = rev rev_dups
615       | dups (rev_dups, x :: xs) =
616           if memb (x, rev_dups) orelse not (memb (x, xs)) then
617             dups (rev_dups, xs)
618           else dups (x :: rev_dups, xs);
619   in
620     dups ([], lst)
621   end;
623 fun duplicates l = gen_duplicates (op =) l;
627 (** association lists **)
629 (*association list lookup*)
630 fun assoc ([], key) = None
631   | assoc ((keyi, xi) :: pairs, key) =
632       if key = keyi then Some xi else assoc (pairs, key);
634 (*association list lookup, optimized version for ints*)
635 fun assoc_int ([], (key:int)) = None
636   | assoc_int ((keyi, xi) :: pairs, key) =
637       if key = keyi then Some xi else assoc_int (pairs, key);
639 (*association list lookup, optimized version for strings*)
640 fun assoc_string ([], (key:string)) = None
641   | assoc_string ((keyi, xi) :: pairs, key) =
642       if key = keyi then Some xi else assoc_string (pairs, key);
644 (*association list lookup, optimized version for string*ints*)
645 fun assoc_string_int ([], (key:string*int)) = None
646   | assoc_string_int ((keyi, xi) :: pairs, key) =
647       if key = keyi then Some xi else assoc_string_int (pairs, key);
649 fun assocs ps x =
650   (case assoc (ps, x) of
651     None => []
652   | Some ys => ys);
654 (*two-fold association list lookup*)
655 fun assoc2 (aal, (key1, key2)) =
656   (case assoc (aal, key1) of
657     Some al => assoc (al, key2)
658   | None => None);
660 (*generalized association list lookup*)
661 fun gen_assoc eq ([], key) = None
662   | gen_assoc eq ((keyi, xi) :: pairs, key) =
663       if eq (key, keyi) then Some xi else gen_assoc eq (pairs, key);
665 (*association list update*)
666 fun overwrite (al, p as (key, _)) =
667   let fun over ((q as (keyi, _)) :: pairs) =
668             if keyi = key then p :: pairs else q :: (over pairs)
669         | over [] = [p]
670   in over al end;
672 fun gen_overwrite eq (al, p as (key, _)) =
673   let fun over ((q as (keyi, _)) :: pairs) =
674             if eq (keyi, key) then p :: pairs else q :: (over pairs)
675         | over [] = [p]
676   in over al end;
680 (** generic tables **)
682 (*Tables are supposed to be 'efficient' encodings of lists of elements distinct
683   wrt. an equality "eq". The extend and merge operations below are optimized
684   for long-term space efficiency.*)
686 (*append (new) elements to a table*)
687 fun generic_extend _ _ _ tab [] = tab
688   | generic_extend eq dest_tab mk_tab tab1 lst2 =
689       let
690         val lst1 = dest_tab tab1;
691         val new_lst2 = gen_rems eq (lst2, lst1);
692       in
693         if null new_lst2 then tab1
694         else mk_tab (lst1 @ new_lst2)
695       end;
697 (*append (new) elements of 2nd table to 1st table*)
698 fun generic_merge eq dest_tab mk_tab tab1 tab2 =
699   let
700     val lst1 = dest_tab tab1;
701     val lst2 = dest_tab tab2;
702     val new_lst2 = gen_rems eq (lst2, lst1);
703   in
704     if null new_lst2 then tab1
705     else if gen_subset eq (lst1, lst2) then tab2
706     else mk_tab (lst1 @ new_lst2)
707   end;
710 (*lists as tables*)
711 fun extend_list tab = generic_extend (op =) I I tab;
712 fun merge_lists tab = generic_merge (op =) I I tab;
714 fun merge_rev_lists xs [] = xs
715   | merge_rev_lists [] ys = ys
716   | merge_rev_lists xs (y :: ys) =
717       (if y mem xs then I else cons y) (merge_rev_lists xs ys);
721 (** balanced trees **)
723 exception Balance;      (*indicates non-positive argument to balancing fun*)
725 (*balanced folding; avoids deep nesting*)
726 fun fold_bal f [x] = x
727   | fold_bal f [] = raise Balance
728   | fold_bal f xs =
729       let val k = length xs div 2
730       in  f (fold_bal f (take(k, xs)),
731              fold_bal f (drop(k, xs)))
732       end;
734 (*construct something of the form f(...g(...(x)...)) for balanced access*)
735 fun access_bal (f, g, x) n i =
736   let fun acc n i =     (*1<=i<=n*)
737           if n=1 then x else
738           let val n2 = n div 2
739           in  if i<=n2 then f (acc n2 i)
740                        else g (acc (n-n2) (i-n2))
741           end
742   in  if 1<=i andalso i<=n then acc n i else raise Balance  end;
744 (*construct ALL such accesses; could try harder to share recursive calls!*)
745 fun accesses_bal (f, g, x) n =
746   let fun acc n =
747           if n=1 then [x] else
748           let val n2 = n div 2
749               val acc2 = acc n2
750           in  if n-n2=n2 then map f acc2 @ map g acc2
751                          else map f acc2 @ map g (acc (n-n2)) end
752   in  if 1<=n then acc n else raise Balance  end;
756 (** orders **)
758 datatype order = LESS | EQUAL | GREATER;
760 fun intord (i, j: int) =
761   if i < j then LESS
762   else if i = j then EQUAL
763   else GREATER;
765 fun stringord (a, b: string) =
766   if a < b then LESS
767   else if a = b then EQUAL
768   else GREATER;
772 (** input / output and diagnostics **)
774 val cd = OS.FileSys.chDir;
775 val pwd = OS.FileSys.getDir;
778 local
779   fun out s =
780     (TextIO.output (TextIO.stdOut, s); TextIO.flushOut TextIO.stdOut);
782   fun prefix_lines prfx txt =
783     txt |> split_lines |> map (fn s => prfx ^ s ^ "\n") |> implode;
784 in
786 (*hooks for output channels: normal, warning, error*)
787 val prs_fn = ref (fn s => out s);
788 val warning_fn = ref (fn s => out (prefix_lines "### " s));
789 val error_fn = ref (fn s => out (prefix_lines "*** " s));
791 end;
793 fun prs s = !prs_fn s;
794 fun writeln s = prs (s ^ "\n");
796 fun warning s = !warning_fn s;
798 (*print error message and abort to top level*)
799 exception ERROR;
800 fun error_msg s = !error_fn s;			(*promise to raise ERROR later!*)
801 fun error s = (error_msg s; raise ERROR);
802 fun sys_error msg = (error_msg " !! SYSTEM ERROR !!\n"; error msg);
804 fun assert p msg = if p then () else error msg;
805 fun deny p msg = if p then error msg else ();
807 (*Assert pred for every member of l, generating a message if pred fails*)
808 fun assert_all pred l msg_fn =
809   let fun asl [] = ()
810         | asl (x::xs) = if pred x then asl xs
811                         else error (msg_fn x)
812   in  asl l  end;
815 (* handle errors (capturing messages) *)
817 datatype 'a error =
818   Error of string |
819   OK of 'a;
821 fun handle_error f x =
822   let
823     val buffer = ref "";
824     fun capture s = buffer := ! buffer ^ s ^ "\n";
825     val result = Some (setmp error_fn capture f x) handle ERROR => None;
826   in
827     case result of
828       None => Error (! buffer)
829     | Some y => OK y
830   end;
833 (* read / write files *)
835 fun read_file name =
836   let
837     val instream  = TextIO.openIn name;
838     val intext = TextIO.inputAll instream;
839   in
840     TextIO.closeIn instream;
841     intext
842   end;
844 fun write_file name txt =
845   let val outstream = TextIO.openOut name in
846     TextIO.output (outstream, txt);
847     TextIO.closeOut outstream
848   end;
850 fun append_file name txt =
851   let val outstream = TextIO.openAppend name in
852     TextIO.output (outstream, txt);
853     TextIO.closeOut outstream
854   end;
857 (*for the "test" target in IsaMakefiles -- signifies successful termination*)
858 fun maketest msg =
859   (writeln msg; write_file "test" "Test examples ran successfully\n");
862 (*print a list surrounded by the brackets lpar and rpar, with comma separator
863   print nothing for empty list*)
864 fun print_list (lpar, rpar, pre: 'a -> unit) (l : 'a list) =
865   let fun prec x = (prs ","; pre x)
866   in
867     (case l of
868       [] => ()
869     | x::l => (prs lpar; pre x; seq prec l; prs rpar))
870   end;
872 (*print a list of items separated by newlines*)
873 fun print_list_ln (pre: 'a -> unit) : 'a list -> unit =
874   seq (fn x => (pre x; writeln ""));
877 val print_int = prs o string_of_int;
880 (* output to LaTeX / xdvi *)
881 fun latex s =
882   execute ("( cd /tmp ; echo \"" ^ s ^
883     "\" | isa2latex -s > \$\$.tex ; latex \$\$.tex ; xdvi \$\$.dvi ; rm \$\$.* ) > /dev/null &");
886 (** timing **)
888 (*unconditional timing function*)
889 fun timeit x = cond_timeit true x;
891 (*timed application function*)
892 fun timeap f x = timeit (fn () => f x);
894 (*timed "use" function, printing filenames*)
895 fun time_use fname = timeit (fn () =>
896   (writeln ("\n**** Starting " ^ fname ^ " ****"); use fname;
897    writeln ("\n**** Finished " ^ fname ^ " ****")));
899 (*use the file, but exit with error code if errors found.*)
900 fun exit_use fname = use fname handle _ => exit 1;
903 (** filenames and paths **)
905 (*Convert UNIX filename of the form "path/file" to "path/" and "file";
906   if filename contains no slash, then it returns "" and "file"*)
907 val split_filename =
908   (pairself implode) o take_suffix (not_equal "/") o explode;
910 val base_name = #2 o split_filename;
912 (*Merge splitted filename (path and file);
913   if path does not end with one a slash is appended*)
914 fun tack_on "" name = name
915   | tack_on path name =
916       if last_elem (explode path) = "/" then path ^ name
917       else path ^ "/" ^ name;
919 (*Remove the extension of a filename, i.e. the part after the last '.'*)
920 val remove_ext = implode o #1 o take_suffix (not_equal ".") o explode;
922 (*Make relative path to reach an absolute location from a different one*)
923 fun relative_path cur_path dest_path =
924   let (*Remove common beginning of both paths and make relative path*)
925       fun mk_relative [] [] = []
926         | mk_relative [] ds = ds
927         | mk_relative cs [] = map (fn _ => "..") cs
928         | mk_relative (c::cs) (d::ds) =
929             if c = d then mk_relative cs ds
930             else ".." :: map (fn _ => "..") cs @ (d::ds);
931   in if cur_path = "" orelse hd (explode cur_path) <> "/" orelse
932         dest_path = "" orelse hd (explode dest_path) <> "/" then
933        error "Relative or empty path passed to relative_path"
934      else ();
935      space_implode "/" (mk_relative (BAD_space_explode "/" cur_path)
936                                     (BAD_space_explode "/" dest_path))
937   end;
939 (*Determine if absolute path1 is a subdirectory of absolute path2*)
940 fun path1 subdir_of path2 =
941   if hd (explode path1) <> "/" orelse hd (explode path2) <> "/" then
942     error "Relative or empty path passed to subdir_of"
943   else (BAD_space_explode "/" path2) prefix (BAD_space_explode "/" path1);
945 fun absolute_path cwd file =
946   let fun rm_points [] result = rev result
947         | rm_points (".."::ds) result = rm_points ds (tl result)
948         | rm_points ("."::ds) result = rm_points ds result
949         | rm_points (d::ds) result = rm_points ds (d::result);
950   in if file = "" then ""
951      else if hd (explode file) = "/" then file
952      else "/" ^ space_implode "/"
953                   (rm_points (BAD_space_explode "/" (tack_on cwd file)) [])
954   end;
956 fun file_exists file = (file_info file <> "");
959 (** misc functions **)
961 (*use the keyfun to make a list of (x, key) pairs*)
962 fun make_keylist (keyfun: 'a->'b) : 'a list -> ('a * 'b) list =
963   let fun keypair x = (x, keyfun x)
964   in map keypair end;
966 (*given a list of (x, key) pairs and a searchkey
967   return the list of xs from each pair whose key equals searchkey*)
968 fun keyfilter [] searchkey = []
969   | keyfilter ((x, key) :: pairs) searchkey =
970       if key = searchkey then x :: keyfilter pairs searchkey
971       else keyfilter pairs searchkey;
974 (*Partition list into elements that satisfy predicate and those that don't.
975   Preserves order of elements in both lists.*)
976 fun partition (pred: 'a->bool) (ys: 'a list) : ('a list * 'a list) =
977     let fun part ([], answer) = answer
978           | part (x::xs, (ys, ns)) = if pred(x)
979             then  part (xs, (x::ys, ns))
980             else  part (xs, (ys, x::ns))
981     in  part (rev ys, ([], []))  end;
984 fun partition_eq (eq:'a * 'a -> bool) =
985     let fun part [] = []
986           | part (x::ys) = let val (xs, xs') = partition (apl(x, eq)) ys
987                            in (x::xs)::(part xs') end
988     in part end;
991 (*Partition a list into buckets  [ bi, b(i+1), ..., bj ]
992    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
993 fun partition_list p i j =
994   let fun part k xs =
995             if k>j then
996               (case xs of [] => []
997                          | _ => raise LIST "partition_list")
998             else
999             let val (ns, rest) = partition (p k) xs;
1000             in  ns :: part(k+1)rest  end
1001   in  part i end;
1004 (* sorting *)
1006 (*insertion sort; stable (does not reorder equal elements)
1007   'less' is less-than test on type 'a*)
1008 fun sort (less: 'a*'a -> bool) =
1009   let fun insert (x, []) = [x]
1010         | insert (x, y::ys) =
1011               if less(y, x) then y :: insert (x, ys) else x::y::ys;
1012       fun sort1 [] = []
1013         | sort1 (x::xs) = insert (x, sort1 xs)
1014   in  sort1  end;
1016 (*sort strings*)
1017 fun sort_wrt sel xs = sort (op <= o pairself (sel: 'a -> string)) xs;
1018 val sort_strings = sort_wrt I;
1021 (* transitive closure (not Warshall's algorithm) *)
1023 fun transitive_closure [] = []
1024   | transitive_closure ((x, ys)::ps) =
1025       let val qs = transitive_closure ps
1026           val zs = foldl (fn (zs, y) => assocs qs y union_string zs) (ys, ys)
1027           fun step(u, us) = (u, if x mem_string us then zs union_string us
1028                                 else us)
1029       in (x, zs) :: map step qs end;
1032 (* generating identifiers *)
1034 (** Freshly generated identifiers; supplied prefix MUST start with a letter **)
1035 local
1036 (*Maps 0-63 to A-Z, a-z, 0-9 or _ or ' for generating random identifiers*)
1037 fun char i =      if i<26 then chr (ord "A" + i)
1038 	     else if i<52 then chr (ord "a" + i - 26)
1039 	     else if i<62 then chr (ord"0" + i - 52)
1040 	     else if i=62 then "_"
1041 	     else  (*i=63*)    "'";
1043 val charVec = Vector.tabulate (64, char);
1045 fun newid n =
1046   let
1047   in  implode (map (fn i => Vector.sub(charVec,i)) (radixpand (64,n)))  end
1049   val seedr = ref 0;
1051 in
1052 fun init_gensym() = (seedr := 0);
1054 fun gensym pre = pre ^
1055                  (#1(newid (!seedr),
1056                      seedr := 1+ !seedr))
1057 end;
1060 local
1061 (*Identifies those character codes legal in identifiers.
1062   chould use Basis Library character functions if Poly/ML provided characters*)
1063 fun idCode k = (ord "a" <= k andalso k < ord "z") orelse
1064                (ord "A" <= k andalso k < ord "Z") orelse
1065                (ord "0" <= k andalso k < ord "9");
1067 val idCodeVec = Vector.tabulate (256, idCode);
1069 in
1071 (*Increment a list of letters like a reversed base 26 number.
1072   If head is "z", bumps chars in tail.
1073   Digits are incremented as if they were integers.
1074   "_" and "'" are not changed.
1075   For making variants of identifiers.*)
1077 fun bump_int_list(c::cs) =
1078 	if c="9" then "0" :: bump_int_list cs
1079 	else
1080         if "0" <= c andalso c < "9" then chr(ord(c)+1) :: cs
1081         else "1" :: c :: cs
1082   | bump_int_list([]) = error("bump_int_list: not an identifier");
1084 fun bump_list([], d) = [d]
1085   | bump_list(["'"], d) = [d, "'"]
1086   | bump_list("z"::cs, _) = "a" :: bump_list(cs, "a")
1087   | bump_list("Z"::cs, _) = "A" :: bump_list(cs, "A")
1088   | bump_list("9"::cs, _) = "0" :: bump_int_list cs
1089   | bump_list(c::cs, _) =
1090         let val k = ord(c)
1091         in if Vector.sub(idCodeVec,k) then chr(k+1) :: cs
1092 	   else
1093            if c="'" orelse c="_" then c :: bump_list(cs, "")
1094 	   else error("bump_list: not legal in identifier: " ^
1095 		      implode(rev(c::cs)))
1096         end;
1098 end;
1100 fun bump_string s : string = implode (rev (bump_list(rev(explode s), "")));
1103 (* lexical scanning *)
1105 (*scan a list of characters into "words" composed of "letters" (recognized by
1106   is_let) and separated by any number of non-"letters"*)
1107 fun scanwords is_let cs =
1108   let fun scan1 [] = []
1109         | scan1 cs =
1110             let val (lets, rest) = take_prefix is_let cs
1111             in implode lets :: scanwords is_let rest end;
1112   in scan1 (#2 (take_prefix (not o is_let) cs)) end;
1114 end;
1116 (*Variable-branching trees: for proof terms*)
1117 datatype 'a mtree = Join of 'a * 'a mtree list;
1119 open Library;