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