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