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