src/Pure/library.ML
 author wenzelm Thu Oct 30 16:59:56 1997 +0100 (1997-10-30) changeset 4046 f89dbf002604 parent 3973 1be726ef6813 child 4063 0b19014b9155 permissions -rw-r--r--
added merge_opts: ('a * 'a -> 'a) -> 'a option * 'a option -> 'a 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 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));
83 (** pairs **)
85 fun pair x y = (x, y);
86 fun rpair x y = (y, x);
88 fun fst (x, y) = x;
89 fun snd (x, y) = y;
91 fun eq_fst ((x1, _), (x2, _)) = x1 = x2;
92 fun eq_snd ((_, y1), (_, y2)) = y1 = y2;
94 fun swap (x, y) = (y, x);
96 (*apply the function to a component of a pair*)
97 fun apfst f (x, y) = (f x, y);
98 fun apsnd f (x, y) = (x, f y);
102 (** booleans **)
104 (* equality *)
106 fun equal x y = x = y;
107 fun not_equal x y = x <> y;
110 (* operators for combining predicates *)
112 fun (p orf q) = fn x => p x orelse q x;
114 fun (p andf q) = fn x => p x andalso q x;
116 fun notf p x = not (p x);
119 (* predicates on lists *)
121 fun orl [] = false
122   | orl (x :: xs) = x orelse orl xs;
124 fun andl [] = true
125   | andl (x :: xs) = x andalso andl xs;
127 (*Several object-logics declare theories named List or Option, hiding the
128   eponymous basis library structures.*)
129 structure List_ = List
130 and       Option_ = Option;
132 (*exists pred [x1, ..., xn] ===> pred x1 orelse ... orelse pred xn*)
133 fun exists (pred: 'a -> bool) : 'a list -> bool =
134   let fun boolf [] = false
135         | boolf (x :: xs) = pred x orelse boolf xs
136   in boolf end;
138 (*forall pred [x1, ..., xn] ===> pred x1 andalso ... andalso pred xn*)
139 fun forall (pred: 'a -> bool) : 'a list -> bool =
140   let fun boolf [] = true
141         | boolf (x :: xs) = pred x andalso boolf xs
142   in boolf end;
145 (* flags *)
147 fun set flag = (flag := true; true);
148 fun reset flag = (flag := false; false);
149 fun toggle flag = (flag := not (! flag); ! flag);
151 fun setmp flag value f x =
152   let
153     val orig_value = ! flag;
154     fun return y = (flag := orig_value; y);
155   in
156     flag := value;
157     return (f x handle exn => (return (); raise exn))
158   end;
162 (** lists **)
164 exception LIST of string;
166 fun null [] = true
167   | null (_ :: _) = false;
169 fun hd [] = raise LIST "hd"
170   | hd (x :: _) = x;
172 fun tl [] = raise LIST "tl"
173   | tl (_ :: xs) = xs;
175 fun cons x xs = x :: xs;
178 (* fold *)
180 (*the following versions of fold are designed to fit nicely with infixes*)
182 (*  (op @) (e, [x1, ..., xn])  ===>  ((e @ x1) @ x2) ... @ xn
183     for operators that associate to the left (TAIL RECURSIVE)*)
184 fun foldl (f: 'a * 'b -> 'a) : 'a * 'b list -> 'a =
185   let fun itl (e, [])  = e
186         | itl (e, a::l) = itl (f(e, a), l)
187   in  itl end;
189 (*  (op @) ([x1, ..., xn], e)  ===>   x1 @ (x2 ... @ (xn @ e))
190     for operators that associate to the right (not tail recursive)*)
191 fun foldr f (l, e) =
192   let fun itr [] = e
193         | itr (a::l) = f(a, itr l)
194   in  itr l  end;
196 (*  (op @) [x1, ..., xn]  ===>   x1 @ (x2 ... @ (x[n-1] @ xn))
197     for n > 0, operators that associate to the right (not tail recursive)*)
198 fun foldr1 f l =
199   let fun itr [x] = x                       (* FIXME [] case: elim warn (?) *)
200         | itr (x::l) = f(x, itr l)
201   in  itr l  end;
204 (* basic list functions *)
206 (*length of a list, should unquestionably be a standard function*)
207 local fun length1 (n, [])  = n   (*TAIL RECURSIVE*)
208         | length1 (n, x :: xs) = length1 (n + 1, xs)
209 in  fun length l = length1 (0, l) end;
211 (*take the first n elements from a list*)
212 fun take (n, []) = []
213   | take (n, x :: xs) =
214       if n > 0 then x :: take (n - 1, xs) else [];
216 (*drop the first n elements from a list*)
217 fun drop (n, []) = []
218   | drop (n, x :: xs) =
219       if n > 0 then drop (n - 1, xs) else x :: xs;
221 (*return nth element of a list, where 0 designates the first element;
222   raise EXCEPTION if list too short*)
223 fun nth_elem NL =
224   (case drop NL of
225     [] => raise LIST "nth_elem"
226   | x :: _ => x);
228 (*last element of a list*)
229 fun last_elem [] = raise LIST "last_elem"
230   | last_elem [x] = x
231   | last_elem (_ :: xs) = last_elem xs;
233 (*rear decomposition*)
234 fun split_last [] = raise LIST "split_last"
235   | split_last [x] = ([], x)
236   | split_last (x :: xs) = apfst (cons x) (split_last xs);
239 (*find the position of an element in a list*)
240 fun find (x, ys) =
241   let fun f (y :: ys, i) = if x = y then i else f (ys, i + 1)
242         | f (_, _) = raise LIST "find"
243   in f (ys, 0) end;
245 (*flatten a list of lists to a list*)
246 fun flat (ls: 'c list list) : 'c list = foldr (op @) (ls, []);
249 (*like Lisp's MAPC -- seq proc [x1, ..., xn] evaluates
250   (proc x1; ...; proc xn) for side effects*)
251 fun seq (proc: 'a -> unit) : 'a list -> unit =
252   let fun seqf [] = ()
253         | seqf (x :: xs) = (proc x; seqf xs)
254   in seqf end;
257 (*separate s [x1, x2, ..., xn]  ===>  [x1, s, x2, s, ..., s, xn]*)
258 fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
259   | separate _ xs = xs;
261 (*make the list [x, x, ..., x] of length n*)
262 fun replicate n (x: 'a) : 'a list =
263   let fun rep (0, xs) = xs
264         | rep (n, xs) = rep (n - 1, x :: xs)
265   in
266     if n < 0 then raise LIST "replicate"
267     else rep (n, [])
268   end;
271 (* filter *)
273 (*copy the list preserving elements that satisfy the predicate*)
274 fun filter (pred: 'a->bool) : 'a list -> 'a list =
275   let fun filt [] = []
276         | filt (x :: xs) = if pred x then x :: filt xs else filt xs
277   in filt end;
279 fun filter_out f = filter (not o f);
282 fun mapfilter (f: 'a -> 'b option) ([]: 'a list) = [] : 'b list
283   | mapfilter f (x :: xs) =
284       (case f x of
285         None => mapfilter f xs
286       | Some y => y :: mapfilter f xs);
289 fun find_first _ [] = None
290   | find_first pred (x :: xs) =
291       if pred x then Some x else find_first pred xs;
294 (* lists of pairs *)
296 fun map2 _ ([], []) = []
297   | map2 f (x :: xs, y :: ys) = (f (x, y) :: map2 f (xs, ys))
298   | map2 _ _ = raise LIST "map2";
300 fun exists2 _ ([], []) = false
301   | exists2 pred (x :: xs, y :: ys) = pred (x, y) orelse exists2 pred (xs, ys)
302   | exists2 _ _ = raise LIST "exists2";
304 fun forall2 _ ([], []) = true
305   | forall2 pred (x :: xs, y :: ys) = pred (x, y) andalso forall2 pred (xs, ys)
306   | forall2 _ _ = raise LIST "forall2";
308 (*combine two lists forming a list of pairs:
309   [x1, ..., xn] ~~ [y1, ..., yn]  ===>  [(x1, y1), ..., (xn, yn)]*)
310 fun [] ~~ [] = []
311   | (x :: xs) ~~ (y :: ys) = (x, y) :: (xs ~~ ys)
312   | _ ~~ _ = raise LIST "~~";
315 (*inverse of ~~; the old 'split':
316   [(x1, y1), ..., (xn, yn)]  ===>  ([x1, ..., xn], [y1, ..., yn])*)
317 fun split_list (l: ('a * 'b) list) = (map #1 l, map #2 l);
320 (* prefixes, suffixes *)
322 fun [] prefix _ = true
323   | (x :: xs) prefix (y :: ys) = x = y andalso (xs prefix ys)
324   | _ prefix _ = false;
326 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., x(i-1)], [xi, ..., xn])
327    where xi is the first element that does not satisfy the predicate*)
328 fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
329   let fun take (rxs, []) = (rev rxs, [])
330         | take (rxs, x :: xs) =
331             if  pred x  then  take(x :: rxs, xs)  else  (rev rxs, x :: xs)
332   in  take([], xs)  end;
334 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., xi], [x(i+1), ..., xn])
335    where xi is the last element that does not satisfy the predicate*)
336 fun take_suffix _ [] = ([], [])
337   | take_suffix pred (x :: xs) =
338       (case take_suffix pred xs of
339         ([], sffx) => if pred x then ([], x :: sffx) else ([x], sffx)
340       | (prfx, sffx) => (x :: prfx, sffx));
344 (** integers **)
346 fun inc i = (i := ! i + 1; ! i);
347 fun dec i = (i := ! i - 1; ! i);
350 (* lists of integers *)
352 (*make the list [from, from + 1, ..., to]*)
353 fun (from upto to) =
354   if from > to then [] else from :: ((from + 1) upto to);
356 (*make the list [from, from - 1, ..., to]*)
357 fun (from downto to) =
358   if from < to then [] else from :: ((from - 1) downto to);
360 (*predicate: downto0 (is, n) <=> is = [n, n - 1, ..., 0]*)
361 fun downto0 (i :: is, n) = i = n andalso downto0 (is, n - 1)
362   | downto0 ([], n) = n = ~1;
365 (* convert integers to strings *)
367 (*expand the number in the given base;
368   example: radixpand (2, 8) gives [1, 0, 0, 0]*)
369 fun radixpand (base, num) : int list =
370   let
371     fun radix (n, tail) =
372       if n < base then n :: tail
373       else radix (n div base, (n mod base) :: tail)
374   in radix (num, []) end;
376 (*expands a number into a string of characters starting from "zerochar";
377   example: radixstring (2, "0", 8) gives "1000"*)
378 fun radixstring (base, zerochar, num) =
379   let val offset = ord zerochar;
380       fun chrof n = chr (offset + n)
381   in implode (map chrof (radixpand (base, num))) end;
384 val string_of_int = Int.toString;
386 fun string_of_indexname (a,0) = a
387   | string_of_indexname (a,i) = a ^ "_" ^ Int.toString i;
390 (** strings **)
392 fun is_letter ch =
393   ord "A" <= ord ch andalso ord ch <= ord "Z" orelse
394   ord "a" <= ord ch andalso ord ch <= ord "z";
396 fun is_digit ch =
397   ord "0" <= ord ch andalso ord ch <= ord "9";
399 (*letter or _ or prime (')*)
400 fun is_quasi_letter "_" = true
401   | is_quasi_letter "'" = true
402   | is_quasi_letter ch = is_letter ch;
404 (*white space: blanks, tabs, newlines, formfeeds*)
405 val is_blank : string -> bool =
406   fn " " => true | "\t" => true | "\n" => true | "\^L" => true | "\160" => true
407     | _ => false;
409 val is_letdig = is_quasi_letter orf is_digit;
411 (*printable chars*)
412 fun is_printable c = ord c > ord " " andalso ord c <= ord "~";
415 (*lower all chars of string*)
416 val to_lower =
417   let
418     fun lower ch =
419       if ch >= "A" andalso ch <= "Z" then
420         chr (ord ch - ord "A" + ord "a")
421       else ch;
422   in implode o (map lower) o explode end;
425 (*enclose in brackets*)
426 fun enclose lpar rpar str = lpar ^ str ^ rpar;
428 (*simple quoting (does not escape special chars)*)
429 val quote = enclose "\"" "\"";
431 (*space_implode "..." (explode "hello"); gives "h...e...l...l...o"*)
432 fun space_implode a bs = implode (separate a bs);
434 val commas = space_implode ", ";
435 val commas_quote = commas o map quote;
437 (*concatenate messages, one per line, into a string*)
438 val cat_lines = space_implode "\n";
440 (*BAD_space_explode "." "h.e..l.lo"; gives ["h", "e", "l", "lo"]*)
441 fun BAD_space_explode sep s =
442   let fun divide [] "" = []
443         | divide [] part = [part]
444         | divide (c::s) part =
445             if c = sep then
446               (if part = "" then divide s "" else part :: divide s "")
447             else divide s (part ^ c)
448   in divide (explode s) "" end;
450 (*space_explode "." "h.e..l.lo"; gives ["h", "e", "", "l", "lo"]*)
451 fun space_explode _ "" = []
452   | space_explode sep str =
453       let
454         fun expl chs =
455           (case take_prefix (not_equal sep) chs of
456             (cs, []) => [implode cs]
457           | (cs, _ :: cs') => implode cs :: expl cs');
458       in expl (explode str) end;
460 val split_lines = space_explode "\n";
464 (** lists as sets **)
466 (*membership in a list*)
467 fun x mem [] = false
468   | x mem (y :: ys) = x = y orelse x mem ys;
470 (*membership in a list, optimized version for ints*)
471 fun (x:int) mem_int [] = false
472   | x mem_int (y :: ys) = x = y orelse x mem_int ys;
474 (*membership in a list, optimized version for strings*)
475 fun (x:string) mem_string [] = false
476   | x mem_string (y :: ys) = x = y orelse x mem_string ys;
478 (*generalized membership test*)
479 fun gen_mem eq (x, []) = false
480   | gen_mem eq (x, y :: ys) = eq (x, y) orelse gen_mem eq (x, ys);
483 (*insertion into list if not already there*)
484 fun (x ins xs) = if x mem xs then xs else x :: xs;
486 (*insertion into list, optimized version for ints*)
487 fun (x ins_int xs) = if x mem_int xs then xs else x :: xs;
489 (*insertion into list, optimized version for strings*)
490 fun (x ins_string xs) = if x mem_string xs then xs else x :: xs;
492 (*generalized insertion*)
493 fun gen_ins eq (x, xs) = if gen_mem eq (x, xs) then xs else x :: xs;
496 (*union of sets represented as lists: no repetitions*)
497 fun xs union [] = xs
498   | [] union ys = ys
499   | (x :: xs) union ys = xs union (x ins ys);
501 (*union of sets, optimized version for ints*)
502 fun (xs:int list) union_int [] = xs
503   | [] union_int ys = ys
504   | (x :: xs) union_int ys = xs union_int (x ins_int ys);
506 (*union of sets, optimized version for strings*)
507 fun (xs:string list) union_string [] = xs
508   | [] union_string ys = ys
509   | (x :: xs) union_string ys = xs union_string (x ins_string ys);
511 (*generalized union*)
512 fun gen_union eq (xs, []) = xs
513   | gen_union eq ([], ys) = ys
514   | gen_union eq (x :: xs, ys) = gen_union eq (xs, gen_ins eq (x, ys));
517 (*intersection*)
518 fun [] inter ys = []
519   | (x :: xs) inter ys =
520       if x mem ys then x :: (xs inter ys) else xs inter ys;
522 (*intersection, optimized version for ints*)
523 fun ([]:int list) inter_int ys = []
524   | (x :: xs) inter_int ys =
525       if x mem_int ys then x :: (xs inter_int ys) else xs inter_int ys;
527 (*intersection, optimized version for strings *)
528 fun ([]:string list) inter_string ys = []
529   | (x :: xs) inter_string ys =
530       if x mem_string ys then x :: (xs inter_string ys) else xs inter_string ys;
533 (*subset*)
534 fun [] subset ys = true
535   | (x :: xs) subset ys = x mem ys andalso xs subset ys;
537 (*subset, optimized version for ints*)
538 fun ([]:int list) subset_int ys = true
539   | (x :: xs) subset_int ys = x mem_int ys andalso xs subset_int ys;
541 (*subset, optimized version for strings*)
542 fun ([]:string list) subset_string ys = true
543   | (x :: xs) subset_string ys = x mem_string ys andalso xs subset_string ys;
545 (*set equality for strings*)
546 fun eq_set_string ((xs:string list), ys) =
547   xs = ys orelse (xs subset_string ys andalso ys subset_string xs);
549 fun gen_subset eq (xs, ys) = forall (fn x => gen_mem eq (x, ys)) xs;
552 (*removing an element from a list WITHOUT duplicates*)
553 fun (y :: ys) \ x = if x = y then ys else y :: (ys \ x)
554   | [] \ x = [];
556 fun ys \\ xs = foldl (op \) (ys,xs);
558 (*removing an element from a list -- possibly WITH duplicates*)
559 fun gen_rem eq (xs, y) = filter_out (fn x => eq (x, y)) xs;
561 fun gen_rems eq = foldl (gen_rem eq);
564 (*makes a list of the distinct members of the input; preserves order, takes
565   first of equal elements*)
566 fun gen_distinct eq lst =
567   let
568     val memb = gen_mem eq;
570     fun dist (rev_seen, []) = rev rev_seen
571       | dist (rev_seen, x :: xs) =
572           if memb (x, rev_seen) then dist (rev_seen, xs)
573           else dist (x :: rev_seen, xs);
574   in
575     dist ([], lst)
576   end;
578 fun distinct l = gen_distinct (op =) l;
581 (*returns the tail beginning with the first repeated element, or []*)
582 fun findrep [] = []
583   | findrep (x :: xs) = if x mem xs then x :: xs else findrep xs;
586 (*returns a list containing all repeated elements exactly once; preserves
587   order, takes first of equal elements*)
588 fun gen_duplicates eq lst =
589   let
590     val memb = gen_mem eq;
592     fun dups (rev_dups, []) = rev rev_dups
593       | dups (rev_dups, x :: xs) =
594           if memb (x, rev_dups) orelse not (memb (x, xs)) then
595             dups (rev_dups, xs)
596           else dups (x :: rev_dups, xs);
597   in
598     dups ([], lst)
599   end;
601 fun duplicates l = gen_duplicates (op =) l;
605 (** association lists **)
607 (*association list lookup*)
608 fun assoc ([], key) = None
609   | assoc ((keyi, xi) :: pairs, key) =
610       if key = keyi then Some xi else assoc (pairs, key);
612 (*association list lookup, optimized version for ints*)
613 fun assoc_int ([], (key:int)) = None
614   | assoc_int ((keyi, xi) :: pairs, key) =
615       if key = keyi then Some xi else assoc_int (pairs, key);
617 (*association list lookup, optimized version for strings*)
618 fun assoc_string ([], (key:string)) = None
619   | assoc_string ((keyi, xi) :: pairs, key) =
620       if key = keyi then Some xi else assoc_string (pairs, key);
622 (*association list lookup, optimized version for string*ints*)
623 fun assoc_string_int ([], (key:string*int)) = None
624   | assoc_string_int ((keyi, xi) :: pairs, key) =
625       if key = keyi then Some xi else assoc_string_int (pairs, key);
627 fun assocs ps x =
628   (case assoc (ps, x) of
629     None => []
630   | Some ys => ys);
632 (*two-fold association list lookup*)
633 fun assoc2 (aal, (key1, key2)) =
634   (case assoc (aal, key1) of
635     Some al => assoc (al, key2)
636   | None => None);
638 (*generalized association list lookup*)
639 fun gen_assoc eq ([], key) = None
640   | gen_assoc eq ((keyi, xi) :: pairs, key) =
641       if eq (key, keyi) then Some xi else gen_assoc eq (pairs, key);
643 (*association list update*)
644 fun overwrite (al, p as (key, _)) =
645   let fun over ((q as (keyi, _)) :: pairs) =
646             if keyi = key then p :: pairs else q :: (over pairs)
647         | over [] = [p]
648   in over al end;
650 fun gen_overwrite eq (al, p as (key, _)) =
651   let fun over ((q as (keyi, _)) :: pairs) =
652             if eq (keyi, key) then p :: pairs else q :: (over pairs)
653         | over [] = [p]
654   in over al end;
658 (** generic tables **)
660 (*Tables are supposed to be 'efficient' encodings of lists of elements distinct
661   wrt. an equality "eq". The extend and merge operations below are optimized
662   for long-term space efficiency.*)
664 (*append (new) elements to a table*)
665 fun generic_extend _ _ _ tab [] = tab
666   | generic_extend eq dest_tab mk_tab tab1 lst2 =
667       let
668         val lst1 = dest_tab tab1;
669         val new_lst2 = gen_rems eq (lst2, lst1);
670       in
671         if null new_lst2 then tab1
672         else mk_tab (lst1 @ new_lst2)
673       end;
675 (*append (new) elements of 2nd table to 1st table*)
676 fun generic_merge eq dest_tab mk_tab tab1 tab2 =
677   let
678     val lst1 = dest_tab tab1;
679     val lst2 = dest_tab tab2;
680     val new_lst2 = gen_rems eq (lst2, lst1);
681   in
682     if null new_lst2 then tab1
683     else if gen_subset eq (lst1, lst2) then tab2
684     else mk_tab (lst1 @ new_lst2)
685   end;
688 (*lists as tables*)
689 fun extend_list tab = generic_extend (op =) I I tab;
690 fun merge_lists tab = generic_merge (op =) I I tab;
692 fun merge_rev_lists xs [] = xs
693   | merge_rev_lists [] ys = ys
694   | merge_rev_lists xs (y :: ys) =
695       (if y mem xs then I else cons y) (merge_rev_lists xs ys);
699 (** balanced trees **)
701 exception Balance;      (*indicates non-positive argument to balancing fun*)
703 (*balanced folding; avoids deep nesting*)
704 fun fold_bal f [x] = x
705   | fold_bal f [] = raise Balance
706   | fold_bal f xs =
707       let val k = length xs div 2
708       in  f (fold_bal f (take(k, xs)),
709              fold_bal f (drop(k, xs)))
710       end;
712 (*construct something of the form f(...g(...(x)...)) for balanced access*)
713 fun access_bal (f, g, x) n i =
714   let fun acc n i =     (*1<=i<=n*)
715           if n=1 then x else
716           let val n2 = n div 2
717           in  if i<=n2 then f (acc n2 i)
718                        else g (acc (n-n2) (i-n2))
719           end
720   in  if 1<=i andalso i<=n then acc n i else raise Balance  end;
722 (*construct ALL such accesses; could try harder to share recursive calls!*)
723 fun accesses_bal (f, g, x) n =
724   let fun acc n =
725           if n=1 then [x] else
726           let val n2 = n div 2
727               val acc2 = acc n2
728           in  if n-n2=n2 then map f acc2 @ map g acc2
729                          else map f acc2 @ map g (acc (n-n2)) end
730   in  if 1<=n then acc n else raise Balance  end;
734 (** orders **)
736 datatype order = LESS | EQUAL | GREATER;
738 fun intord (i, j: int) =
739   if i < j then LESS
740   else if i = j then EQUAL
741   else GREATER;
743 fun stringord (a, b: string) =
744   if a < b then LESS
745   else if a = b then EQUAL
746   else GREATER;
750 (** input / output and diagnostics **)
752 val cd = OS.FileSys.chDir;
753 val pwd = OS.FileSys.getDir;
756 local
757   fun out s =
758     (TextIO.output (TextIO.stdOut, s); TextIO.flushOut TextIO.stdOut);
760   fun prefix_lines prfx txt =
761     txt |> split_lines |> map (fn s => prfx ^ s ^ "\n") |> implode;
762 in
764 (*hooks for output channels: normal, warning, error*)
765 val prs_fn = ref (fn s => out s);
766 val warning_fn = ref (fn s => out (prefix_lines "### " s));
767 val error_fn = ref (fn s => out (prefix_lines "*** " s));
769 end;
771 fun prs s = !prs_fn s;
772 fun writeln s = prs (s ^ "\n");
774 fun warning s = !warning_fn s;
776 (*print error message and abort to top level*)
777 exception ERROR;
778 fun error_msg s = !error_fn s;			(*promise to raise ERROR later!*)
779 fun error s = (error_msg s; raise ERROR);
780 fun sys_error msg = (error_msg " !! SYSTEM ERROR !!\n"; error msg);
782 fun assert p msg = if p then () else error msg;
783 fun deny p msg = if p then error msg else ();
785 (*Assert pred for every member of l, generating a message if pred fails*)
786 fun assert_all pred l msg_fn =
787   let fun asl [] = ()
788         | asl (x::xs) = if pred x then asl xs
789                         else error (msg_fn x)
790   in  asl l  end;
793 (* handle errors (capturing messages) *)
795 datatype 'a error =
796   Error of string |
797   OK of 'a;
799 fun handle_error f x =
800   let
801     val buffer = ref "";
802     fun capture s = buffer := ! buffer ^ s ^ "\n";
803     val result = Some (setmp error_fn capture f x) handle ERROR => None;
804   in
805     case result of
806       None => Error (! buffer)
807     | Some y => OK y
808   end;
811 (* read / write files *)
813 fun read_file name =
814   let
815     val instream  = TextIO.openIn name;
816     val intext = TextIO.inputAll instream;
817   in
818     TextIO.closeIn instream;
819     intext
820   end;
822 fun write_file name txt =
823   let val outstream = TextIO.openOut name in
824     TextIO.output (outstream, txt);
825     TextIO.closeOut outstream
826   end;
828 fun append_file name txt =
829   let val outstream = TextIO.openAppend name in
830     TextIO.output (outstream, txt);
831     TextIO.closeOut outstream
832   end;
835 (*for the "test" target in IsaMakefiles -- signifies successful termination*)
836 fun maketest msg =
837   (writeln msg; write_file "test" "Test examples ran successfully\n");
840 (*print a list surrounded by the brackets lpar and rpar, with comma separator
841   print nothing for empty list*)
842 fun print_list (lpar, rpar, pre: 'a -> unit) (l : 'a list) =
843   let fun prec x = (prs ","; pre x)
844   in
845     (case l of
846       [] => ()
847     | x::l => (prs lpar; pre x; seq prec l; prs rpar))
848   end;
850 (*print a list of items separated by newlines*)
851 fun print_list_ln (pre: 'a -> unit) : 'a list -> unit =
852   seq (fn x => (pre x; writeln ""));
855 val print_int = prs o string_of_int;
858 (* output to LaTeX / xdvi *)
859 fun latex s =
860   execute ("( cd /tmp ; echo \"" ^ s ^
861     "\" | isa2latex -s > \$\$.tex ; latex \$\$.tex ; xdvi \$\$.dvi ; rm \$\$.* ) > /dev/null &");
864 (** timing **)
866 (*unconditional timing function*)
867 fun timeit x = cond_timeit true x;
869 (*timed application function*)
870 fun timeap f x = timeit (fn () => f x);
872 (*timed "use" function, printing filenames*)
873 fun time_use fname = timeit (fn () =>
874   (writeln ("\n**** Starting " ^ fname ^ " ****"); use fname;
875    writeln ("\n**** Finished " ^ fname ^ " ****")));
877 (*use the file, but exit with error code if errors found.*)
878 fun exit_use fname = use fname handle _ => exit 1;
881 (** filenames and paths **)
883 (*Convert UNIX filename of the form "path/file" to "path/" and "file";
884   if filename contains no slash, then it returns "" and "file"*)
885 val split_filename =
886   (pairself implode) o take_suffix (not_equal "/") o explode;
888 val base_name = #2 o split_filename;
890 (*Merge splitted filename (path and file);
891   if path does not end with one a slash is appended*)
892 fun tack_on "" name = name
893   | tack_on path name =
894       if last_elem (explode path) = "/" then path ^ name
895       else path ^ "/" ^ name;
897 (*Remove the extension of a filename, i.e. the part after the last '.'*)
898 val remove_ext = implode o #1 o take_suffix (not_equal ".") o explode;
900 (*Make relative path to reach an absolute location from a different one*)
901 fun relative_path cur_path dest_path =
902   let (*Remove common beginning of both paths and make relative path*)
903       fun mk_relative [] [] = []
904         | mk_relative [] ds = ds
905         | mk_relative cs [] = map (fn _ => "..") cs
906         | mk_relative (c::cs) (d::ds) =
907             if c = d then mk_relative cs ds
908             else ".." :: map (fn _ => "..") cs @ (d::ds);
909   in if cur_path = "" orelse hd (explode cur_path) <> "/" orelse
910         dest_path = "" orelse hd (explode dest_path) <> "/" then
911        error "Relative or empty path passed to relative_path"
912      else ();
913      space_implode "/" (mk_relative (BAD_space_explode "/" cur_path)
914                                     (BAD_space_explode "/" dest_path))
915   end;
917 (*Determine if absolute path1 is a subdirectory of absolute path2*)
918 fun path1 subdir_of path2 =
919   if hd (explode path1) <> "/" orelse hd (explode path2) <> "/" then
920     error "Relative or empty path passed to subdir_of"
921   else (BAD_space_explode "/" path2) prefix (BAD_space_explode "/" path1);
923 fun absolute_path cwd file =
924   let fun rm_points [] result = rev result
925         | rm_points (".."::ds) result = rm_points ds (tl result)
926         | rm_points ("."::ds) result = rm_points ds result
927         | rm_points (d::ds) result = rm_points ds (d::result);
928   in if file = "" then ""
929      else if hd (explode file) = "/" then file
930      else "/" ^ space_implode "/"
931                   (rm_points (BAD_space_explode "/" (tack_on cwd file)) [])
932   end;
934 fun file_exists file = (file_info file <> "");
937 (** misc functions **)
939 (*use the keyfun to make a list of (x, key) pairs*)
940 fun make_keylist (keyfun: 'a->'b) : 'a list -> ('a * 'b) list =
941   let fun keypair x = (x, keyfun x)
942   in map keypair end;
944 (*given a list of (x, key) pairs and a searchkey
945   return the list of xs from each pair whose key equals searchkey*)
946 fun keyfilter [] searchkey = []
947   | keyfilter ((x, key) :: pairs) searchkey =
948       if key = searchkey then x :: keyfilter pairs searchkey
949       else keyfilter pairs searchkey;
952 (*Partition list into elements that satisfy predicate and those that don't.
953   Preserves order of elements in both lists.*)
954 fun partition (pred: 'a->bool) (ys: 'a list) : ('a list * 'a list) =
955     let fun part ([], answer) = answer
956           | part (x::xs, (ys, ns)) = if pred(x)
957             then  part (xs, (x::ys, ns))
958             else  part (xs, (ys, x::ns))
959     in  part (rev ys, ([], []))  end;
962 fun partition_eq (eq:'a * 'a -> bool) =
963     let fun part [] = []
964           | part (x::ys) = let val (xs, xs') = partition (apl(x, eq)) ys
965                            in (x::xs)::(part xs') end
966     in part end;
969 (*Partition a list into buckets  [ bi, b(i+1), ..., bj ]
970    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
971 fun partition_list p i j =
972   let fun part k xs =
973             if k>j then
974               (case xs of [] => []
975                          | _ => raise LIST "partition_list")
976             else
977             let val (ns, rest) = partition (p k) xs;
978             in  ns :: part(k+1)rest  end
979   in  part i end;
982 (* sorting *)
984 (*insertion sort; stable (does not reorder equal elements)
985   'less' is less-than test on type 'a*)
986 fun sort (less: 'a*'a -> bool) =
987   let fun insert (x, []) = [x]
988         | insert (x, y::ys) =
989               if less(y, x) then y :: insert (x, ys) else x::y::ys;
990       fun sort1 [] = []
991         | sort1 (x::xs) = insert (x, sort1 xs)
992   in  sort1  end;
994 (*sort strings*)
995 fun sort_wrt sel xs = sort (op <= o pairself (sel: 'a -> string)) xs;
996 val sort_strings = sort_wrt I;
999 (* transitive closure (not Warshall's algorithm) *)
1001 fun transitive_closure [] = []
1002   | transitive_closure ((x, ys)::ps) =
1003       let val qs = transitive_closure ps
1004           val zs = foldl (fn (zs, y) => assocs qs y union_string zs) (ys, ys)
1005           fun step(u, us) = (u, if x mem_string us then zs union_string us
1006                                 else us)
1007       in (x, zs) :: map step qs end;
1010 (* generating identifiers *)
1012 local
1013   val a = ord "a" and z = ord "z" and A = ord "A" and Z = ord "Z"
1014   and k0 = ord "0" and k9 = ord "9"
1016   val seedr = ref 0;
1017 in
1019 (*Maps 0-63 to A-Z, a-z, 0-9 or _ or ' for generating random identifiers*)
1020 fun newid n =
1021   let fun char i =
1022                if i<26 then chr (A+i)
1023           else if i<52 then chr (a+i-26)
1024           else if i<62 then chr (k0+i-52)
1025           else if i=62 then "_"
1026           else  (*i=63*)    "'"
1027   in  implode (map char (radixpand (64,n)))  end;
1029 (*Freshly generated identifiers with given prefix; MUST start with a letter*)
1030 fun gensym pre = pre ^
1031                  (#1(newid (!seedr),
1032                      seedr := 1+ !seedr))
1034 (*Increment a list of letters like a reversed base 26 number.
1035   If head is "z", bumps chars in tail.
1036   Digits are incremented as if they were integers.
1037   "_" and "'" are not changed.
1038   For making variants of identifiers.*)
1040 fun bump_int_list(c::cs) = if c="9" then "0" :: bump_int_list cs else
1041         if k0 <= ord(c) andalso ord(c) < k9 then chr(ord(c)+1) :: cs
1042         else "1" :: c :: cs
1043   | bump_int_list([]) = error("bump_int_list: not an identifier");
1045 fun bump_list([], d) = [d]
1046   | bump_list(["'"], d) = [d, "'"]
1047   | bump_list("z"::cs, _) = "a" :: bump_list(cs, "a")
1048   | bump_list("Z"::cs, _) = "A" :: bump_list(cs, "A")
1049   | bump_list("9"::cs, _) = "0" :: bump_int_list cs
1050   | bump_list(c::cs, _) = let val k = ord(c)
1051         in if (a <= k andalso k < z) orelse (A <= k andalso k < Z) orelse
1052               (k0 <= k andalso k < k9) then chr(k+1) :: cs else
1053            if c="'" orelse c="_" then c :: bump_list(cs, "") else
1054                 error("bump_list: not legal in identifier: " ^
1055                         implode(rev(c::cs)))
1056         end;
1058 end;
1060 fun bump_string s : string = implode (rev (bump_list(rev(explode s), "")));
1063 (* lexical scanning *)
1065 (*scan a list of characters into "words" composed of "letters" (recognized by
1066   is_let) and separated by any number of non-"letters"*)
1067 fun scanwords is_let cs =
1068   let fun scan1 [] = []
1069         | scan1 cs =
1070             let val (lets, rest) = take_prefix is_let cs
1071             in implode lets :: scanwords is_let rest end;
1072   in scan1 (#2 (take_prefix (not o is_let) cs)) end;
1074 end;
1076 (*Variable-branching trees: for proof terms*)
1077 datatype 'a mtree = Join of 'a * 'a mtree list;
1079 open Library;