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