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