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