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