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