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