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