src/Pure/library.ML
author haftmann
Thu Sep 30 18:37:29 2010 +0200 (2010-09-30)
changeset 39809 dac3c3106746
parent 39616 8052101883c3
child 39811 0659e84bdc5f
permissions -rw-r--r--
take_while, drop_while
     1 (*  Title:      Pure/library.ML
     2     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     3     Author:     Markus Wenzel, TU Muenchen
     4 
     5 Basic library: functions, pairs, booleans, lists, integers,
     6 strings, lists as sets, orders, current directory, misc.
     7 
     8 See also General/basics.ML for the most fundamental concepts.
     9 *)
    10 
    11 infix 2 ?
    12 infix 3 o oo ooo oooo
    13 infix 4 ~~ upto downto
    14 infix orf andf
    15 
    16 signature BASIC_LIBRARY =
    17 sig
    18   (*functions*)
    19   val undefined: 'a -> 'b
    20   val I: 'a -> 'a
    21   val K: 'a -> 'b -> 'a
    22   val curry: ('a * 'b -> 'c) -> 'a -> 'b -> 'c
    23   val uncurry: ('a -> 'b -> 'c) -> 'a * 'b -> 'c
    24   val ? : bool * ('a -> 'a) -> 'a -> 'a
    25   val oo: ('a -> 'b) * ('c -> 'd -> 'a) -> 'c -> 'd -> 'b
    26   val ooo: ('a -> 'b) * ('c -> 'd -> 'e -> 'a) -> 'c -> 'd -> 'e -> 'b
    27   val oooo: ('a -> 'b) * ('c -> 'd -> 'e -> 'f -> 'a) -> 'c -> 'd -> 'e -> 'f -> 'b
    28   val funpow: int -> ('a -> 'a) -> 'a -> 'a
    29   val funpow_yield: int -> ('a -> 'b * 'a) -> 'a -> 'b list * 'a
    30 
    31   (*errors*)
    32   exception SYS_ERROR of string
    33   val sys_error: string -> 'a
    34   exception ERROR of string
    35   val error: string -> 'a
    36   val cat_error: string -> string -> 'a
    37   val assert_all: ('a -> bool) -> 'a list -> ('a -> string) -> unit
    38 
    39   (*pairs*)
    40   val pair: 'a -> 'b -> 'a * 'b
    41   val rpair: 'a -> 'b -> 'b * 'a
    42   val fst: 'a * 'b -> 'a
    43   val snd: 'a * 'b -> 'b
    44   val eq_fst: ('a * 'c -> bool) -> ('a * 'b) * ('c * 'd) -> bool
    45   val eq_snd: ('b * 'd -> bool) -> ('a * 'b) * ('c * 'd) -> bool
    46   val eq_pair: ('a * 'c -> bool) -> ('b * 'd -> bool) -> ('a * 'b) * ('c * 'd) -> bool
    47   val swap: 'a * 'b -> 'b * 'a
    48   val apfst: ('a -> 'b) -> 'a * 'c -> 'b * 'c
    49   val apsnd: ('a -> 'b) -> 'c * 'a -> 'c * 'b
    50   val pairself: ('a -> 'b) -> 'a * 'a -> 'b * 'b
    51 
    52   (*booleans*)
    53   val equal: ''a -> ''a -> bool
    54   val not_equal: ''a -> ''a -> bool
    55   val orf: ('a -> bool) * ('a -> bool) -> 'a -> bool
    56   val andf: ('a -> bool) * ('a -> bool) -> 'a -> bool
    57   val exists: ('a -> bool) -> 'a list -> bool
    58   val forall: ('a -> bool) -> 'a list -> bool
    59   val setmp_CRITICAL: 'a Unsynchronized.ref -> 'a -> ('b -> 'c) -> 'b -> 'c
    60   val setmp_thread_data: 'a Universal.tag -> 'a -> 'a -> ('b -> 'c) -> 'b -> 'c
    61 
    62   (*lists*)
    63   exception UnequalLengths
    64   val single: 'a -> 'a list
    65   val the_single: 'a list -> 'a
    66   val singleton: ('a list -> 'b list) -> 'a -> 'b
    67   val yield_singleton: ('a list -> 'c -> 'b list * 'c) -> 'a -> 'c -> 'b * 'c
    68   val apply: ('a -> 'a) list -> 'a -> 'a
    69   val perhaps_apply: ('a -> 'a option) list -> 'a -> 'a option
    70   val perhaps_loop: ('a -> 'a option) -> 'a -> 'a option
    71   val foldl1: ('a * 'a -> 'a) -> 'a list -> 'a
    72   val foldr1: ('a * 'a -> 'a) -> 'a list -> 'a
    73   val flat: 'a list list -> 'a list
    74   val unflat: 'a list list -> 'b list -> 'b list list
    75   val burrow: ('a list -> 'b list) -> 'a list list -> 'b list list
    76   val burrow_options: ('a list -> 'b list) -> 'a option list -> 'b option list
    77   val burrow_fst: ('a list -> 'b list) -> ('a * 'c) list -> ('b * 'c) list
    78   val fold_burrow: ('a list -> 'c -> 'b list * 'd) -> 'a list list -> 'c -> 'b list list * 'd
    79   val maps: ('a -> 'b list) -> 'a list -> 'b list
    80   val filter: ('a -> bool) -> 'a list -> 'a list
    81   val filter_out: ('a -> bool) -> 'a list -> 'a list
    82   val map_filter: ('a -> 'b option) -> 'a list -> 'b list
    83   val take: int -> 'a list -> 'a list
    84   val drop: int -> 'a list -> 'a list
    85   val chop: int -> 'a list -> 'a list * 'a list
    86   val take_while: ('a -> bool) -> 'a list -> 'a list
    87   val drop_while: ('a -> bool) -> 'a list -> 'a list
    88   val nth: 'a list -> int -> 'a
    89   val nth_map: int -> ('a -> 'a) -> 'a list -> 'a list
    90   val nth_drop: int -> 'a list -> 'a list
    91   val nth_list: 'a list list -> int -> 'a list
    92   val map_index: (int * 'a -> 'b) -> 'a list -> 'b list
    93   val fold_index: (int * 'a -> 'b -> 'b) -> 'a list -> 'b -> 'b
    94   val map_range: (int -> 'a) -> int -> 'a list
    95   val split_last: 'a list -> 'a list * 'a
    96   val find_index: ('a -> bool) -> 'a list -> int
    97   val find_first: ('a -> bool) -> 'a list -> 'a option
    98   val get_index: ('a -> 'b option) -> 'a list -> (int * 'b) option
    99   val get_first: ('a -> 'b option) -> 'a list -> 'b option
   100   val eq_list: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   101   val map2: ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
   102   val fold2: ('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> 'c -> 'c
   103   val zip_options: 'a list -> 'b option list -> ('a * 'b) list
   104   val ~~ : 'a list * 'b list -> ('a * 'b) list
   105   val map_split: ('a -> 'b * 'c) -> 'a list -> 'b list * 'c list
   106   val split_list: ('a * 'b) list -> 'a list * 'b list
   107   val map_product: ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
   108   val fold_product: ('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> 'c -> 'c
   109   val map_transpose: ('a list -> 'b) -> 'a list list -> 'b list
   110   val separate: 'a -> 'a list -> 'a list
   111   val surround: 'a -> 'a list -> 'a list
   112   val replicate: int -> 'a -> 'a list
   113   val is_prefix: ('a * 'a -> bool) -> 'a list -> 'a list -> bool
   114   val take_prefix: ('a -> bool) -> 'a list -> 'a list * 'a list
   115   val chop_prefix: ('a * 'b -> bool) -> 'a list * 'b list -> 'a list * ('a list * 'b list)
   116   val take_suffix: ('a -> bool) -> 'a list -> 'a list * 'a list
   117   val prefixes1: 'a list -> 'a list list
   118   val prefixes: 'a list -> 'a list list
   119   val suffixes1: 'a list -> 'a list list
   120   val suffixes: 'a list -> 'a list list
   121 
   122   (*integers*)
   123   val upto: int * int -> int list
   124   val downto: int * int -> int list
   125   val radixpand: int * int -> int list
   126   val radixstring: int * string * int -> string
   127   val string_of_int: int -> string
   128   val signed_string_of_int: int -> string
   129   val string_of_indexname: string * int -> string
   130   val read_radix_int: int -> string list -> int * string list
   131   val read_int: string list -> int * string list
   132   val oct_char: string -> string
   133 
   134   (*strings*)
   135   val nth_string: string -> int -> string
   136   val fold_string: (string -> 'a -> 'a) -> string -> 'a -> 'a
   137   val exists_string: (string -> bool) -> string -> bool
   138   val forall_string: (string -> bool) -> string -> bool
   139   val first_field: string -> string -> (string * string) option
   140   val enclose: string -> string -> string -> string
   141   val unenclose: string -> string
   142   val quote: string -> string
   143   val space_implode: string -> string list -> string
   144   val commas: string list -> string
   145   val commas_quote: string list -> string
   146   val cat_lines: string list -> string
   147   val space_explode: string -> string -> string list
   148   val split_lines: string -> string list
   149   val prefix_lines: string -> string -> string
   150   val prefix: string -> string -> string
   151   val suffix: string -> string -> string
   152   val unprefix: string -> string -> string
   153   val unsuffix: string -> string -> string
   154   val replicate_string: int -> string -> string
   155   val translate_string: (string -> string) -> string -> string
   156   val match_string: string -> string -> bool
   157 
   158   (*lists as sets -- see also Pure/General/ord_list.ML*)
   159   val member: ('b * 'a -> bool) -> 'a list -> 'b -> bool
   160   val insert: ('a * 'a -> bool) -> 'a -> 'a list -> 'a list
   161   val remove: ('b * 'a -> bool) -> 'b -> 'a list -> 'a list
   162   val update: ('a * 'a -> bool) -> 'a -> 'a list -> 'a list
   163   val union: ('a * 'a -> bool) -> 'a list -> 'a list -> 'a list
   164   val subtract: ('b * 'a -> bool) -> 'b list -> 'a list -> 'a list
   165   val inter: ('a * 'b -> bool) -> 'b list -> 'a list -> 'a list
   166   val merge: ('a * 'a -> bool) -> 'a list * 'a list -> 'a list
   167   val subset: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   168   val eq_set: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   169   val distinct: ('a * 'a -> bool) -> 'a list -> 'a list
   170   val duplicates: ('a * 'a -> bool) -> 'a list -> 'a list
   171   val has_duplicates: ('a * 'a -> bool) -> 'a list -> bool
   172 
   173   (*lists as multisets*)
   174   val remove1: ('b * 'a -> bool) -> 'b -> 'a list -> 'a list
   175   val combine: ('a * 'a -> bool) -> 'a list -> 'a list -> 'a list
   176   val submultiset: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   177 
   178   (*orders*)
   179   val is_equal: order -> bool
   180   val rev_order: order -> order
   181   val make_ord: ('a * 'a -> bool) -> 'a * 'a -> order
   182   val bool_ord: bool * bool -> order
   183   val int_ord: int * int -> order
   184   val string_ord: string * string -> order
   185   val fast_string_ord: string * string -> order
   186   val option_ord: ('a * 'b -> order) -> 'a option * 'b option -> order
   187   val prod_ord: ('a * 'b -> order) -> ('c * 'd -> order) -> ('a * 'c) * ('b * 'd) -> order
   188   val dict_ord: ('a * 'b -> order) -> 'a list * 'b list -> order
   189   val list_ord: ('a * 'b -> order) -> 'a list * 'b list -> order
   190   val sort: ('a * 'a -> order) -> 'a list -> 'a list
   191   val sort_distinct: ('a * 'a -> order) -> 'a list -> 'a list
   192   val sort_strings: string list -> string list
   193   val sort_wrt: ('a -> string) -> 'a list -> 'a list
   194   val tag_list: int -> 'a list -> (int * 'a) list
   195   val untag_list: (int * 'a) list -> 'a list
   196   val order_list: (int * 'a) list -> 'a list
   197 
   198   (*random numbers*)
   199   exception RANDOM
   200   val random: unit -> real
   201   val random_range: int -> int -> int
   202   val one_of: 'a list -> 'a
   203   val frequency: (int * 'a) list -> 'a
   204 
   205   (*misc*)
   206   val divide_and_conquer: ('a -> 'a list * ('b list -> 'b)) -> 'a -> 'b
   207   val divide_and_conquer': ('a -> 'b -> ('a list * ('c list * 'b -> 'c * 'b)) * 'b) ->
   208     'a -> 'b -> 'c * 'b
   209   val partition_eq: ('a * 'a -> bool) -> 'a list -> 'a list list
   210   val partition_list: (int -> 'a -> bool) -> int -> int -> 'a list -> 'a list list
   211   val gensym: string -> string
   212   type stamp
   213   val stamp: unit -> stamp
   214   type serial
   215   val serial: unit -> serial
   216   val serial_string: unit -> string
   217   structure Object: sig type T end
   218 end;
   219 
   220 signature LIBRARY =
   221 sig
   222   include BASIC_LIBRARY
   223   val foldl: ('a * 'b -> 'a) -> 'a * 'b list -> 'a
   224   val foldr: ('a * 'b -> 'b) -> 'a list * 'b -> 'b
   225   val foldl_map: ('a * 'b -> 'a * 'c) -> 'a * 'b list -> 'a * 'c list
   226   val last_elem: 'a list -> 'a
   227 end;
   228 
   229 structure Library: LIBRARY =
   230 struct
   231 
   232 (* functions *)
   233 
   234 fun undefined _ = raise Match;
   235 
   236 fun I x = x;
   237 fun K x = fn _ => x;
   238 fun curry f x y = f (x, y);
   239 fun uncurry f (x, y) = f x y;
   240 
   241 (*conditional application*)
   242 fun b ? f = fn x => if b then f x else x;
   243 
   244 (*composition with multiple args*)
   245 fun (f oo g) x y = f (g x y);
   246 fun (f ooo g) x y z = f (g x y z);
   247 fun (f oooo g) x y z w = f (g x y z w);
   248 
   249 (*function exponentiation: f (... (f x) ...) with n applications of f*)
   250 fun funpow (0 : int) _ = I
   251   | funpow n f = f #> funpow (n - 1) f;
   252 
   253 fun funpow_yield (0 : int) _ x = ([], x)
   254   | funpow_yield n f x = x |> f ||>> funpow_yield (n - 1) f |>> op ::;
   255 
   256 (* errors *)
   257 
   258 exception SYS_ERROR of string;
   259 fun sys_error msg = raise SYS_ERROR msg;
   260 
   261 exception ERROR of string;
   262 fun error msg = raise ERROR msg;
   263 
   264 fun cat_error "" msg = error msg
   265   | cat_error msg1 msg2 = error (msg1 ^ "\n" ^ msg2);
   266 
   267 fun assert_all pred list msg =
   268   let
   269     fun ass [] = ()
   270       | ass (x :: xs) = if pred x then ass xs else error (msg x);
   271   in ass list end;
   272 
   273 
   274 (* pairs *)
   275 
   276 fun pair x y = (x, y);
   277 fun rpair x y = (y, x);
   278 
   279 fun fst (x, y) = x;
   280 fun snd (x, y) = y;
   281 
   282 fun eq_fst eq ((x1, _), (x2, _)) = eq (x1, x2);
   283 fun eq_snd eq ((_, y1), (_, y2)) = eq (y1, y2);
   284 fun eq_pair eqx eqy ((x1, y1), (x2, y2)) = eqx (x1, x2) andalso eqy (y1, y2);
   285 
   286 fun swap (x, y) = (y, x);
   287 
   288 fun apfst f (x, y) = (f x, y);
   289 fun apsnd f (x, y) = (x, f y);
   290 fun pairself f (x, y) = (f x, f y);
   291 
   292 
   293 (* booleans *)
   294 
   295 (*polymorphic equality*)
   296 fun equal x y = x = y;
   297 fun not_equal x y = x <> y;
   298 
   299 (*combining predicates*)
   300 fun p orf q = fn x => p x orelse q x;
   301 fun p andf q = fn x => p x andalso q x;
   302 
   303 val exists = List.exists;
   304 val forall = List.all;
   305 
   306 
   307 (* flags *)
   308 
   309 fun setmp_CRITICAL flag value f x =
   310   NAMED_CRITICAL "setmp" (fn () => Unsynchronized.setmp flag value f x);
   311 
   312 fun setmp_thread_data tag orig_data data f x =
   313   uninterruptible (fn restore_attributes => fn () =>
   314     let
   315       val _ = Thread.setLocal (tag, data);
   316       val result = Exn.capture (restore_attributes f) x;
   317       val _ = Thread.setLocal (tag, orig_data);
   318     in Exn.release result end) ();
   319 
   320 
   321 
   322 (** lists **)
   323 
   324 exception UnequalLengths;
   325 
   326 fun single x = [x];
   327 
   328 fun the_single [x] = x
   329   | the_single _ = raise Empty;
   330 
   331 fun singleton f x = the_single (f [x]);
   332 
   333 fun yield_singleton f x = f [x] #>> the_single;
   334 
   335 fun apply [] x = x
   336   | apply (f :: fs) x = apply fs (f x);
   337 
   338 fun perhaps_apply funs arg =
   339   let
   340     fun app [] res = res
   341       | app (f :: fs) (changed, x) =
   342           (case f x of
   343             NONE => app fs (changed, x)
   344           | SOME x' => app fs (true, x'));
   345   in (case app funs (false, arg) of (false, _) => NONE | (true, arg') => SOME arg') end;
   346 
   347 fun perhaps_loop f arg =
   348   let
   349     fun loop (changed, x) =
   350       (case f x of
   351         NONE => (changed, x)
   352       | SOME x' => loop (true, x'));
   353   in (case loop (false, arg) of (false, _) => NONE | (true, arg') => SOME arg') end;
   354 
   355 
   356 (* fold -- old versions *)
   357 
   358 (*the following versions of fold are designed to fit nicely with infixes*)
   359 
   360 (*  (op @) (e, [x1, ..., xn])  ===>  ((e @ x1) @ x2) ... @ xn
   361     for operators that associate to the left (TAIL RECURSIVE)*)
   362 fun foldl (f: 'a * 'b -> 'a) : 'a * 'b list -> 'a =
   363   let fun itl (e, [])  = e
   364         | itl (e, a::l) = itl (f(e, a), l)
   365   in  itl end;
   366 
   367 (*  (op @) ([x1, ..., xn], e)  ===>   x1 @ (x2 ... @ (xn @ e))
   368     for operators that associate to the right (not tail recursive)*)
   369 fun foldr f (l, e) =
   370   let fun itr [] = e
   371         | itr (a::l) = f(a, itr l)
   372   in  itr l  end;
   373 
   374 (*  (op @) [x1, ..., xn]  ===>  ((x1 @ x2) @ x3) ... @ xn
   375     for operators that associate to the left (TAIL RECURSIVE)*)
   376 fun foldl1 f [] = raise Empty
   377   | foldl1 f (x :: xs) = foldl f (x, xs);
   378 
   379 (*  (op @) [x1, ..., xn]  ===>   x1 @ (x2 ... @ (x[n-1] @ xn))
   380     for n > 0, operators that associate to the right (not tail recursive)*)
   381 fun foldr1 f [] = raise Empty
   382   | foldr1 f l =
   383       let fun itr [x] = x
   384             | itr (x::l) = f(x, itr l)
   385       in  itr l  end;
   386 
   387 fun foldl_map f =
   388   let
   389     fun fold_aux (x, []) = (x, [])
   390       | fold_aux (x, y :: ys) =
   391           let
   392             val (x', y') = f (x, y);
   393             val (x'', ys') = fold_aux (x', ys);
   394           in (x'', y' :: ys') end;
   395   in fold_aux end;
   396 
   397 
   398 (* basic list functions *)
   399 
   400 fun eq_list eq (list1, list2) =
   401   let
   402     fun eq_lst (x :: xs, y :: ys) = eq (x, y) andalso eq_lst (xs, ys)
   403       | eq_lst _ = true;
   404   in length list1 = length list2 andalso eq_lst (list1, list2) end;
   405 
   406 fun maps f [] = []
   407   | maps f (x :: xs) = f x @ maps f xs;
   408 
   409 val filter = List.filter;
   410 fun filter_out f = filter (not o f);
   411 val map_filter = List.mapPartial;
   412 
   413 fun take (0: int) xs = []
   414   | take _ [] = []
   415   | take n (x :: xs) = x :: take (n - 1) xs;
   416 
   417 fun drop (0: int) xs = xs
   418   | drop _ [] = []
   419   | drop n (x :: xs) = drop (n - 1) xs;
   420 
   421 fun chop (0: int) xs = ([], xs)
   422   | chop _ [] = ([], [])
   423   | chop n (x :: xs) = chop (n - 1) xs |>> cons x;
   424 
   425 fun drop_while P [] = []
   426   | drop_while P (ys as x :: xs) = if P x then drop_while P xs else ys;
   427 
   428 fun take_while P [] = []
   429   | take_while P (x :: xs) = if P x then x :: take_while P xs else [];
   430 
   431 (*return nth element of a list, where 0 designates the first element;
   432   raise Subscript if list too short*)
   433 fun nth xs i = List.nth (xs, i);
   434 
   435 fun nth_list xss i = nth xss i handle Subscript => [];
   436 
   437 fun nth_map 0 f (x :: xs) = f x :: xs
   438   | nth_map n f (x :: xs) = x :: nth_map (n - 1) f xs
   439   | nth_map (_: int) _ [] = raise Subscript;
   440 
   441 fun nth_drop n xs =
   442   List.take (xs, n) @ List.drop (xs, n + 1);
   443 
   444 fun map_index f =
   445   let
   446     fun mapp (_: int) [] = []
   447       | mapp i (x :: xs) = f (i, x) :: mapp (i + 1) xs
   448   in mapp 0 end;
   449 
   450 fun fold_index f =
   451   let
   452     fun fold_aux (_: int) [] y = y
   453       | fold_aux i (x :: xs) y = fold_aux (i + 1) xs (f (i, x) y);
   454   in fold_aux 0 end;
   455 
   456 fun map_range f i =
   457   let
   458     fun mapp (k: int) =
   459       if k < i then f k :: mapp (k + 1) else [];
   460   in mapp 0 end;
   461 
   462 val last_elem = List.last;
   463 
   464 (*rear decomposition*)
   465 fun split_last [] = raise Empty
   466   | split_last [x] = ([], x)
   467   | split_last (x :: xs) = apfst (cons x) (split_last xs);
   468 
   469 (*find position of first element satisfying a predicate*)
   470 fun find_index pred =
   471   let fun find (_: int) [] = ~1
   472         | find n (x :: xs) = if pred x then n else find (n + 1) xs;
   473   in find 0 end;
   474 
   475 (*find first element satisfying predicate*)
   476 val find_first = List.find;
   477 
   478 (*get first element by lookup function*)
   479 fun get_first _ [] = NONE
   480   | get_first f (x :: xs) =
   481       (case f x of
   482         NONE => get_first f xs
   483       | some => some);
   484 
   485 fun get_index f =
   486   let
   487     fun get (_: int) [] = NONE
   488       | get i (x :: xs) =
   489           case f x
   490            of NONE => get (i + 1) xs
   491             | SOME y => SOME (i, y)
   492   in get 0 end;
   493 
   494 val flat = List.concat;
   495 
   496 fun unflat (xs :: xss) ys =
   497       let val (ps, qs) = chop (length xs) ys
   498       in ps :: unflat xss qs end
   499   | unflat [] [] = []
   500   | unflat _ _ = raise UnequalLengths;
   501 
   502 fun burrow f xss = unflat xss (f (flat xss));
   503 
   504 fun burrow_options f os = map (try hd) (burrow f (map the_list os));
   505 
   506 fun fold_burrow f xss s =
   507   apfst (unflat xss) (f (flat xss) s);
   508 
   509 (*separate s [x1, x2, ..., xn]  ===>  [x1, s, x2, s, ..., s, xn]*)
   510 fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
   511   | separate _ xs = xs;
   512 
   513 fun surround s (x :: xs) = s :: x :: surround s xs
   514   | surround s [] = [s];
   515 
   516 (*make the list [x, x, ..., x] of length n*)
   517 fun replicate (n: int) x =
   518   let fun rep (0, xs) = xs
   519         | rep (n, xs) = rep (n - 1, x :: xs)
   520   in
   521     if n < 0 then raise Subscript
   522     else rep (n, [])
   523   end;
   524 
   525 
   526 (* direct product *)
   527 
   528 fun map_product f _ [] = []
   529   | map_product f [] _ = []
   530   | map_product f (x :: xs) ys = map (f x) ys @ map_product f xs ys;
   531 
   532 fun fold_product f _ [] z = z
   533   | fold_product f [] _ z = z
   534   | fold_product f (x :: xs) ys z = z |> fold (f x) ys |> fold_product f xs ys;
   535 
   536 
   537 (* lists of pairs *)
   538 
   539 exception UnequalLengths;
   540 
   541 fun map2 _ [] [] = []
   542   | map2 f (x :: xs) (y :: ys) = f x y :: map2 f xs ys
   543   | map2 _ _ _ = raise UnequalLengths;
   544 
   545 fun fold2 f [] [] z = z
   546   | fold2 f (x :: xs) (y :: ys) z = fold2 f xs ys (f x y z)
   547   | fold2 f _ _ _ = raise UnequalLengths;
   548 
   549 fun map_split f [] = ([], [])
   550   | map_split f (x :: xs) =
   551       let
   552         val (y, w) = f x;
   553         val (ys, ws) = map_split f xs;
   554       in (y :: ys, w :: ws) end;
   555 
   556 fun zip_options (x :: xs) (SOME y :: ys) = (x, y) :: zip_options xs ys
   557   | zip_options (_ :: xs) (NONE :: ys) = zip_options xs ys
   558   | zip_options _ [] = []
   559   | zip_options [] _ = raise UnequalLengths;
   560 
   561 (*combine two lists forming a list of pairs:
   562   [x1, ..., xn] ~~ [y1, ..., yn]  ===>  [(x1, y1), ..., (xn, yn)]*)
   563 fun [] ~~ [] = []
   564   | (x :: xs) ~~ (y :: ys) = (x, y) :: (xs ~~ ys)
   565   | _ ~~ _ = raise UnequalLengths;
   566 
   567 (*inverse of ~~; the old 'split':
   568   [(x1, y1), ..., (xn, yn)]  ===>  ([x1, ..., xn], [y1, ..., yn])*)
   569 val split_list = ListPair.unzip;
   570 
   571 fun burrow_fst f xs = split_list xs |>> f |> op ~~;
   572 
   573 
   574 (* prefixes, suffixes *)
   575 
   576 fun is_prefix _ [] _ = true
   577   | is_prefix eq (x :: xs) (y :: ys) = eq (x, y) andalso is_prefix eq xs ys
   578   | is_prefix eq _ _ = false;
   579 
   580 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., x(i-1)], [xi, ..., xn])
   581    where xi is the first element that does not satisfy the predicate*)
   582 fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
   583   let fun take (rxs, []) = (rev rxs, [])
   584         | take (rxs, x :: xs) =
   585             if  pred x  then  take(x :: rxs, xs)  else  (rev rxs, x :: xs)
   586   in  take([], xs)  end;
   587 
   588 fun chop_prefix eq ([], ys) = ([], ([], ys))
   589   | chop_prefix eq (xs, []) = ([], (xs, []))
   590   | chop_prefix eq (xs as x :: xs', ys as y :: ys') =
   591       if eq (x, y) then
   592         let val (ps', xys'') = chop_prefix eq (xs', ys')
   593         in (x :: ps', xys'') end
   594       else ([], (xs, ys));
   595 
   596 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., xi], [x(i+1), ..., xn])
   597    where xi is the last element that does not satisfy the predicate*)
   598 fun take_suffix _ [] = ([], [])
   599   | take_suffix pred (x :: xs) =
   600       (case take_suffix pred xs of
   601         ([], sffx) => if pred x then ([], x :: sffx) else ([x], sffx)
   602       | (prfx, sffx) => (x :: prfx, sffx));
   603 
   604 fun prefixes1 [] = []
   605   | prefixes1 (x :: xs) = map (cons x) ([] :: prefixes1 xs);
   606 
   607 fun prefixes xs = [] :: prefixes1 xs;
   608 
   609 fun suffixes1 xs = map rev (prefixes1 (rev xs));
   610 fun suffixes xs = [] :: suffixes1 xs;
   611 
   612 
   613 
   614 (** integers **)
   615 
   616 (* lists of integers *)
   617 
   618 (*make the list [from, from + 1, ..., to]*)
   619 fun ((i: int) upto j) =
   620   if i > j then [] else i :: (i + 1 upto j);
   621 
   622 (*make the list [from, from - 1, ..., to]*)
   623 fun ((i: int) downto j) =
   624   if i < j then [] else i :: (i - 1 downto j);
   625 
   626 
   627 (* convert integers to strings *)
   628 
   629 (*expand the number in the given base;
   630   example: radixpand (2, 8) gives [1, 0, 0, 0]*)
   631 fun radixpand (base, num) : int list =
   632   let
   633     fun radix (n, tail) =
   634       if n < base then n :: tail
   635       else radix (n div base, (n mod base) :: tail)
   636   in radix (num, []) end;
   637 
   638 (*expands a number into a string of characters starting from "zerochar";
   639   example: radixstring (2, "0", 8) gives "1000"*)
   640 fun radixstring (base, zerochar, num) =
   641   let val offset = ord zerochar;
   642       fun chrof n = chr (offset + n)
   643   in implode (map chrof (radixpand (base, num))) end;
   644 
   645 
   646 val string_of_int = Int.toString;
   647 
   648 fun signed_string_of_int i =
   649   if i < 0 then "-" ^ string_of_int (~ i) else string_of_int i;
   650 
   651 fun string_of_indexname (a, 0) = a
   652   | string_of_indexname (a, i) = a ^ "_" ^ string_of_int i;
   653 
   654 
   655 (* read integers *)
   656 
   657 fun read_radix_int radix cs =
   658   let
   659     val zero = ord "0";
   660     val limit = zero + radix;
   661     fun scan (num, []) = (num, [])
   662       | scan (num, c :: cs) =
   663         if zero <= ord c andalso ord c < limit then
   664           scan (radix * num + (ord c - zero), cs)
   665         else (num, c :: cs);
   666   in scan (0, cs) end;
   667 
   668 val read_int = read_radix_int 10;
   669 
   670 fun oct_char s = chr (#1 (read_radix_int 8 (explode s)));
   671 
   672 
   673 
   674 (** strings **)
   675 
   676 (* functions tuned for strings, avoiding explode *)
   677 
   678 fun nth_string str i =
   679   (case try String.substring (str, i, 1) of
   680     SOME s => s
   681   | NONE => raise Subscript);
   682 
   683 fun fold_string f str x0 =
   684   let
   685     val n = size str;
   686     fun iter (x, i) =
   687       if i < n then iter (f (String.substring (str, i, 1)) x, i + 1) else x;
   688   in iter (x0, 0) end;
   689 
   690 fun exists_string pred str =
   691   let
   692     val n = size str;
   693     fun ex i = i < n andalso (pred (String.substring (str, i, 1)) orelse ex (i + 1));
   694   in ex 0 end;
   695 
   696 fun forall_string pred = not o exists_string (not o pred);
   697 
   698 fun first_field sep str =
   699   let
   700     val n = size sep;
   701     val len = size str;
   702     fun find i =
   703       if i + n > len then NONE
   704       else if String.substring (str, i, n) = sep then SOME i
   705       else find (i + 1);
   706   in
   707     (case find 0 of
   708       NONE => NONE
   709     | SOME i => SOME (String.substring (str, 0, i), String.extract (str, i + n, NONE)))
   710   end;
   711 
   712 (*enclose in brackets*)
   713 fun enclose lpar rpar str = lpar ^ str ^ rpar;
   714 fun unenclose str = String.substring (str, 1, size str - 2);
   715 
   716 (*simple quoting (does not escape special chars)*)
   717 val quote = enclose "\"" "\"";
   718 
   719 (*space_implode "..." (explode "hello") = "h...e...l...l...o"*)
   720 fun space_implode a bs = implode (separate a bs);
   721 
   722 val commas = space_implode ", ";
   723 val commas_quote = commas o map quote;
   724 
   725 (*concatenate messages, one per line, into a string*)
   726 val cat_lines = space_implode "\n";
   727 
   728 (*space_explode "." "h.e..l.lo" = ["h", "e", "", "l", "lo"]*)
   729 fun space_explode _ "" = []
   730   | space_explode sep s = String.fields (fn c => str c = sep) s;
   731 
   732 val split_lines = space_explode "\n";
   733 
   734 fun prefix_lines "" txt = txt
   735   | prefix_lines prfx txt = txt |> split_lines |> map (fn s => prfx ^ s) |> cat_lines;
   736 
   737 fun prefix prfx s = prfx ^ s;
   738 fun suffix sffx s = s ^ sffx;
   739 
   740 fun unprefix prfx s =
   741   if String.isPrefix prfx s then String.substring (s, size prfx, size s - size prfx)
   742   else raise Fail "unprefix";
   743 
   744 fun unsuffix sffx s =
   745   if String.isSuffix sffx s then String.substring (s, 0, size s - size sffx)
   746   else raise Fail "unsuffix";
   747 
   748 fun replicate_string (0: int) _ = ""
   749   | replicate_string 1 a = a
   750   | replicate_string k a =
   751       if k mod 2 = 0 then replicate_string (k div 2) (a ^ a)
   752       else replicate_string (k div 2) (a ^ a) ^ a;
   753 
   754 fun translate_string f = String.translate (f o String.str);
   755 
   756 (*crude matching of str against simple glob pat*)
   757 fun match_string pat str =
   758   let
   759     fun match [] _ = true
   760       | match (p :: ps) s =
   761           size p <= size s andalso
   762             (case try (unprefix p) s of
   763               SOME s' => match ps s'
   764             | NONE => match (p :: ps) (String.substring (s, 1, size s - 1)));
   765   in match (space_explode "*" pat) str end;
   766 
   767 
   768 
   769 (** lists as sets -- see also Pure/General/ord_list.ML **)
   770 
   771 (* canonical operations *)
   772 
   773 fun member eq list x =
   774   let
   775     fun memb [] = false
   776       | memb (y :: ys) = eq (x, y) orelse memb ys;
   777   in memb list end;
   778 
   779 fun insert eq x xs = if member eq xs x then xs else x :: xs;
   780 fun remove eq x xs = if member eq xs x then filter_out (fn y => eq (x, y)) xs else xs;
   781 fun update eq x xs = cons x (remove eq x xs);
   782 
   783 fun inter eq xs = filter (member eq xs);
   784 
   785 fun union eq = fold (insert eq);
   786 fun subtract eq = fold (remove eq);
   787 
   788 fun merge eq (xs, ys) =
   789   if pointer_eq (xs, ys) then xs
   790   else if null xs then ys
   791   else fold_rev (insert eq) ys xs;
   792 
   793 
   794 (* subset and set equality *)
   795 
   796 fun subset eq (xs, ys) = forall (member eq ys) xs;
   797 
   798 fun eq_set eq (xs, ys) =
   799   eq_list eq (xs, ys) orelse
   800     (subset eq (xs, ys) andalso subset (eq o swap) (ys, xs));
   801 
   802 
   803 (*makes a list of the distinct members of the input; preserves order, takes
   804   first of equal elements*)
   805 fun distinct eq lst =
   806   let
   807     fun dist (rev_seen, []) = rev rev_seen
   808       | dist (rev_seen, x :: xs) =
   809           if member eq rev_seen x then dist (rev_seen, xs)
   810           else dist (x :: rev_seen, xs);
   811   in dist ([], lst) end;
   812 
   813 (*returns a list containing all repeated elements exactly once; preserves
   814   order, takes first of equal elements*)
   815 fun duplicates eq lst =
   816   let
   817     fun dups (rev_dups, []) = rev rev_dups
   818       | dups (rev_dups, x :: xs) =
   819           if member eq rev_dups x orelse not (member eq xs x) then
   820             dups (rev_dups, xs)
   821           else dups (x :: rev_dups, xs);
   822   in dups ([], lst) end;
   823 
   824 fun has_duplicates eq =
   825   let
   826     fun dups [] = false
   827       | dups (x :: xs) = member eq xs x orelse dups xs;
   828   in dups end;
   829 
   830 
   831 (* matrices *)
   832 
   833 fun map_transpose f xss =
   834   let
   835     val n = case distinct (op =) (map length xss)
   836      of [] => 0
   837       | [n] => n
   838       | _ => raise UnequalLengths;
   839   in map_range (fn m => f (map (fn xs => nth xs m) xss)) n end;
   840 
   841 
   842 
   843 (** lists as multisets **)
   844 
   845 fun remove1 eq x [] = []
   846   | remove1 eq x (y :: ys) = if eq (x, y) then ys else y :: remove1 eq x ys;
   847 
   848 fun combine eq xs ys = fold (remove1 eq) ys xs @ ys;
   849 
   850 fun submultiset _ ([], _)  = true
   851   | submultiset eq (x :: xs, ys) = member eq ys x andalso submultiset eq (xs, remove1 eq x ys);
   852 
   853 
   854 
   855 (** orders **)
   856 
   857 fun is_equal EQUAL = true
   858   | is_equal _ = false;
   859 
   860 fun rev_order LESS = GREATER
   861   | rev_order EQUAL = EQUAL
   862   | rev_order GREATER = LESS;
   863 
   864 (*assume rel is a linear strict order*)
   865 fun make_ord rel (x, y) =
   866   if rel (x, y) then LESS
   867   else if rel (y, x) then GREATER
   868   else EQUAL;
   869 
   870 fun bool_ord (false, true) = LESS
   871   | bool_ord (true, false) = GREATER
   872   | bool_ord _ = EQUAL;
   873 
   874 val int_ord = Int.compare;
   875 val string_ord = String.compare;
   876 
   877 fun fast_string_ord (s1, s2) =
   878   (case int_ord (size s1, size s2) of EQUAL => string_ord (s1, s2) | ord => ord);
   879 
   880 fun option_ord ord (SOME x, SOME y) = ord (x, y)
   881   | option_ord _ (NONE, NONE) = EQUAL
   882   | option_ord _ (NONE, SOME _) = LESS
   883   | option_ord _ (SOME _, NONE) = GREATER;
   884 
   885 (*lexicographic product*)
   886 fun prod_ord a_ord b_ord ((x, y), (x', y')) =
   887   (case a_ord (x, x') of EQUAL => b_ord (y, y') | ord => ord);
   888 
   889 (*dictionary order -- in general NOT well-founded!*)
   890 fun dict_ord elem_ord (x :: xs, y :: ys) =
   891       (case elem_ord (x, y) of EQUAL => dict_ord elem_ord (xs, ys) | ord => ord)
   892   | dict_ord _ ([], []) = EQUAL
   893   | dict_ord _ ([], _ :: _) = LESS
   894   | dict_ord _ (_ :: _, []) = GREATER;
   895 
   896 (*lexicographic product of lists*)
   897 fun list_ord elem_ord (xs, ys) =
   898   (case int_ord (length xs, length ys) of EQUAL => dict_ord elem_ord (xs, ys) | ord => ord);
   899 
   900 
   901 (* sorting *)
   902 
   903 (*quicksort -- stable, i.e. does not reorder equal elements*)
   904 fun quicksort unique ord =
   905   let
   906     fun qsort [] = []
   907       | qsort (xs as [_]) = xs
   908       | qsort (xs as [x, y]) =
   909           (case ord (x, y) of
   910             LESS => xs
   911           | EQUAL => if unique then [x] else xs
   912           | GREATER => [y, x])
   913       | qsort xs =
   914           let val (lts, eqs, gts) = part (nth xs (length xs div 2)) xs
   915           in qsort lts @ eqs @ qsort gts end
   916     and part _ [] = ([], [], [])
   917       | part pivot (x :: xs) = add (ord (x, pivot)) x (part pivot xs)
   918     and add LESS x (lts, eqs, gts) = (x :: lts, eqs, gts)
   919       | add EQUAL x (lts, [], gts) = (lts, [x], gts)
   920       | add EQUAL x (res as (lts, eqs, gts)) = if unique then res else (lts, x :: eqs, gts)
   921       | add GREATER x (lts, eqs, gts) = (lts, eqs, x :: gts);
   922   in qsort end;
   923 
   924 fun sort ord = quicksort false ord;
   925 fun sort_distinct ord = quicksort true ord;
   926 
   927 val sort_strings = sort string_ord;
   928 fun sort_wrt sel xs = sort (string_ord o pairself sel) xs;
   929 
   930 
   931 (* items tagged by integer index *)
   932 
   933 (*insert tags*)
   934 fun tag_list k [] = []
   935   | tag_list k (x :: xs) = (k:int, x) :: tag_list (k + 1) xs;
   936 
   937 (*remove tags and suppress duplicates -- list is assumed sorted!*)
   938 fun untag_list [] = []
   939   | untag_list [(k: int, x)] = [x]
   940   | untag_list ((k, x) :: (rest as (k', x') :: _)) =
   941       if k = k' then untag_list rest
   942       else x :: untag_list rest;
   943 
   944 (*return list elements in original order*)
   945 fun order_list list = untag_list (sort (int_ord o pairself fst) list);
   946 
   947 
   948 
   949 (** random numbers **)
   950 
   951 exception RANDOM;
   952 
   953 fun rmod x y = x - y * Real.realFloor (x / y);
   954 
   955 local
   956   val a = 16807.0;
   957   val m = 2147483647.0;
   958   val random_seed = Unsynchronized.ref 1.0;
   959 in
   960 
   961 fun random () = CRITICAL (fn () =>
   962   let val r = rmod (a * ! random_seed) m
   963   in (random_seed := r; r) end);
   964 
   965 end;
   966 
   967 fun random_range l h =
   968   if h < l orelse l < 0 then raise RANDOM
   969   else l + Real.floor (rmod (random ()) (real (h - l + 1)));
   970 
   971 fun one_of xs = nth xs (random_range 0 (length xs - 1));
   972 
   973 fun frequency xs =
   974   let
   975     val sum = foldl op + (0, map fst xs);
   976     fun pick n ((k: int, x) :: xs) =
   977       if n <= k then x else pick (n - k) xs
   978   in pick (random_range 1 sum) xs end;
   979 
   980 
   981 
   982 (** misc **)
   983 
   984 fun divide_and_conquer decomp x =
   985   let val (ys, recomb) = decomp x
   986   in recomb (map (divide_and_conquer decomp) ys) end;
   987 
   988 fun divide_and_conquer' decomp x s =
   989   let val ((ys, recomb), s') = decomp x s
   990   in recomb (fold_map (divide_and_conquer' decomp) ys s') end;
   991 
   992 
   993 (*Partition a list into buckets  [ bi, b(i+1), ..., bj ]
   994    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
   995 fun partition_list p i j =
   996   let
   997     fun part (k: int) xs =
   998       if k > j then
   999         (case xs of
  1000           [] => []
  1001         | _ => raise Fail "partition_list")
  1002       else
  1003         let val (ns, rest) = List.partition (p k) xs
  1004         in ns :: part (k + 1) rest end;
  1005   in part (i: int) end;
  1006 
  1007 fun partition_eq (eq: 'a * 'a -> bool) =
  1008   let
  1009     fun part [] = []
  1010       | part (x :: ys) =
  1011           let val (xs, xs') = List.partition (fn y => eq (x, y)) ys
  1012           in (x :: xs) :: part xs' end;
  1013   in part end;
  1014 
  1015 
  1016 
  1017 (* generating identifiers *)
  1018 
  1019 (** Freshly generated identifiers; supplied prefix MUST start with a letter **)
  1020 local
  1021 (*Maps 0-61 to A-Z, a-z, 0-9; exclude _ or ' to avoid clash with internal/unusual indentifiers*)
  1022 fun gensym_char i =
  1023   if i<26 then chr (ord "A" + i)
  1024   else if i<52 then chr (ord "a" + i - 26)
  1025   else chr (ord "0" + i - 52);
  1026 
  1027 val char_vec = Vector.tabulate (62, gensym_char);
  1028 fun newid n = implode (map (fn i => Vector.sub (char_vec, i)) (radixpand (62, n)));
  1029 
  1030 val gensym_seed = Unsynchronized.ref (0: int);
  1031 
  1032 in
  1033   fun gensym pre =
  1034     pre ^ newid (NAMED_CRITICAL "gensym" (fn () => Unsynchronized.inc gensym_seed));
  1035 end;
  1036 
  1037 
  1038 (* stamps and serial numbers *)
  1039 
  1040 type stamp = unit Unsynchronized.ref;
  1041 val stamp: unit -> stamp = Unsynchronized.ref;
  1042 
  1043 type serial = int;
  1044 val serial = Multithreading.serial;
  1045 val serial_string = string_of_int o serial;
  1046 
  1047 
  1048 (* generic objects *)
  1049 
  1050 (*note that the builtin exception datatype may be extended by new
  1051   constructors at any time*)
  1052 structure Object = struct type T = exn end;
  1053 
  1054 end;
  1055 
  1056 structure Basic_Library: BASIC_LIBRARY = Library;
  1057 open Basic_Library;