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