src/Pure/library.ML
author wenzelm
Mon Nov 16 11:32:28 1998 +0100 (1998-11-16)
changeset 5893 c755dfd02509
parent 5285 2d1425492fb3
child 5904 e077a0e66563
permissions -rw-r--r--
added oo, ooo (*concatenation: 2 and 3 args*);
     1 (*  Title:      Pure/library.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Copyright   1992  University of Cambridge
     5 
     6 Basic library: functions, options, pairs, booleans, lists, integers,
     7 strings, lists as sets, association lists, generic tables, balanced
     8 trees, orders, I/O and diagnostics, timing, misc.
     9 *)
    10 
    11 infix |> ~~ \ \\ ins ins_string ins_int orf andf prefix upto downto
    12   mem mem_int mem_string union union_int union_string inter inter_int
    13   inter_string subset subset_int subset_string;
    14 
    15 infix 3 oo ooo;
    16 
    17 signature LIBRARY =
    18 sig
    19   (*functions*)
    20   val curry: ('a * 'b -> 'c) -> 'a -> 'b -> 'c
    21   val uncurry: ('a -> 'b -> 'c) -> 'a * 'b -> 'c
    22   val I: 'a -> 'a
    23   val K: 'a -> 'b -> 'a
    24   val |> : 'a * ('a -> 'b) -> 'b
    25   val apl: 'a * ('a * 'b -> 'c) -> 'b -> 'c
    26   val apr: ('a * 'b -> 'c) * 'b -> 'a -> 'c
    27   val funpow: int -> ('a -> 'a) -> 'a -> 'a
    28   val oo: ('a -> 'b) * ('c -> 'd -> 'a) -> 'c -> 'd -> 'b
    29   val ooo: ('a -> 'b) * ('c -> 'd -> 'e -> 'a) -> 'c -> 'd -> 'e -> 'b
    30 
    31   (*stamps*)
    32   type stamp
    33   val stamp: unit -> stamp
    34 
    35   (*options*)
    36   datatype 'a option = None | Some of 'a
    37   exception OPTION
    38   val the: 'a option -> 'a
    39   val if_none: 'a option -> 'a -> 'a
    40   val is_some: 'a option -> bool
    41   val is_none: 'a option -> bool
    42   val apsome: ('a -> 'b) -> 'a option -> 'b option
    43   val can: ('a -> 'b) -> 'a -> bool
    44   val try: ('a -> 'b) -> 'a -> 'b option
    45 
    46   (*pairs*)
    47   val pair: 'a -> 'b -> 'a * 'b
    48   val rpair: 'a -> 'b -> 'b * 'a
    49   val fst: 'a * 'b -> 'a
    50   val snd: 'a * 'b -> 'b
    51   val eq_fst: (''a * 'b) * (''a * 'c) -> bool
    52   val eq_snd: ('a * ''b) * ('c * ''b) -> bool
    53   val swap: 'a * 'b -> 'b * 'a
    54   val apfst: ('a -> 'b) -> 'a * 'c -> 'b * 'c
    55   val apsnd: ('a -> 'b) -> 'c * 'a -> 'c * 'b
    56   val pairself: ('a -> 'b) -> 'a * 'a -> 'b * 'b
    57 
    58   (*booleans*)
    59   val equal: ''a -> ''a -> bool
    60   val not_equal: ''a -> ''a -> bool
    61   val orf: ('a -> bool) * ('a -> bool) -> 'a -> bool
    62   val andf: ('a -> bool) * ('a -> bool) -> 'a -> bool
    63   val exists: ('a -> bool) -> 'a list -> bool
    64   val forall: ('a -> bool) -> 'a list -> bool
    65   val set: bool ref -> bool
    66   val reset: bool ref -> bool
    67   val toggle: bool ref -> bool
    68   val setmp: 'a ref -> 'a -> ('b -> 'c) -> 'b -> 'c
    69 
    70   (*lists*)
    71   exception LIST of string
    72   val null: 'a list -> bool
    73   val hd: 'a list -> 'a
    74   val tl: 'a list -> 'a list
    75   val cons: 'a -> 'a list -> 'a list
    76   val single: 'a -> 'a list
    77   val append: 'a list -> 'a list -> 'a list
    78   val foldl: ('a * 'b -> 'a) -> 'a * 'b list -> 'a
    79   val foldr: ('a * 'b -> 'b) -> 'a list * 'b -> 'b
    80   val foldr1: ('a * 'a -> 'a) -> 'a list -> 'a
    81   val foldl_map: ('a * 'b -> 'a * 'c) -> 'a * 'b list -> 'a * 'c list
    82   val length: 'a list -> int
    83   val take: int * 'a list -> 'a list
    84   val drop: int * 'a list -> 'a list
    85   val dropwhile: ('a -> bool) -> 'a list -> 'a list
    86   val nth_elem: int * 'a list -> 'a
    87   val last_elem: 'a list -> 'a
    88   val split_last: 'a list -> 'a list * 'a
    89   val nth_update: 'a -> int * 'a list -> 'a list
    90   val find_index: ('a -> bool) -> 'a list -> int
    91   val find_index_eq: ''a -> ''a list -> int
    92   val find_first: ('a -> bool) -> 'a list -> 'a option
    93   val get_first: ('a -> 'b option) -> 'a list -> 'b option
    94   val flat: 'a list list -> 'a list
    95   val seq: ('a -> unit) -> 'a list -> unit
    96   val separate: 'a -> 'a list -> 'a list
    97   val replicate: int -> 'a -> 'a list
    98   val multiply: 'a list * 'a list list -> 'a list list
    99   val filter: ('a -> bool) -> 'a list -> 'a list
   100   val filter_out: ('a -> bool) -> 'a list -> 'a list
   101   val mapfilter: ('a -> 'b option) -> 'a list -> 'b list
   102   val map2: ('a * 'b -> 'c) -> 'a list * 'b list -> 'c list
   103   val exists2: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   104   val forall2: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   105   val seq2: ('a * 'b -> unit) -> 'a list * 'b list -> unit
   106   val ~~ : 'a list * 'b list -> ('a * 'b) list
   107   val split_list: ('a * 'b) list -> 'a list * 'b list
   108   val prefix: ''a list * ''a list -> bool
   109   val take_prefix: ('a -> bool) -> 'a list -> 'a list * 'a list
   110   val take_suffix: ('a -> bool) -> 'a list -> 'a list * 'a list
   111 
   112   (*integers*)
   113   val inc: int ref -> int
   114   val dec: int ref -> int
   115   val upto: int * int -> int list
   116   val downto: int * int -> int list
   117   val downto0: int list * int -> bool
   118   val radixpand: int * int -> int list
   119   val radixstring: int * string * int -> string
   120   val string_of_int: int -> string
   121   val string_of_indexname: string * int -> string
   122 
   123   (*strings*)
   124   val enclose: string -> string -> string -> string
   125   val quote: string -> string
   126   val space_implode: string -> string list -> string
   127   val commas: string list -> string
   128   val commas_quote: string list -> string
   129   val cat_lines: string list -> string
   130   val space_explode: string -> string -> string list
   131   val split_lines: string -> string list
   132   val suffix: string -> string -> string
   133   val unsuffix: string -> string -> string
   134 
   135   (*lists as sets*)
   136   val mem: ''a * ''a list -> bool
   137   val mem_int: int * int list -> bool
   138   val mem_string: string * string list -> bool
   139   val gen_mem: ('a * 'b -> bool) -> 'a * 'b list -> bool
   140   val ins: ''a * ''a list -> ''a list
   141   val ins_int: int * int list -> int list
   142   val ins_string: string * string list -> string list
   143   val gen_ins: ('a * 'a -> bool) -> 'a * 'a list -> 'a list
   144   val union: ''a list * ''a list -> ''a list
   145   val union_int: int list * int list -> int list
   146   val union_string: string list * string list -> string list
   147   val gen_union: ('a * 'a -> bool) -> 'a list * 'a list -> 'a list
   148   val inter: ''a list * ''a list -> ''a list
   149   val inter_int: int list * int list -> int list
   150   val inter_string: string list * string list -> string list
   151   val subset: ''a list * ''a list -> bool
   152   val subset_int: int list * int list -> bool
   153   val subset_string: string list * string list -> bool
   154   val eq_set: ''a list * ''a list -> bool
   155   val eq_set_string: string list * string list -> bool
   156   val gen_subset: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   157   val \ : ''a list * ''a -> ''a list
   158   val \\ : ''a list * ''a list -> ''a list
   159   val gen_rem: ('a * 'b -> bool) -> 'a list * 'b -> 'a list
   160   val gen_rems: ('a * 'b -> bool) -> 'a list * 'b list -> 'a list
   161   val gen_distinct: ('a * 'a -> bool) -> 'a list -> 'a list
   162   val distinct: ''a list -> ''a list
   163   val findrep: ''a list -> ''a list
   164   val gen_duplicates: ('a * 'a -> bool) -> 'a list -> 'a list
   165   val duplicates: ''a list -> ''a list
   166 
   167   (*association lists*)
   168   val assoc: (''a * 'b) list * ''a -> 'b option
   169   val assoc_int: (int * 'a) list * int -> 'a option
   170   val assoc_string: (string * 'a) list * string -> 'a option
   171   val assoc_string_int: ((string * int) * 'a) list * (string * int) -> 'a option
   172   val assocs: (''a * 'b list) list -> ''a -> 'b list
   173   val assoc2: (''a * (''b * 'c) list) list * (''a * ''b) -> 'c option
   174   val gen_assoc: ('a * 'b -> bool) -> ('b * 'c) list * 'a -> 'c option
   175   val overwrite: (''a * 'b) list * (''a * 'b) -> (''a * 'b) list
   176   val gen_overwrite: ('a * 'a -> bool) -> ('a * 'b) list * ('a * 'b) -> ('a * 'b) list
   177 
   178   (*generic tables*)
   179   val generic_extend: ('a * 'a -> bool)
   180     -> ('b -> 'a list) -> ('a list -> 'b) -> 'b -> 'a list -> 'b
   181   val generic_merge: ('a * 'a -> bool) -> ('b -> 'a list) -> ('a list -> 'b) -> 'b -> 'b -> 'b
   182   val extend_list: ''a list -> ''a list -> ''a list
   183   val merge_lists: ''a list -> ''a list -> ''a list
   184   val merge_alists: (''a * 'b) list -> (''a * 'b) list -> (''a * 'b) list
   185   val merge_rev_lists: ''a list -> ''a list -> ''a list
   186 
   187   (*balanced trees*)
   188   exception Balance
   189   val fold_bal: ('a * 'a -> 'a) -> 'a list -> 'a
   190   val access_bal: ('a -> 'a) * ('a -> 'a) * 'a -> int -> int -> 'a
   191   val accesses_bal: ('a -> 'a) * ('a -> 'a) * 'a -> int -> 'a list
   192 
   193   (*orders*)
   194   datatype order = EQUAL | GREATER | LESS
   195   val rev_order: order -> order
   196   val make_ord: ('a * 'a -> bool) -> 'a * 'a -> order
   197   val int_ord: int * int -> order
   198   val string_ord: string * string -> order
   199   val prod_ord: ('a * 'b -> order) -> ('c * 'd -> order) -> ('a * 'c) * ('b * 'd) -> order
   200   val dict_ord: ('a * 'b -> order) -> 'a list * 'b list -> order
   201   val list_ord: ('a * 'b -> order) -> 'a list * 'b list -> order
   202   val sort: ('a * 'a -> order) -> 'a list -> 'a list
   203   val sort_strings: string list -> string list
   204   val sort_wrt: ('a -> string) -> 'a list -> 'a list
   205 
   206   (*I/O and diagnostics*)
   207   val cd: string -> unit
   208   val pwd: unit -> string
   209   val prs_fn: (string -> unit) ref
   210   val warning_fn: (string -> unit) ref
   211   val error_fn: (string -> unit) ref
   212   val prs: string -> unit
   213   val writeln: string -> unit
   214   val warning: string -> unit
   215   exception ERROR
   216   val error_msg: string -> unit
   217   val error: string -> 'a
   218   val sys_error: string -> 'a
   219   val assert: bool -> string -> unit
   220   val deny: bool -> string -> unit
   221   val assert_all: ('a -> bool) -> 'a list -> ('a -> string) -> unit
   222   datatype 'a error = Error of string | OK of 'a
   223   val get_error: 'a error -> string option
   224   val get_ok: 'a error -> 'a option
   225   val handle_error: ('a -> 'b) -> 'a -> 'b error
   226   exception ERROR_MESSAGE of string
   227   val transform_error: ('a -> 'b) -> 'a -> 'b
   228 
   229   (*timing*)
   230   val cond_timeit: bool -> (unit -> 'a) -> 'a
   231   val timeit: (unit -> 'a) -> 'a
   232   val timeap: ('a -> 'b) -> 'a -> 'b
   233 
   234   (*misc*)
   235   val make_keylist: ('a -> 'b) -> 'a list -> ('a * 'b) list
   236   val keyfilter: ('a * ''b) list -> ''b -> 'a list
   237   val partition: ('a -> bool) -> 'a list -> 'a list * 'a list
   238   val partition_eq: ('a * 'a -> bool) -> 'a list -> 'a list list
   239   val partition_list: (int -> 'a -> bool) -> int -> int -> 'a list -> 'a list list
   240   val transitive_closure: (string * string list) list -> (string * string list) list
   241   val init_gensym: unit -> unit
   242   val gensym: string -> string
   243   val bump_int_list: string list -> string list
   244   val bump_list: string list * string -> string list
   245   val bump_string: string -> string
   246   val scanwords: (string -> bool) -> string list -> string list
   247   datatype 'a mtree = Join of 'a * 'a mtree list
   248 end;
   249 
   250 structure Library: LIBRARY =
   251 struct
   252 
   253 
   254 (** functions **)
   255 
   256 (*handy combinators*)
   257 fun curry f x y = f (x, y);
   258 fun uncurry f (x, y) = f x y;
   259 fun I x = x;
   260 fun K x y = x;
   261 
   262 (*reverse apply*)
   263 fun (x |> f) = f x;
   264 
   265 (*application of (infix) operator to its left or right argument*)
   266 fun apl (x, f) y = f (x, y);
   267 fun apr (f, y) x = f (x, y);
   268 
   269 (*function exponentiation: f(...(f x)...) with n applications of f*)
   270 fun funpow n f x =
   271   let fun rep (0, x) = x
   272         | rep (n, x) = rep (n - 1, f x)
   273   in rep (n, x) end;
   274 
   275 (*concatenation: 2 and 3 args*)
   276 fun (f oo g) x y = f (g x y);
   277 fun (f ooo g) x y z = f (g x y z);
   278 
   279 
   280 (** stamps **)
   281 
   282 type stamp = unit ref;
   283 val stamp: unit -> stamp = ref;
   284 
   285 
   286 
   287 (** options **)
   288 
   289 datatype 'a option = None | Some of 'a;
   290 
   291 exception OPTION;
   292 
   293 fun the (Some x) = x
   294   | the None = raise OPTION;
   295 
   296 (*strict!*)
   297 fun if_none None y = y
   298   | if_none (Some x) _ = x;
   299 
   300 fun is_some (Some _) = true
   301   | is_some None = false;
   302 
   303 fun is_none (Some _) = false
   304   | is_none None = true;
   305 
   306 fun apsome f (Some x) = Some (f x)
   307   | apsome _ None = None;
   308 
   309 (*handle partial functions*)
   310 fun can f x = (f x; true) handle _ => false;
   311 fun try f x = Some (f x) handle _ => None;
   312 
   313 
   314 
   315 (** pairs **)
   316 
   317 fun pair x y = (x, y);
   318 fun rpair x y = (y, x);
   319 
   320 fun fst (x, y) = x;
   321 fun snd (x, y) = y;
   322 
   323 fun eq_fst ((x1, _), (x2, _)) = x1 = x2;
   324 fun eq_snd ((_, y1), (_, y2)) = y1 = y2;
   325 
   326 fun swap (x, y) = (y, x);
   327 
   328 (*apply function to components*)
   329 fun apfst f (x, y) = (f x, y);
   330 fun apsnd f (x, y) = (x, f y);
   331 fun pairself f (x, y) = (f x, f y);
   332 
   333 
   334 
   335 (** booleans **)
   336 
   337 (* equality *)
   338 
   339 fun equal x y = x = y;
   340 fun not_equal x y = x <> y;
   341 
   342 
   343 (* operators for combining predicates *)
   344 
   345 fun (p orf q) = fn x => p x orelse q x;
   346 fun (p andf q) = fn x => p x andalso q x;
   347 
   348 
   349 (* predicates on lists *)
   350 
   351 (*exists pred [x1, ..., xn] ===> pred x1 orelse ... orelse pred xn*)
   352 fun exists (pred: 'a -> bool) : 'a list -> bool =
   353   let fun boolf [] = false
   354         | boolf (x :: xs) = pred x orelse boolf xs
   355   in boolf end;
   356 
   357 (*forall pred [x1, ..., xn] ===> pred x1 andalso ... andalso pred xn*)
   358 fun forall (pred: 'a -> bool) : 'a list -> bool =
   359   let fun boolf [] = true
   360         | boolf (x :: xs) = pred x andalso boolf xs
   361   in boolf end;
   362 
   363 
   364 (* flags *)
   365 
   366 fun set flag = (flag := true; true);
   367 fun reset flag = (flag := false; false);
   368 fun toggle flag = (flag := not (! flag); ! flag);
   369 
   370 (*temporarily set flag, handling errors*)
   371 fun setmp flag value f x =
   372   let
   373     val orig_value = ! flag;
   374     fun return y = (flag := orig_value; y);
   375   in
   376     flag := value;
   377     return (f x handle exn => (return (); raise exn))
   378   end;
   379 
   380 
   381 
   382 (** lists **)
   383 
   384 exception LIST of string;
   385 
   386 fun null [] = true
   387   | null (_ :: _) = false;
   388 
   389 fun hd [] = raise LIST "hd"
   390   | hd (x :: _) = x;
   391 
   392 fun tl [] = raise LIST "tl"
   393   | tl (_ :: xs) = xs;
   394 
   395 fun cons x xs = x :: xs;
   396 fun single x = [x];
   397 
   398 fun append xs ys = xs @ ys;
   399 
   400 
   401 (* fold *)
   402 
   403 (*the following versions of fold are designed to fit nicely with infixes*)
   404 
   405 (*  (op @) (e, [x1, ..., xn])  ===>  ((e @ x1) @ x2) ... @ xn
   406     for operators that associate to the left (TAIL RECURSIVE)*)
   407 fun foldl (f: 'a * 'b -> 'a) : 'a * 'b list -> 'a =
   408   let fun itl (e, [])  = e
   409         | itl (e, a::l) = itl (f(e, a), l)
   410   in  itl end;
   411 
   412 (*  (op @) ([x1, ..., xn], e)  ===>   x1 @ (x2 ... @ (xn @ e))
   413     for operators that associate to the right (not tail recursive)*)
   414 fun foldr f (l, e) =
   415   let fun itr [] = e
   416         | itr (a::l) = f(a, itr l)
   417   in  itr l  end;
   418 
   419 (*  (op @) [x1, ..., xn]  ===>   x1 @ (x2 ... @ (x[n-1] @ xn))
   420     for n > 0, operators that associate to the right (not tail recursive)*)
   421 fun foldr1 f l =
   422   let fun itr [x] = x
   423         | itr (x::l) = f(x, itr l)
   424   in  itr l  end;
   425 
   426 fun foldl_map _ (x, []) = (x, [])
   427   | foldl_map f (x, y :: ys) =
   428       let
   429         val (x', y') = f (x, y);
   430         val (x'', ys') = foldl_map f (x', ys);
   431       in (x'', y' :: ys') end;
   432 
   433 
   434 (* basic list functions *)
   435 
   436 (*length of a list, should unquestionably be a standard function*)
   437 local fun length1 (n, [])  = n   (*TAIL RECURSIVE*)
   438         | length1 (n, x :: xs) = length1 (n + 1, xs)
   439 in  fun length l = length1 (0, l) end;
   440 
   441 (*take the first n elements from a list*)
   442 fun take (n, []) = []
   443   | take (n, x :: xs) =
   444       if n > 0 then x :: take (n - 1, xs) else [];
   445 
   446 (*drop the first n elements from a list*)
   447 fun drop (n, []) = []
   448   | drop (n, x :: xs) =
   449       if n > 0 then drop (n - 1, xs) else x :: xs;
   450 
   451 fun dropwhile P [] = []
   452   | dropwhile P (ys as x::xs) = if P x then dropwhile P xs else ys;
   453 
   454 (*return nth element of a list, where 0 designates the first element;
   455   raise EXCEPTION if list too short*)
   456 fun nth_elem NL =
   457   (case drop NL of
   458     [] => raise LIST "nth_elem"
   459   | x :: _ => x);
   460 
   461 (*last element of a list*)
   462 fun last_elem [] = raise LIST "last_elem"
   463   | last_elem [x] = x
   464   | last_elem (_ :: xs) = last_elem xs;
   465 
   466 (*rear decomposition*)
   467 fun split_last [] = raise LIST "split_last"
   468   | split_last [x] = ([], x)
   469   | split_last (x :: xs) = apfst (cons x) (split_last xs);
   470 
   471 (*update nth element*)
   472 fun nth_update x (n, xs) =
   473   let
   474     val prfx = take (n, xs);
   475     val sffx = drop (n, xs);
   476   in
   477     (case sffx of
   478       [] => raise LIST "nth_update"
   479     | _ :: sffx' => prfx @ (x :: sffx'))
   480   end;
   481 
   482 (*find the position of an element in a list*)
   483 fun find_index pred =
   484   let fun find _ [] = ~1
   485         | find n (x :: xs) = if pred x then n else find (n + 1) xs;
   486   in find 0 end;
   487 
   488 fun find_index_eq x = find_index (equal x);
   489 
   490 (*find first element satisfying predicate*)
   491 fun find_first _ [] = None
   492   | find_first pred (x :: xs) =
   493       if pred x then Some x else find_first pred xs;
   494 
   495 (*get first element by lookup function*)
   496 fun get_first _ [] = None
   497   | get_first f (x :: xs) =
   498       (case f x of
   499         None => get_first f xs
   500       | some => some);
   501 
   502 (*flatten a list of lists to a list*)
   503 fun flat (ls: 'c list list) : 'c list = foldr (op @) (ls, []);
   504 
   505 (*like Lisp's MAPC -- seq proc [x1, ..., xn] evaluates
   506   (proc x1; ...; proc xn) for side effects*)
   507 fun seq (proc: 'a -> unit) : 'a list -> unit =
   508   let fun seqf [] = ()
   509         | seqf (x :: xs) = (proc x; seqf xs)
   510   in seqf end;
   511 
   512 (*separate s [x1, x2, ..., xn]  ===>  [x1, s, x2, s, ..., s, xn]*)
   513 fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
   514   | separate _ xs = xs;
   515 
   516 (*make the list [x, x, ..., x] of length n*)
   517 fun replicate n (x: 'a) : 'a list =
   518   let fun rep (0, xs) = xs
   519         | rep (n, xs) = rep (n - 1, x :: xs)
   520   in
   521     if n < 0 then raise LIST "replicate"
   522     else rep (n, [])
   523   end;
   524 
   525 (*multiply [a, b, c, ...] * [xs, ys, zs, ...]*)
   526 fun multiply ([], _) = []
   527   | multiply (x :: xs, yss) = map (cons x) yss @ multiply (xs, yss);
   528 
   529 
   530 (* filter *)
   531 
   532 (*copy the list preserving elements that satisfy the predicate*)
   533 fun filter (pred: 'a->bool) : 'a list -> 'a list =
   534   let fun filt [] = []
   535         | filt (x :: xs) = if pred x then x :: filt xs else filt xs
   536   in filt end;
   537 
   538 fun filter_out f = filter (not o f);
   539 
   540 fun mapfilter (f: 'a -> 'b option) ([]: 'a list) = [] : 'b list
   541   | mapfilter f (x :: xs) =
   542       (case f x of
   543         None => mapfilter f xs
   544       | Some y => y :: mapfilter f xs);
   545 
   546 
   547 (* lists of pairs *)
   548 
   549 fun map2 _ ([], []) = []
   550   | map2 f (x :: xs, y :: ys) = (f (x, y) :: map2 f (xs, ys))
   551   | map2 _ _ = raise LIST "map2";
   552 
   553 fun exists2 _ ([], []) = false
   554   | exists2 pred (x :: xs, y :: ys) = pred (x, y) orelse exists2 pred (xs, ys)
   555   | exists2 _ _ = raise LIST "exists2";
   556 
   557 fun forall2 _ ([], []) = true
   558   | forall2 pred (x :: xs, y :: ys) = pred (x, y) andalso forall2 pred (xs, ys)
   559   | forall2 _ _ = raise LIST "forall2";
   560 
   561 fun seq2 _ ([], []) = ()
   562   | seq2 f (x :: xs, y :: ys) = (f (x, y); seq2 f (xs, ys))
   563   | seq2 _ _ = raise LIST "seq2";
   564 
   565 (*combine two lists forming a list of pairs:
   566   [x1, ..., xn] ~~ [y1, ..., yn]  ===>  [(x1, y1), ..., (xn, yn)]*)
   567 fun [] ~~ [] = []
   568   | (x :: xs) ~~ (y :: ys) = (x, y) :: (xs ~~ ys)
   569   | _ ~~ _ = raise LIST "~~";
   570 
   571 (*inverse of ~~; the old 'split':
   572   [(x1, y1), ..., (xn, yn)]  ===>  ([x1, ..., xn], [y1, ..., yn])*)
   573 fun split_list (l: ('a * 'b) list) = (map #1 l, map #2 l);
   574 
   575 
   576 (* prefixes, suffixes *)
   577 
   578 fun [] prefix _ = true
   579   | (x :: xs) prefix (y :: ys) = x = y andalso (xs prefix ys)
   580   | _ prefix _ = false;
   581 
   582 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., x(i-1)], [xi, ..., xn])
   583    where xi is the first element that does not satisfy the predicate*)
   584 fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
   585   let fun take (rxs, []) = (rev rxs, [])
   586         | take (rxs, x :: xs) =
   587             if  pred x  then  take(x :: rxs, xs)  else  (rev rxs, x :: xs)
   588   in  take([], xs)  end;
   589 
   590 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., xi], [x(i+1), ..., xn])
   591    where xi is the last element that does not satisfy the predicate*)
   592 fun take_suffix _ [] = ([], [])
   593   | take_suffix pred (x :: xs) =
   594       (case take_suffix pred xs of
   595         ([], sffx) => if pred x then ([], x :: sffx) else ([x], sffx)
   596       | (prfx, sffx) => (x :: prfx, sffx));
   597 
   598 
   599 
   600 (** integers **)
   601 
   602 fun inc i = (i := ! i + 1; ! i);
   603 fun dec i = (i := ! i - 1; ! i);
   604 
   605 
   606 (* lists of integers *)
   607 
   608 (*make the list [from, from + 1, ..., to]*)
   609 fun (from upto to) =
   610   if from > to then [] else from :: ((from + 1) upto to);
   611 
   612 (*make the list [from, from - 1, ..., to]*)
   613 fun (from downto to) =
   614   if from < to then [] else from :: ((from - 1) downto to);
   615 
   616 (*predicate: downto0 (is, n) <=> is = [n, n - 1, ..., 0]*)
   617 fun downto0 (i :: is, n) = i = n andalso downto0 (is, n - 1)
   618   | downto0 ([], n) = n = ~1;
   619 
   620 
   621 (* convert integers to strings *)
   622 
   623 (*expand the number in the given base;
   624   example: radixpand (2, 8) gives [1, 0, 0, 0]*)
   625 fun radixpand (base, num) : int list =
   626   let
   627     fun radix (n, tail) =
   628       if n < base then n :: tail
   629       else radix (n div base, (n mod base) :: tail)
   630   in radix (num, []) end;
   631 
   632 (*expands a number into a string of characters starting from "zerochar";
   633   example: radixstring (2, "0", 8) gives "1000"*)
   634 fun radixstring (base, zerochar, num) =
   635   let val offset = ord zerochar;
   636       fun chrof n = chr (offset + n)
   637   in implode (map chrof (radixpand (base, num))) end;
   638 
   639 
   640 val string_of_int = Int.toString;
   641 
   642 fun string_of_indexname (a,0) = a
   643   | string_of_indexname (a,i) = a ^ "_" ^ Int.toString i;
   644 
   645 
   646 
   647 (** strings **)
   648 
   649 (*enclose in brackets*)
   650 fun enclose lpar rpar str = lpar ^ str ^ rpar;
   651 
   652 (*simple quoting (does not escape special chars)*)
   653 val quote = enclose "\"" "\"";
   654 
   655 (*space_implode "..." (explode "hello") = "h...e...l...l...o"*)
   656 fun space_implode a bs = implode (separate a bs);
   657 
   658 val commas = space_implode ", ";
   659 val commas_quote = commas o map quote;
   660 
   661 (*concatenate messages, one per line, into a string*)
   662 val cat_lines = space_implode "\n";
   663 
   664 (*space_explode "." "h.e..l.lo" = ["h", "e", "", "l", "lo"]*)
   665 fun space_explode _ "" = []
   666   | space_explode sep str =
   667       let
   668         fun expl chs =
   669           (case take_prefix (not_equal sep) chs of
   670             (cs, []) => [implode cs]
   671           | (cs, _ :: cs') => implode cs :: expl cs');
   672       in expl (explode str) end;
   673 
   674 val split_lines = space_explode "\n";
   675 
   676 (*append suffix*)
   677 fun suffix sfx s = s ^ sfx;
   678 
   679 (*remove suffix*)
   680 fun unsuffix sfx s =
   681   let
   682     val cs = explode s;
   683     val prfx_len = size s - size sfx;
   684   in
   685     if prfx_len >= 0 andalso implode (drop (prfx_len, cs)) = sfx then
   686       implode (take (prfx_len, cs))
   687     else raise LIST "unsuffix"
   688   end;
   689 
   690 
   691 
   692 (** lists as sets **)
   693 
   694 (*membership in a list*)
   695 fun x mem [] = false
   696   | x mem (y :: ys) = x = y orelse x mem ys;
   697 
   698 (*membership in a list, optimized version for ints*)
   699 fun (x:int) mem_int [] = false
   700   | x mem_int (y :: ys) = x = y orelse x mem_int ys;
   701 
   702 (*membership in a list, optimized version for strings*)
   703 fun (x:string) mem_string [] = false
   704   | x mem_string (y :: ys) = x = y orelse x mem_string ys;
   705 
   706 (*generalized membership test*)
   707 fun gen_mem eq (x, []) = false
   708   | gen_mem eq (x, y :: ys) = eq (x, y) orelse gen_mem eq (x, ys);
   709 
   710 
   711 (*insertion into list if not already there*)
   712 fun (x ins xs) = if x mem xs then xs else x :: xs;
   713 
   714 (*insertion into list, optimized version for ints*)
   715 fun (x ins_int xs) = if x mem_int xs then xs else x :: xs;
   716 
   717 (*insertion into list, optimized version for strings*)
   718 fun (x ins_string xs) = if x mem_string xs then xs else x :: xs;
   719 
   720 (*generalized insertion*)
   721 fun gen_ins eq (x, xs) = if gen_mem eq (x, xs) then xs else x :: xs;
   722 
   723 
   724 (*union of sets represented as lists: no repetitions*)
   725 fun xs union [] = xs
   726   | [] union ys = ys
   727   | (x :: xs) union ys = xs union (x ins ys);
   728 
   729 (*union of sets, optimized version for ints*)
   730 fun (xs:int list) union_int [] = xs
   731   | [] union_int ys = ys
   732   | (x :: xs) union_int ys = xs union_int (x ins_int ys);
   733 
   734 (*union of sets, optimized version for strings*)
   735 fun (xs:string list) union_string [] = xs
   736   | [] union_string ys = ys
   737   | (x :: xs) union_string ys = xs union_string (x ins_string ys);
   738 
   739 (*generalized union*)
   740 fun gen_union eq (xs, []) = xs
   741   | gen_union eq ([], ys) = ys
   742   | gen_union eq (x :: xs, ys) = gen_union eq (xs, gen_ins eq (x, ys));
   743 
   744 
   745 (*intersection*)
   746 fun [] inter ys = []
   747   | (x :: xs) inter ys =
   748       if x mem ys then x :: (xs inter ys) else xs inter ys;
   749 
   750 (*intersection, optimized version for ints*)
   751 fun ([]:int list) inter_int ys = []
   752   | (x :: xs) inter_int ys =
   753       if x mem_int ys then x :: (xs inter_int ys) else xs inter_int ys;
   754 
   755 (*intersection, optimized version for strings *)
   756 fun ([]:string list) inter_string ys = []
   757   | (x :: xs) inter_string ys =
   758       if x mem_string ys then x :: (xs inter_string ys) else xs inter_string ys;
   759 
   760 
   761 (*subset*)
   762 fun [] subset ys = true
   763   | (x :: xs) subset ys = x mem ys andalso xs subset ys;
   764 
   765 (*subset, optimized version for ints*)
   766 fun ([]:int list) subset_int ys = true
   767   | (x :: xs) subset_int ys = x mem_int ys andalso xs subset_int ys;
   768 
   769 (*subset, optimized version for strings*)
   770 fun ([]:string list) subset_string ys = true
   771   | (x :: xs) subset_string ys = x mem_string ys andalso xs subset_string ys;
   772 
   773 (*set equality*)
   774 fun eq_set (xs, ys) =
   775   xs = ys orelse (xs subset ys andalso ys subset xs);
   776 
   777 (*set equality for strings*)
   778 fun eq_set_string ((xs:string list), ys) =
   779   xs = ys orelse (xs subset_string ys andalso ys subset_string xs);
   780 
   781 fun gen_subset eq (xs, ys) = forall (fn x => gen_mem eq (x, ys)) xs;
   782 
   783 
   784 (*removing an element from a list WITHOUT duplicates*)
   785 fun (y :: ys) \ x = if x = y then ys else y :: (ys \ x)
   786   | [] \ x = [];
   787 
   788 fun ys \\ xs = foldl (op \) (ys,xs);
   789 
   790 (*removing an element from a list -- possibly WITH duplicates*)
   791 fun gen_rem eq (xs, y) = filter_out (fn x => eq (x, y)) xs;
   792 
   793 fun gen_rems eq = foldl (gen_rem eq);
   794 
   795 
   796 (*makes a list of the distinct members of the input; preserves order, takes
   797   first of equal elements*)
   798 fun gen_distinct eq lst =
   799   let
   800     val memb = gen_mem eq;
   801 
   802     fun dist (rev_seen, []) = rev rev_seen
   803       | dist (rev_seen, x :: xs) =
   804           if memb (x, rev_seen) then dist (rev_seen, xs)
   805           else dist (x :: rev_seen, xs);
   806   in
   807     dist ([], lst)
   808   end;
   809 
   810 fun distinct l = gen_distinct (op =) l;
   811 
   812 
   813 (*returns the tail beginning with the first repeated element, or []*)
   814 fun findrep [] = []
   815   | findrep (x :: xs) = if x mem xs then x :: xs else findrep xs;
   816 
   817 
   818 (*returns a list containing all repeated elements exactly once; preserves
   819   order, takes first of equal elements*)
   820 fun gen_duplicates eq lst =
   821   let
   822     val memb = gen_mem eq;
   823 
   824     fun dups (rev_dups, []) = rev rev_dups
   825       | dups (rev_dups, x :: xs) =
   826           if memb (x, rev_dups) orelse not (memb (x, xs)) then
   827             dups (rev_dups, xs)
   828           else dups (x :: rev_dups, xs);
   829   in
   830     dups ([], lst)
   831   end;
   832 
   833 fun duplicates l = gen_duplicates (op =) l;
   834 
   835 
   836 
   837 (** association lists **)
   838 
   839 (*association list lookup*)
   840 fun assoc ([], key) = None
   841   | assoc ((keyi, xi) :: pairs, key) =
   842       if key = keyi then Some xi else assoc (pairs, key);
   843 
   844 (*association list lookup, optimized version for ints*)
   845 fun assoc_int ([], (key:int)) = None
   846   | assoc_int ((keyi, xi) :: pairs, key) =
   847       if key = keyi then Some xi else assoc_int (pairs, key);
   848 
   849 (*association list lookup, optimized version for strings*)
   850 fun assoc_string ([], (key:string)) = None
   851   | assoc_string ((keyi, xi) :: pairs, key) =
   852       if key = keyi then Some xi else assoc_string (pairs, key);
   853 
   854 (*association list lookup, optimized version for string*ints*)
   855 fun assoc_string_int ([], (key:string*int)) = None
   856   | assoc_string_int ((keyi, xi) :: pairs, key) =
   857       if key = keyi then Some xi else assoc_string_int (pairs, key);
   858 
   859 fun assocs ps x =
   860   (case assoc (ps, x) of
   861     None => []
   862   | Some ys => ys);
   863 
   864 (*two-fold association list lookup*)
   865 fun assoc2 (aal, (key1, key2)) =
   866   (case assoc (aal, key1) of
   867     Some al => assoc (al, key2)
   868   | None => None);
   869 
   870 (*generalized association list lookup*)
   871 fun gen_assoc eq ([], key) = None
   872   | gen_assoc eq ((keyi, xi) :: pairs, key) =
   873       if eq (key, keyi) then Some xi else gen_assoc eq (pairs, key);
   874 
   875 (*association list update*)
   876 fun overwrite (al, p as (key, _)) =
   877   let fun over ((q as (keyi, _)) :: pairs) =
   878             if keyi = key then p :: pairs else q :: (over pairs)
   879         | over [] = [p]
   880   in over al end;
   881 
   882 fun gen_overwrite eq (al, p as (key, _)) =
   883   let fun over ((q as (keyi, _)) :: pairs) =
   884             if eq (keyi, key) then p :: pairs else q :: (over pairs)
   885         | over [] = [p]
   886   in over al end;
   887 
   888 
   889 
   890 (** generic tables **)
   891 
   892 (*Tables are supposed to be 'efficient' encodings of lists of elements distinct
   893   wrt. an equality "eq". The extend and merge operations below are optimized
   894   for long-term space efficiency.*)
   895 
   896 (*append (new) elements to a table*)
   897 fun generic_extend _ _ _ tab [] = tab
   898   | generic_extend eq dest_tab mk_tab tab1 lst2 =
   899       let
   900         val lst1 = dest_tab tab1;
   901         val new_lst2 = gen_rems eq (lst2, lst1);
   902       in
   903         if null new_lst2 then tab1
   904         else mk_tab (lst1 @ new_lst2)
   905       end;
   906 
   907 (*append (new) elements of 2nd table to 1st table*)
   908 fun generic_merge eq dest_tab mk_tab tab1 tab2 =
   909   let
   910     val lst1 = dest_tab tab1;
   911     val lst2 = dest_tab tab2;
   912     val new_lst2 = gen_rems eq (lst2, lst1);
   913   in
   914     if null new_lst2 then tab1
   915     else if gen_subset eq (lst1, lst2) then tab2
   916     else mk_tab (lst1 @ new_lst2)
   917   end;
   918 
   919 
   920 (*lists as tables*)
   921 fun extend_list tab = generic_extend (op =) I I tab;
   922 fun merge_lists tab = generic_merge (op =) I I tab;
   923 fun merge_alists tab = generic_merge eq_fst I I tab;
   924 
   925 fun merge_rev_lists xs [] = xs
   926   | merge_rev_lists [] ys = ys
   927   | merge_rev_lists xs (y :: ys) =
   928       (if y mem xs then I else cons y) (merge_rev_lists xs ys);
   929 
   930 
   931 
   932 (** balanced trees **)
   933 
   934 exception Balance;      (*indicates non-positive argument to balancing fun*)
   935 
   936 (*balanced folding; avoids deep nesting*)
   937 fun fold_bal f [x] = x
   938   | fold_bal f [] = raise Balance
   939   | fold_bal f xs =
   940       let val k = length xs div 2
   941       in  f (fold_bal f (take(k, xs)),
   942              fold_bal f (drop(k, xs)))
   943       end;
   944 
   945 (*construct something of the form f(...g(...(x)...)) for balanced access*)
   946 fun access_bal (f, g, x) n i =
   947   let fun acc n i =     (*1<=i<=n*)
   948           if n=1 then x else
   949           let val n2 = n div 2
   950           in  if i<=n2 then f (acc n2 i)
   951                        else g (acc (n-n2) (i-n2))
   952           end
   953   in  if 1<=i andalso i<=n then acc n i else raise Balance  end;
   954 
   955 (*construct ALL such accesses; could try harder to share recursive calls!*)
   956 fun accesses_bal (f, g, x) n =
   957   let fun acc n =
   958           if n=1 then [x] else
   959           let val n2 = n div 2
   960               val acc2 = acc n2
   961           in  if n-n2=n2 then map f acc2 @ map g acc2
   962                          else map f acc2 @ map g (acc (n-n2)) end
   963   in  if 1<=n then acc n else raise Balance  end;
   964 
   965 
   966 
   967 (** orders **)
   968 
   969 datatype order = LESS | EQUAL | GREATER;
   970 
   971 fun rev_order LESS = GREATER
   972   | rev_order EQUAL = EQUAL
   973   | rev_order GREATER = LESS;
   974 
   975 (*assume rel is a linear strict order*)
   976 fun make_ord rel (x, y) =
   977   if rel (x, y) then LESS
   978   else if rel (y, x) then GREATER
   979   else EQUAL;
   980 
   981 fun int_ord (i, j: int) =
   982   if i < j then LESS
   983   else if i = j then EQUAL
   984   else GREATER;
   985 
   986 fun string_ord (a, b: string) =
   987   if a < b then LESS
   988   else if a = b then EQUAL
   989   else GREATER;
   990 
   991 (*lexicographic product*)
   992 fun prod_ord a_ord b_ord ((x, y), (x', y')) =
   993   (case a_ord (x, x') of EQUAL => b_ord (y, y') | ord => ord);
   994 
   995 (*dictionary order -- in general NOT well-founded!*)
   996 fun dict_ord _ ([], []) = EQUAL
   997   | dict_ord _ ([], _ :: _) = LESS
   998   | dict_ord _ (_ :: _, []) = GREATER
   999   | dict_ord elem_ord (x :: xs, y :: ys) =
  1000       (case elem_ord (x, y) of EQUAL => dict_ord elem_ord (xs, ys) | ord => ord);
  1001 
  1002 (*lexicographic product of lists*)
  1003 fun list_ord elem_ord (xs, ys) =
  1004   prod_ord int_ord (dict_ord elem_ord) ((length xs, xs), (length ys, ys));
  1005 
  1006 
  1007 (* sorting *)
  1008 
  1009 (*quicksort (stable, i.e. does not reorder equal elements)*)
  1010 fun sort ord =
  1011   let
  1012     fun qsort xs =
  1013       let val len = length xs in
  1014         if len <= 1 then xs
  1015         else
  1016           let val (lts, eqs, gts) = part (nth_elem (len div 2, xs)) xs in
  1017             qsort lts @ eqs @ qsort gts
  1018           end
  1019       end
  1020     and part _ [] = ([], [], [])
  1021       | part pivot (x :: xs) = add (ord (x, pivot)) x (part pivot xs)
  1022     and add LESS x (lts, eqs, gts) = (x :: lts, eqs, gts)
  1023       | add EQUAL x (lts, eqs, gts) = (lts, x :: eqs, gts)
  1024       | add GREATER x (lts, eqs, gts) = (lts, eqs, x :: gts);
  1025   in qsort end;
  1026 
  1027 (*sort strings*)
  1028 val sort_strings = sort string_ord;
  1029 fun sort_wrt sel xs = sort (string_ord o pairself sel) xs;
  1030 
  1031 
  1032 
  1033 (** input / output and diagnostics **)
  1034 
  1035 val cd = OS.FileSys.chDir;
  1036 val pwd = OS.FileSys.getDir;
  1037 
  1038 
  1039 local
  1040   fun out s =
  1041     (TextIO.output (TextIO.stdOut, s); TextIO.flushOut TextIO.stdOut);
  1042 
  1043   fun prefix_lines prfx txt =
  1044     txt |> split_lines |> map (fn s => prfx ^ s ^ "\n") |> implode;
  1045 in
  1046 
  1047 (*hooks for output channels: normal, warning, error*)
  1048 val prs_fn = ref (fn s => out s);
  1049 val warning_fn = ref (fn s => out (prefix_lines "### " s));
  1050 val error_fn = ref (fn s => out (prefix_lines "*** " s));
  1051 
  1052 end;
  1053 
  1054 fun prs s = !prs_fn s;
  1055 fun writeln s = prs (s ^ "\n");
  1056 
  1057 fun warning s = !warning_fn s;
  1058 
  1059 (*print error message and abort to top level*)
  1060 exception ERROR;
  1061 fun error_msg s = !error_fn s;
  1062 fun error s = (error_msg s; raise ERROR);
  1063 fun sys_error msg = error ("## SYSTEM ERROR ##\n" ^ msg);
  1064 
  1065 fun assert p msg = if p then () else error msg;
  1066 fun deny p msg = if p then error msg else ();
  1067 
  1068 (*Assert pred for every member of l, generating a message if pred fails*)
  1069 fun assert_all pred l msg_fn =
  1070   let fun asl [] = ()
  1071         | asl (x::xs) = if pred x then asl xs else error (msg_fn x)
  1072   in asl l end;
  1073 
  1074 
  1075 (* handle errors capturing messages *)
  1076 
  1077 datatype 'a error =
  1078   Error of string |
  1079   OK of 'a;
  1080 
  1081 fun get_error (Error msg) = Some msg
  1082   | get_error _ = None;
  1083 
  1084 fun get_ok (OK x) = Some x
  1085   | get_ok _ = None;
  1086 
  1087 datatype 'a result =
  1088   Result of 'a |
  1089   Exn of exn;
  1090 
  1091 fun handle_error f x =
  1092   let
  1093     val buffer = ref ([]: string list);
  1094     fun capture s = buffer := ! buffer @ [s];
  1095     fun err_msg () = if not (null (! buffer)) then error_msg (cat_lines (! buffer)) else ();
  1096   in
  1097     (case Result (setmp error_fn capture f x) handle exn => Exn exn of
  1098       Result y => (err_msg (); OK y)
  1099     | Exn ERROR => Error (cat_lines (! buffer))
  1100     | Exn exn => (err_msg (); raise exn))
  1101   end;
  1102 
  1103 
  1104 (* transform ERROR into ERROR_MESSAGE *)
  1105 
  1106 exception ERROR_MESSAGE of string;
  1107 
  1108 fun transform_error f x =
  1109   (case handle_error f x of
  1110     OK y => y
  1111   | Error msg => raise ERROR_MESSAGE msg);
  1112 
  1113 
  1114 
  1115 (** timing **)
  1116 
  1117 (*a conditional timing function: applies f to () and, if the flag is true,
  1118   prints its runtime*)
  1119 fun cond_timeit flag f =
  1120   if flag then
  1121     let val start = startTiming()
  1122         val result = f ()
  1123     in
  1124 	writeln (endTiming start);  result
  1125     end
  1126   else f ();
  1127 
  1128 (*unconditional timing function*)
  1129 fun timeit x = cond_timeit true x;
  1130 
  1131 (*timed application function*)
  1132 fun timeap f x = timeit (fn () => f x);
  1133 
  1134 
  1135 
  1136 (** misc **)
  1137 
  1138 (*use the keyfun to make a list of (x, key) pairs*)
  1139 fun make_keylist (keyfun: 'a->'b) : 'a list -> ('a * 'b) list =
  1140   let fun keypair x = (x, keyfun x)
  1141   in map keypair end;
  1142 
  1143 (*given a list of (x, key) pairs and a searchkey
  1144   return the list of xs from each pair whose key equals searchkey*)
  1145 fun keyfilter [] searchkey = []
  1146   | keyfilter ((x, key) :: pairs) searchkey =
  1147       if key = searchkey then x :: keyfilter pairs searchkey
  1148       else keyfilter pairs searchkey;
  1149 
  1150 
  1151 (*Partition list into elements that satisfy predicate and those that don't.
  1152   Preserves order of elements in both lists.*)
  1153 fun partition (pred: 'a->bool) (ys: 'a list) : ('a list * 'a list) =
  1154     let fun part ([], answer) = answer
  1155           | part (x::xs, (ys, ns)) = if pred(x)
  1156             then  part (xs, (x::ys, ns))
  1157             else  part (xs, (ys, x::ns))
  1158     in  part (rev ys, ([], []))  end;
  1159 
  1160 
  1161 fun partition_eq (eq:'a * 'a -> bool) =
  1162     let fun part [] = []
  1163           | part (x::ys) = let val (xs, xs') = partition (apl(x, eq)) ys
  1164                            in (x::xs)::(part xs') end
  1165     in part end;
  1166 
  1167 
  1168 (*Partition a list into buckets  [ bi, b(i+1), ..., bj ]
  1169    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
  1170 fun partition_list p i j =
  1171   let fun part k xs =
  1172             if k>j then
  1173               (case xs of [] => []
  1174                          | _ => raise LIST "partition_list")
  1175             else
  1176             let val (ns, rest) = partition (p k) xs;
  1177             in  ns :: part(k+1)rest  end
  1178   in  part i end;
  1179 
  1180 
  1181 (* transitive closure (not Warshall's algorithm) *)
  1182 
  1183 fun transitive_closure [] = []
  1184   | transitive_closure ((x, ys)::ps) =
  1185       let val qs = transitive_closure ps
  1186           val zs = foldl (fn (zs, y) => assocs qs y union_string zs) (ys, ys)
  1187           fun step(u, us) = (u, if x mem_string us then zs union_string us 
  1188                                 else us)
  1189       in (x, zs) :: map step qs end;
  1190 
  1191 
  1192 (* generating identifiers *)
  1193 
  1194 (** Freshly generated identifiers; supplied prefix MUST start with a letter **)
  1195 local
  1196 (*Maps 0-63 to A-Z, a-z, 0-9 or _ or ' for generating random identifiers*)
  1197 fun char i =      if i<26 then chr (ord "A" + i)
  1198 	     else if i<52 then chr (ord "a" + i - 26)
  1199 	     else if i<62 then chr (ord"0" + i - 52)
  1200 	     else if i=62 then "_"
  1201 	     else  (*i=63*)    "'";
  1202 
  1203 val charVec = Vector.tabulate (64, char);
  1204 
  1205 fun newid n = 
  1206   let 
  1207   in  implode (map (fn i => Vector.sub(charVec,i)) (radixpand (64,n)))  end;
  1208 
  1209 val seedr = ref 0;
  1210 
  1211 in
  1212 
  1213 fun init_gensym() = (seedr := 0);
  1214 
  1215 fun gensym pre = pre ^ (#1(newid (!seedr), inc seedr));
  1216 end;
  1217 
  1218 
  1219 local
  1220 (*Identifies those character codes legal in identifiers.
  1221   chould use Basis Library character functions if Poly/ML provided characters*)
  1222 fun idCode k = (ord "a" <= k andalso k < ord "z") orelse 
  1223                (ord "A" <= k andalso k < ord "Z") orelse
  1224                (ord "0" <= k andalso k < ord "9");
  1225 
  1226 val idCodeVec = Vector.tabulate (256, idCode);
  1227 
  1228 in
  1229 
  1230 (*Increment a list of letters like a reversed base 26 number.
  1231   If head is "z", bumps chars in tail.
  1232   Digits are incremented as if they were integers.
  1233   "_" and "'" are not changed.
  1234   For making variants of identifiers.*)
  1235 
  1236 fun bump_int_list(c::cs) = 
  1237 	if c="9" then "0" :: bump_int_list cs 
  1238 	else
  1239         if "0" <= c andalso c < "9" then chr(ord(c)+1) :: cs
  1240         else "1" :: c :: cs
  1241   | bump_int_list([]) = error("bump_int_list: not an identifier");
  1242 
  1243 fun bump_list([], d) = [d]
  1244   | bump_list(["'"], d) = [d, "'"]
  1245   | bump_list("z"::cs, _) = "a" :: bump_list(cs, "a")
  1246   | bump_list("Z"::cs, _) = "A" :: bump_list(cs, "A")
  1247   | bump_list("9"::cs, _) = "0" :: bump_int_list cs
  1248   | bump_list(c::cs, _) = 
  1249         let val k = ord(c)
  1250         in if Vector.sub(idCodeVec,k) then chr(k+1) :: cs 
  1251 	   else
  1252            if c="'" orelse c="_" then c :: bump_list(cs, "") 
  1253 	   else error("bump_list: not legal in identifier: " ^
  1254 		      implode(rev(c::cs)))
  1255         end;
  1256 
  1257 end;
  1258 
  1259 fun bump_string s : string = implode (rev (bump_list(rev(explode s), "")));
  1260 
  1261 
  1262 (* lexical scanning *)
  1263 
  1264 (*scan a list of characters into "words" composed of "letters" (recognized by
  1265   is_let) and separated by any number of non-"letters"*)
  1266 fun scanwords is_let cs =
  1267   let fun scan1 [] = []
  1268         | scan1 cs =
  1269             let val (lets, rest) = take_prefix is_let cs
  1270             in implode lets :: scanwords is_let rest end;
  1271   in scan1 (#2 (take_prefix (not o is_let) cs)) end;
  1272 
  1273 
  1274 
  1275 (* Variable-branching trees: for proof terms etc. *)
  1276 datatype 'a mtree = Join of 'a * 'a mtree list;
  1277 
  1278 
  1279 end;
  1280 
  1281 open Library;