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