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