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