src/Pure/library.ML
author wenzelm
Thu Mar 08 21:35:54 2012 +0100 (2012-03-08)
changeset 46838 c54b81bb9588
parent 46779 4f298836018b
child 46891 af4c1dd3963f
permissions -rw-r--r--
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   (*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 flat: 'a list list -> 'a list
    70   val unflat: 'a list list -> 'b list -> 'b list list
    71   val burrow: ('a list -> 'b list) -> 'a list list -> 'b list list
    72   val burrow_options: ('a list -> 'b list) -> 'a option list -> 'b option list
    73   val burrow_fst: ('a list -> 'b list) -> ('a * 'c) list -> ('b * 'c) list
    74   val fold_burrow: ('a list -> 'c -> 'b list * 'd) -> 'a list list -> 'c -> 'b list list * 'd
    75   val maps: ('a -> 'b list) -> 'a list -> 'b list
    76   val filter: ('a -> bool) -> 'a list -> 'a list
    77   val filter_out: ('a -> bool) -> 'a list -> 'a list
    78   val map_filter: ('a -> 'b option) -> 'a list -> 'b list
    79   val take: int -> 'a list -> 'a list
    80   val drop: int -> 'a list -> 'a list
    81   val chop: int -> 'a list -> 'a list * 'a list
    82   val chop_while: ('a -> bool) -> 'a list -> 'a list * 'a list
    83   val nth: 'a list -> int -> 'a
    84   val nth_map: int -> ('a -> 'a) -> 'a list -> 'a list
    85   val nth_drop: int -> 'a list -> 'a list
    86   val nth_list: 'a list list -> int -> 'a list
    87   val map_index: (int * 'a -> 'b) -> 'a list -> 'b list
    88   val fold_index: (int * 'a -> 'b -> 'b) -> 'a list -> 'b -> 'b
    89   val map_range: (int -> 'a) -> int -> 'a list
    90   val split_last: 'a list -> 'a list * 'a
    91   val find_index: ('a -> bool) -> 'a list -> int
    92   val find_first: ('a -> bool) -> 'a list -> 'a option
    93   val get_index: ('a -> 'b option) -> 'a list -> (int * 'b) option
    94   val get_first: ('a -> 'b option) -> 'a list -> 'b option
    95   val eq_list: ('a * 'a -> bool) -> 'a list * 'a list -> bool
    96   val map2: ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
    97   val fold2: ('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> 'c -> 'c
    98   val fold_rev2: ('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> 'c -> 'c
    99   val forall2: ('a -> 'b -> bool) -> 'a list -> 'b list -> bool
   100   val zip_options: 'a list -> 'b option list -> ('a * 'b) list
   101   val ~~ : 'a list * 'b list -> ('a * 'b) list
   102   val map_split: ('a -> 'b * 'c) -> 'a list -> 'b list * 'c list
   103   val split_list: ('a * 'b) list -> 'a list * 'b list
   104   val map_product: ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list
   105   val fold_product: ('a -> 'b -> 'c -> 'c) -> 'a list -> 'b list -> 'c -> 'c
   106   val map_transpose: ('a list -> 'b) -> 'a list list -> 'b list
   107   val separate: 'a -> 'a list -> 'a list
   108   val surround: 'a -> 'a list -> 'a list
   109   val replicate: int -> 'a -> 'a list
   110   val is_prefix: ('a * 'a -> bool) -> 'a list -> 'a list -> bool
   111   val take_prefix: ('a -> bool) -> 'a list -> 'a list * 'a list
   112   val chop_prefix: ('a * 'b -> bool) -> 'a list * 'b list -> 'a list * ('a list * 'b list)
   113   val take_suffix: ('a -> bool) -> 'a list -> 'a list * 'a list
   114   val prefixes1: 'a list -> 'a list list
   115   val prefixes: 'a list -> 'a list list
   116   val suffixes1: 'a list -> 'a list list
   117   val suffixes: 'a list -> 'a list list
   118 
   119   (*integers*)
   120   val upto: int * int -> int list
   121   val downto: int * int -> int list
   122   val radixpand: int * int -> int list
   123   val radixstring: int * string * int -> string
   124   val string_of_int: int -> string
   125   val signed_string_of_int: int -> string
   126   val string_of_indexname: string * int -> string
   127   val read_radix_int: int -> string list -> int * string list
   128   val read_int: string list -> int * string list
   129   val oct_char: string -> string
   130 
   131   (*strings*)
   132   val nth_string: string -> int -> string
   133   val fold_string: (string -> 'a -> 'a) -> string -> 'a -> 'a
   134   val exists_string: (string -> bool) -> string -> bool
   135   val forall_string: (string -> bool) -> string -> bool
   136   val first_field: string -> string -> (string * string) option
   137   val enclose: string -> string -> string -> string
   138   val unenclose: string -> string
   139   val quote: string -> string
   140   val space_implode: string -> string list -> string
   141   val commas: string list -> string
   142   val commas_quote: string list -> string
   143   val cat_lines: string list -> string
   144   val space_explode: string -> string -> string list
   145   val split_lines: string -> string list
   146   val prefix_lines: string -> string -> string
   147   val prefix: string -> string -> string
   148   val suffix: string -> string -> string
   149   val unprefix: string -> string -> string
   150   val unsuffix: string -> string -> string
   151   val replicate_string: int -> string -> string
   152   val translate_string: (string -> string) -> string -> string
   153   val match_string: string -> string -> bool
   154 
   155   (*reals*)
   156   val string_of_real: real -> string
   157   val signed_string_of_real: real -> string
   158   val smart_string_of_real: real -> string
   159 
   160   (*lists as sets -- see also Pure/General/ord_list.ML*)
   161   val member: ('b * 'a -> bool) -> 'a list -> 'b -> bool
   162   val insert: ('a * 'a -> bool) -> 'a -> 'a list -> 'a list
   163   val remove: ('b * 'a -> bool) -> 'b -> 'a list -> 'a list
   164   val update: ('a * 'a -> bool) -> 'a -> 'a list -> 'a list
   165   val union: ('a * 'a -> bool) -> 'a list -> 'a list -> 'a list
   166   val subtract: ('b * 'a -> bool) -> 'b list -> 'a list -> 'a list
   167   val inter: ('a * 'b -> bool) -> 'b list -> 'a list -> 'a list
   168   val merge: ('a * 'a -> bool) -> 'a list * 'a list -> 'a list
   169   val subset: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   170   val eq_set: ('a * 'a -> bool) -> 'a list * 'a list -> bool
   171   val distinct: ('a * 'a -> bool) -> 'a list -> 'a list
   172   val duplicates: ('a * 'a -> bool) -> 'a list -> 'a list
   173   val has_duplicates: ('a * 'a -> bool) -> 'a list -> bool
   174 
   175   (*lists as multisets*)
   176   val remove1: ('b * 'a -> bool) -> 'b -> 'a list -> 'a list
   177   val combine: ('a * 'a -> bool) -> 'a list -> 'a list -> 'a list
   178   val submultiset: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   179 
   180   (*orders*)
   181   val is_equal: order -> bool
   182   val rev_order: order -> order
   183   val make_ord: ('a * 'a -> bool) -> 'a * 'a -> order
   184   val bool_ord: bool * bool -> order
   185   val int_ord: int * int -> order
   186   val string_ord: string * string -> order
   187   val fast_string_ord: string * string -> order
   188   val option_ord: ('a * 'b -> order) -> 'a option * 'b option -> order
   189   val prod_ord: ('a * 'b -> order) -> ('c * 'd -> order) -> ('a * 'c) * ('b * 'd) -> order
   190   val dict_ord: ('a * 'b -> order) -> 'a list * 'b list -> order
   191   val list_ord: ('a * 'b -> order) -> 'a list * 'b list -> order
   192   val sort: ('a * 'a -> order) -> 'a list -> 'a list
   193   val sort_distinct: ('a * 'a -> order) -> 'a list -> 'a list
   194   val sort_strings: string list -> string list
   195   val sort_wrt: ('a -> string) -> 'a list -> 'a list
   196   val tag_list: int -> 'a list -> (int * 'a) list
   197   val untag_list: (int * 'a) list -> 'a list
   198   val order_list: (int * 'a) list -> 'a list
   199 
   200   (*random numbers*)
   201   exception RANDOM
   202   val random: unit -> real
   203   val random_range: int -> int -> int
   204   val one_of: 'a list -> 'a
   205   val frequency: (int * 'a) list -> 'a
   206 
   207   (*misc*)
   208   val divide_and_conquer: ('a -> 'a list * ('b list -> 'b)) -> 'a -> 'b
   209   val divide_and_conquer': ('a -> 'b -> ('a list * ('c list * 'b -> 'c * 'b)) * 'b) ->
   210     'a -> 'b -> 'c * 'b
   211   val partition_eq: ('a * 'a -> bool) -> 'a list -> 'a list list
   212   val partition_list: (int -> 'a -> bool) -> int -> int -> 'a list -> 'a list list
   213   val legacy_gensym: string -> string
   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 Object: 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 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 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 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_while P [] = ([], [])
   414   | chop_while P (ys as x :: xs) =
   415       if P x then chop_while P xs |>> cons x else ([], ys);
   416 
   417 (*return nth element of a list, where 0 designates the first element;
   418   raise Subscript if list too short*)
   419 fun nth xs i = List.nth (xs, i);
   420 
   421 fun nth_list xss i = nth xss i handle General.Subscript => [];
   422 
   423 fun nth_map 0 f (x :: xs) = f x :: xs
   424   | nth_map n f (x :: xs) = x :: nth_map (n - 1) f xs
   425   | nth_map (_: int) _ [] = raise Subscript;
   426 
   427 fun nth_drop n xs =
   428   List.take (xs, n) @ List.drop (xs, n + 1);
   429 
   430 fun map_index f =
   431   let
   432     fun mapp (_: int) [] = []
   433       | mapp i (x :: xs) = f (i, x) :: mapp (i + 1) xs
   434   in mapp 0 end;
   435 
   436 fun fold_index f =
   437   let
   438     fun fold_aux (_: int) [] y = y
   439       | fold_aux i (x :: xs) y = fold_aux (i + 1) xs (f (i, x) y);
   440   in fold_aux 0 end;
   441 
   442 fun map_range f i =
   443   let
   444     fun mapp (k: int) =
   445       if k < i then f k :: mapp (k + 1) else [];
   446   in mapp 0 end;
   447 
   448 (*rear decomposition*)
   449 fun split_last [] = raise Empty
   450   | split_last [x] = ([], x)
   451   | split_last (x :: xs) = apfst (cons x) (split_last xs);
   452 
   453 (*find position of first element satisfying a predicate*)
   454 fun find_index pred =
   455   let fun find (_: int) [] = ~1
   456         | find n (x :: xs) = if pred x then n else find (n + 1) xs;
   457   in find 0 end;
   458 
   459 (*find first element satisfying predicate*)
   460 val find_first = List.find;
   461 
   462 (*get first element by lookup function*)
   463 fun get_first _ [] = NONE
   464   | get_first f (x :: xs) =
   465       (case f x of
   466         NONE => get_first f xs
   467       | some => some);
   468 
   469 fun get_index f =
   470   let
   471     fun get (_: int) [] = NONE
   472       | get i (x :: xs) =
   473           (case f x of
   474             NONE => get (i + 1) xs
   475           | SOME y => SOME (i, y))
   476   in get 0 end;
   477 
   478 val flat = List.concat;
   479 
   480 fun unflat (xs :: xss) ys =
   481       let val (ps, qs) = chop (length xs) ys
   482       in ps :: unflat xss qs end
   483   | unflat [] [] = []
   484   | unflat _ _ = raise ListPair.UnequalLengths;
   485 
   486 fun burrow f xss = unflat xss (f (flat xss));
   487 
   488 fun burrow_options f os = map (try hd) (burrow f (map the_list os));
   489 
   490 fun fold_burrow f xss s =
   491   apfst (unflat xss) (f (flat xss) s);
   492 
   493 (*separate s [x1, x2, ..., xn]  ===>  [x1, s, x2, s, ..., s, xn]*)
   494 fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
   495   | separate _ xs = xs;
   496 
   497 fun surround s (x :: xs) = s :: x :: surround s xs
   498   | surround s [] = [s];
   499 
   500 (*make the list [x, x, ..., x] of length n*)
   501 fun replicate (n: int) x =
   502   let fun rep (0, xs) = xs
   503         | rep (n, xs) = rep (n - 1, x :: xs)
   504   in
   505     if n < 0 then raise Subscript
   506     else rep (n, [])
   507   end;
   508 
   509 
   510 (* direct product *)
   511 
   512 fun map_product f _ [] = []
   513   | map_product f [] _ = []
   514   | map_product f (x :: xs) ys = map (f x) ys @ map_product f xs ys;
   515 
   516 fun fold_product f _ [] z = z
   517   | fold_product f [] _ z = z
   518   | fold_product f (x :: xs) ys z = z |> fold (f x) ys |> fold_product f xs ys;
   519 
   520 
   521 (* lists of pairs *)
   522 
   523 fun map2 _ [] [] = []
   524   | map2 f (x :: xs) (y :: ys) = f x y :: map2 f xs ys
   525   | map2 _ _ _ = raise ListPair.UnequalLengths;
   526 
   527 fun fold2 f [] [] z = z
   528   | fold2 f (x :: xs) (y :: ys) z = fold2 f xs ys (f x y z)
   529   | fold2 f _ _ _ = raise ListPair.UnequalLengths;
   530 
   531 fun fold_rev2 f [] [] z = z
   532   | fold_rev2 f (x :: xs) (y :: ys) z = f x y (fold_rev2 f xs ys z)
   533   | fold_rev2 f _ _ _ = raise ListPair.UnequalLengths;
   534 
   535 fun forall2 P [] [] = true
   536   | forall2 P (x :: xs) (y :: ys) = P x y andalso forall2 P xs ys
   537   | forall2 P _ _ = raise ListPair.UnequalLengths;
   538 
   539 fun map_split f [] = ([], [])
   540   | map_split f (x :: xs) =
   541       let
   542         val (y, w) = f x;
   543         val (ys, ws) = map_split f xs;
   544       in (y :: ys, w :: ws) end;
   545 
   546 fun zip_options (x :: xs) (SOME y :: ys) = (x, y) :: zip_options xs ys
   547   | zip_options (_ :: xs) (NONE :: ys) = zip_options xs ys
   548   | zip_options _ [] = []
   549   | zip_options [] _ = raise ListPair.UnequalLengths;
   550 
   551 (*combine two lists forming a list of pairs:
   552   [x1, ..., xn] ~~ [y1, ..., yn]  ===>  [(x1, y1), ..., (xn, yn)]*)
   553 fun [] ~~ [] = []
   554   | (x :: xs) ~~ (y :: ys) = (x, y) :: (xs ~~ ys)
   555   | _ ~~ _ = raise ListPair.UnequalLengths;
   556 
   557 (*inverse of ~~; the old 'split':
   558   [(x1, y1), ..., (xn, yn)]  ===>  ([x1, ..., xn], [y1, ..., yn])*)
   559 val split_list = ListPair.unzip;
   560 
   561 fun burrow_fst f xs = split_list xs |>> f |> op ~~;
   562 
   563 
   564 (* prefixes, suffixes *)
   565 
   566 fun is_prefix _ [] _ = true
   567   | is_prefix eq (x :: xs) (y :: ys) = eq (x, y) andalso is_prefix eq xs ys
   568   | is_prefix eq _ _ = false;
   569 
   570 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., x(i-1)], [xi, ..., xn])
   571    where xi is the first element that does not satisfy the predicate*)
   572 fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
   573   let fun take (rxs, []) = (rev rxs, [])
   574         | take (rxs, x :: xs) =
   575             if  pred x  then  take(x :: rxs, xs)  else  (rev rxs, x :: xs)
   576   in  take([], xs)  end;
   577 
   578 fun chop_prefix eq ([], ys) = ([], ([], ys))
   579   | chop_prefix eq (xs, []) = ([], (xs, []))
   580   | chop_prefix eq (xs as x :: xs', ys as y :: ys') =
   581       if eq (x, y) then
   582         let val (ps', xys'') = chop_prefix eq (xs', ys')
   583         in (x :: ps', xys'') end
   584       else ([], (xs, ys));
   585 
   586 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., xi], [x(i+1), ..., xn])
   587    where xi is the last element that does not satisfy the predicate*)
   588 fun take_suffix _ [] = ([], [])
   589   | take_suffix pred (x :: xs) =
   590       (case take_suffix pred xs of
   591         ([], sffx) => if pred x then ([], x :: sffx) else ([x], sffx)
   592       | (prfx, sffx) => (x :: prfx, sffx));
   593 
   594 fun prefixes1 [] = []
   595   | prefixes1 (x :: xs) = map (cons x) ([] :: prefixes1 xs);
   596 
   597 fun prefixes xs = [] :: prefixes1 xs;
   598 
   599 fun suffixes1 xs = map rev (prefixes1 (rev xs));
   600 fun suffixes xs = [] :: suffixes1 xs;
   601 
   602 
   603 
   604 (** integers **)
   605 
   606 (* lists of integers *)
   607 
   608 (*make the list [from, from + 1, ..., to]*)
   609 fun ((i: int) upto j) =
   610   if i > j then [] else i :: (i + 1 upto j);
   611 
   612 (*make the list [from, from - 1, ..., to]*)
   613 fun ((i: int) downto j) =
   614   if i < j then [] else i :: (i - 1 downto j);
   615 
   616 
   617 (* convert integers to strings *)
   618 
   619 (*expand the number in the given base;
   620   example: radixpand (2, 8) gives [1, 0, 0, 0]*)
   621 fun radixpand (base, num) : int list =
   622   let
   623     fun radix (n, tail) =
   624       if n < base then n :: tail
   625       else radix (n div base, (n mod base) :: tail)
   626   in radix (num, []) end;
   627 
   628 (*expands a number into a string of characters starting from "zerochar";
   629   example: radixstring (2, "0", 8) gives "1000"*)
   630 fun radixstring (base, zerochar, num) =
   631   let val offset = ord zerochar;
   632       fun chrof n = chr (offset + n)
   633   in implode (map chrof (radixpand (base, num))) end;
   634 
   635 
   636 local
   637   val zero = ord "0";
   638   val small = 10000: int;
   639   val small_table = Vector.tabulate (small, Int.toString);
   640 in
   641 
   642 fun string_of_int i =
   643   if i < 0 then Int.toString i
   644   else if i < 10 then chr (zero + i)
   645   else if i < small then Vector.sub (small_table, i)
   646   else Int.toString i;
   647 
   648 end;
   649 
   650 fun signed_string_of_int i =
   651   if i < 0 then "-" ^ string_of_int (~ i) else string_of_int i;
   652 
   653 fun string_of_indexname (a, 0) = a
   654   | string_of_indexname (a, i) = a ^ "_" ^ string_of_int i;
   655 
   656 
   657 (* read integers *)
   658 
   659 fun read_radix_int radix cs =
   660   let
   661     val zero = ord "0";
   662     val limit = zero + radix;
   663     fun scan (num, []) = (num, [])
   664       | scan (num, c :: cs) =
   665         if zero <= ord c andalso ord c < limit then
   666           scan (radix * num + (ord c - zero), cs)
   667         else (num, c :: cs);
   668   in scan (0, cs) end;
   669 
   670 val read_int = read_radix_int 10;
   671 
   672 fun oct_char s = chr (#1 (read_radix_int 8 (raw_explode s)));
   673 
   674 
   675 
   676 (** strings **)
   677 
   678 (* functions tuned for strings, avoiding explode *)
   679 
   680 fun nth_string str i =
   681   (case try String.substring (str, i, 1) of
   682     SOME s => s
   683   | NONE => raise Subscript);
   684 
   685 fun fold_string f str x0 =
   686   let
   687     val n = size str;
   688     fun iter (x, i) =
   689       if i < n then iter (f (String.substring (str, i, 1)) x, i + 1) else x;
   690   in iter (x0, 0) end;
   691 
   692 fun exists_string pred str =
   693   let
   694     val n = size str;
   695     fun ex i = i < n andalso (pred (String.substring (str, i, 1)) orelse ex (i + 1));
   696   in ex 0 end;
   697 
   698 fun forall_string pred = not o exists_string (not o pred);
   699 
   700 fun first_field sep str =
   701   let
   702     val n = size sep;
   703     val len = size str;
   704     fun find i =
   705       if i + n > len then NONE
   706       else if String.substring (str, i, n) = sep then SOME i
   707       else find (i + 1);
   708   in
   709     (case find 0 of
   710       NONE => NONE
   711     | SOME i => SOME (String.substring (str, 0, i), String.extract (str, i + n, NONE)))
   712   end;
   713 
   714 (*enclose in brackets*)
   715 fun enclose lpar rpar str = lpar ^ str ^ rpar;
   716 fun unenclose str = String.substring (str, 1, size str - 2);
   717 
   718 (*simple quoting (does not escape special chars)*)
   719 val quote = enclose "\"" "\"";
   720 
   721 fun space_implode a bs = implode (separate a bs);
   722 
   723 val commas = space_implode ", ";
   724 val commas_quote = commas o map quote;
   725 
   726 val cat_lines = space_implode "\n";
   727 
   728 (*space_explode "." "h.e..l.lo" = ["h", "e", "", "l", "lo"]*)
   729 fun space_explode _ "" = []
   730   | space_explode sep s = String.fields (fn c => str c = sep) s;
   731 
   732 val split_lines = space_explode "\n";
   733 
   734 fun prefix_lines "" txt = txt
   735   | prefix_lines prfx txt = txt |> split_lines |> map (fn s => prfx ^ s) |> cat_lines;
   736 
   737 fun prefix prfx s = prfx ^ s;
   738 fun suffix sffx s = s ^ sffx;
   739 
   740 fun unprefix prfx s =
   741   if String.isPrefix prfx s then String.substring (s, size prfx, size s - size prfx)
   742   else raise Fail "unprefix";
   743 
   744 fun unsuffix sffx s =
   745   if String.isSuffix sffx s then String.substring (s, 0, size s - size sffx)
   746   else raise Fail "unsuffix";
   747 
   748 fun replicate_string (0: int) _ = ""
   749   | replicate_string 1 a = a
   750   | replicate_string k a =
   751       if k mod 2 = 0 then replicate_string (k div 2) (a ^ a)
   752       else replicate_string (k div 2) (a ^ a) ^ a;
   753 
   754 fun translate_string f = String.translate (f o String.str);
   755 
   756 (*crude matching of str against simple glob pat*)
   757 fun match_string pat str =
   758   let
   759     fun match [] _ = true
   760       | match (p :: ps) s =
   761           size p <= size s andalso
   762             (case try (unprefix p) s of
   763               SOME s' => match ps s'
   764             | NONE => match (p :: ps) (String.substring (s, 1, size s - 1)));
   765   in match (space_explode "*" pat) str end;
   766 
   767 
   768 (** reals **)
   769 
   770 val string_of_real = Real.fmt (StringCvt.GEN NONE);
   771 
   772 fun signed_string_of_real x =
   773   if x < 0.0 then "-" ^ string_of_real (~ x) else string_of_real x;
   774 
   775 fun smart_string_of_real x =
   776   let
   777     val s = signed_string_of_real x;
   778   in
   779     (case space_explode "." s of
   780       [a, b] => if forall_string (fn c => c = "0") b then a else s
   781     | _ => s)
   782   end;
   783 
   784 
   785 
   786 (** lists as sets -- see also Pure/General/ord_list.ML **)
   787 
   788 (* canonical operations *)
   789 
   790 fun member eq list x =
   791   let
   792     fun memb [] = false
   793       | memb (y :: ys) = eq (x, y) orelse memb ys;
   794   in memb list end;
   795 
   796 fun insert eq x xs = if member eq xs x then xs else x :: xs;
   797 fun remove eq x xs = if member eq xs x then filter_out (fn y => eq (x, y)) xs else xs;
   798 fun update eq x xs = cons x (remove eq x xs);
   799 
   800 fun inter eq xs = filter (member eq xs);
   801 
   802 fun union eq = fold (insert eq);
   803 fun subtract eq = fold (remove eq);
   804 
   805 fun merge eq (xs, ys) =
   806   if pointer_eq (xs, ys) then xs
   807   else if null xs then ys
   808   else fold_rev (insert eq) ys xs;
   809 
   810 
   811 (* subset and set equality *)
   812 
   813 fun subset eq (xs, ys) = forall (member eq ys) xs;
   814 
   815 fun eq_set eq (xs, ys) =
   816   eq_list eq (xs, ys) orelse
   817     (subset eq (xs, ys) andalso subset (eq o swap) (ys, xs));
   818 
   819 
   820 (*makes a list of the distinct members of the input; preserves order, takes
   821   first of equal elements*)
   822 fun distinct eq lst =
   823   let
   824     fun dist (rev_seen, []) = rev rev_seen
   825       | dist (rev_seen, x :: xs) =
   826           if member eq rev_seen x then dist (rev_seen, xs)
   827           else dist (x :: rev_seen, xs);
   828   in dist ([], lst) end;
   829 
   830 (*returns a list containing all repeated elements exactly once; preserves
   831   order, takes first of equal elements*)
   832 fun duplicates eq lst =
   833   let
   834     fun dups (rev_dups, []) = rev rev_dups
   835       | dups (rev_dups, x :: xs) =
   836           if member eq rev_dups x orelse not (member eq xs x) then
   837             dups (rev_dups, xs)
   838           else dups (x :: rev_dups, xs);
   839   in dups ([], lst) end;
   840 
   841 fun has_duplicates eq =
   842   let
   843     fun dups [] = false
   844       | dups (x :: xs) = member eq xs x orelse dups xs;
   845   in dups end;
   846 
   847 
   848 (* matrices *)
   849 
   850 fun map_transpose f xss =
   851   let
   852     val n =
   853       (case distinct (op =) (map length xss) of
   854         [] => 0
   855       | [n] => n
   856       | _ => raise ListPair.UnequalLengths);
   857   in map_range (fn m => f (map (fn xs => nth xs m) xss)) n end;
   858 
   859 
   860 
   861 (** lists as multisets **)
   862 
   863 fun remove1 eq x [] = []
   864   | remove1 eq x (y :: ys) = if eq (x, y) then ys else y :: remove1 eq x ys;
   865 
   866 fun combine eq xs ys = fold (remove1 eq) ys xs @ ys;
   867 
   868 fun submultiset _ ([], _)  = true
   869   | submultiset eq (x :: xs, ys) = member eq ys x andalso submultiset eq (xs, remove1 eq x ys);
   870 
   871 
   872 
   873 (** orders **)
   874 
   875 fun is_equal EQUAL = true
   876   | is_equal _ = false;
   877 
   878 fun rev_order LESS = GREATER
   879   | rev_order EQUAL = EQUAL
   880   | rev_order GREATER = LESS;
   881 
   882 (*assume rel is a linear strict order*)
   883 fun make_ord rel (x, y) =
   884   if rel (x, y) then LESS
   885   else if rel (y, x) then GREATER
   886   else EQUAL;
   887 
   888 fun bool_ord (false, true) = LESS
   889   | bool_ord (true, false) = GREATER
   890   | bool_ord _ = EQUAL;
   891 
   892 val int_ord = Int.compare;
   893 val string_ord = String.compare;
   894 
   895 fun fast_string_ord (s1, s2) =
   896   if pointer_eq (s1, s2) then EQUAL
   897   else (case int_ord (size s1, size s2) of EQUAL => string_ord (s1, s2) | ord => ord);
   898 
   899 fun option_ord ord (SOME x, SOME y) = ord (x, y)
   900   | option_ord _ (NONE, NONE) = EQUAL
   901   | option_ord _ (NONE, SOME _) = LESS
   902   | option_ord _ (SOME _, NONE) = GREATER;
   903 
   904 (*lexicographic product*)
   905 fun prod_ord a_ord b_ord ((x, y), (x', y')) =
   906   (case a_ord (x, x') of EQUAL => b_ord (y, y') | ord => ord);
   907 
   908 (*dictionary order -- in general NOT well-founded!*)
   909 fun dict_ord elem_ord (x :: xs, y :: ys) =
   910       (case elem_ord (x, y) of EQUAL => dict_ord elem_ord (xs, ys) | ord => ord)
   911   | dict_ord _ ([], []) = EQUAL
   912   | dict_ord _ ([], _ :: _) = LESS
   913   | dict_ord _ (_ :: _, []) = GREATER;
   914 
   915 (*lexicographic product of lists*)
   916 fun list_ord elem_ord (xs, ys) =
   917   (case int_ord (length xs, length ys) of EQUAL => dict_ord elem_ord (xs, ys) | ord => ord);
   918 
   919 
   920 (* sorting *)
   921 
   922 (*quicksort -- stable, i.e. does not reorder equal elements*)
   923 fun quicksort unique ord =
   924   let
   925     fun qsort [] = []
   926       | qsort (xs as [_]) = xs
   927       | qsort (xs as [x, y]) =
   928           (case ord (x, y) of
   929             LESS => xs
   930           | EQUAL => if unique then [x] else xs
   931           | GREATER => [y, x])
   932       | qsort xs =
   933           let val (lts, eqs, gts) = part (nth xs (length xs div 2)) xs
   934           in qsort lts @ eqs @ qsort gts end
   935     and part _ [] = ([], [], [])
   936       | part pivot (x :: xs) = add (ord (x, pivot)) x (part pivot xs)
   937     and add LESS x (lts, eqs, gts) = (x :: lts, eqs, gts)
   938       | add EQUAL x (lts, [], gts) = (lts, [x], gts)
   939       | add EQUAL x (res as (lts, eqs, gts)) = if unique then res else (lts, x :: eqs, gts)
   940       | add GREATER x (lts, eqs, gts) = (lts, eqs, x :: gts);
   941   in qsort end;
   942 
   943 fun sort ord = quicksort false ord;
   944 fun sort_distinct ord = quicksort true ord;
   945 
   946 val sort_strings = sort string_ord;
   947 fun sort_wrt key xs = sort (string_ord o pairself key) xs;
   948 
   949 
   950 (* items tagged by integer index *)
   951 
   952 (*insert tags*)
   953 fun tag_list k [] = []
   954   | tag_list k (x :: xs) = (k:int, x) :: tag_list (k + 1) xs;
   955 
   956 (*remove tags and suppress duplicates -- list is assumed sorted!*)
   957 fun untag_list [] = []
   958   | untag_list [(k: int, x)] = [x]
   959   | untag_list ((k, x) :: (rest as (k', x') :: _)) =
   960       if k = k' then untag_list rest
   961       else x :: untag_list rest;
   962 
   963 (*return list elements in original order*)
   964 fun order_list list = untag_list (sort (int_ord o pairself fst) list);
   965 
   966 
   967 
   968 (** random numbers **)
   969 
   970 exception RANDOM;
   971 
   972 fun rmod x y = x - y * Real.realFloor (x / y);
   973 
   974 local
   975   val a = 16807.0;
   976   val m = 2147483647.0;
   977   val random_seed = Unsynchronized.ref 1.0;
   978 in
   979 
   980 fun random () = CRITICAL (fn () =>
   981   let val r = rmod (a * ! random_seed) m
   982   in (random_seed := r; r) end);
   983 
   984 end;
   985 
   986 fun random_range l h =
   987   if h < l orelse l < 0 then raise RANDOM
   988   else l + Real.floor (rmod (random ()) (real (h - l + 1)));
   989 
   990 fun one_of xs = nth xs (random_range 0 (length xs - 1));
   991 
   992 fun frequency xs =
   993   let
   994     val sum = foldl op + (0, map fst xs);
   995     fun pick n ((k: int, x) :: xs) =
   996       if n <= k then x else pick (n - k) xs
   997   in pick (random_range 1 sum) xs end;
   998 
   999 
  1000 
  1001 (** misc **)
  1002 
  1003 fun divide_and_conquer decomp x =
  1004   let val (ys, recomb) = decomp x
  1005   in recomb (map (divide_and_conquer decomp) ys) end;
  1006 
  1007 fun divide_and_conquer' decomp x s =
  1008   let val ((ys, recomb), s') = decomp x s
  1009   in recomb (fold_map (divide_and_conquer' decomp) ys s') end;
  1010 
  1011 
  1012 (*Partition a list into buckets  [ bi, b(i+1), ..., bj ]
  1013    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
  1014 fun partition_list p i j =
  1015   let
  1016     fun part (k: int) xs =
  1017       if k > j then
  1018         (case xs of
  1019           [] => []
  1020         | _ => raise Fail "partition_list")
  1021       else
  1022         let val (ns, rest) = List.partition (p k) xs
  1023         in ns :: part (k + 1) rest end;
  1024   in part (i: int) end;
  1025 
  1026 fun partition_eq (eq: 'a * 'a -> bool) =
  1027   let
  1028     fun part [] = []
  1029       | part (x :: ys) =
  1030           let val (xs, xs') = List.partition (fn y => eq (x, y)) ys
  1031           in (x :: xs) :: part xs' end;
  1032   in part end;
  1033 
  1034 
  1035 
  1036 (* generating identifiers -- often fresh *)
  1037 
  1038 local
  1039 (*Maps 0-61 to A-Z, a-z, 0-9; exclude _ or ' to avoid clash with internal/unusual indentifiers*)
  1040 fun gensym_char i =
  1041   if i<26 then chr (ord "A" + i)
  1042   else if i<52 then chr (ord "a" + i - 26)
  1043   else chr (ord "0" + i - 52);
  1044 
  1045 val char_vec = Vector.tabulate (62, gensym_char);
  1046 fun newid n = implode (map (fn i => Vector.sub (char_vec, i)) (radixpand (62, n)));
  1047 
  1048 val gensym_seed = Unsynchronized.ref (0: int);
  1049 
  1050 in
  1051   fun legacy_gensym pre =
  1052     pre ^ newid (NAMED_CRITICAL "legacy_gensym" (fn () => Unsynchronized.inc gensym_seed));
  1053 end;
  1054 
  1055 
  1056 (* serial numbers and abstract stamps *)
  1057 
  1058 type serial = int;
  1059 val serial = Multithreading.serial;
  1060 val serial_string = string_of_int o serial;
  1061 
  1062 datatype stamp = Stamp of serial;
  1063 fun stamp () = Stamp (serial ());
  1064 
  1065 
  1066 (* generic objects *)
  1067 
  1068 (*note that the builtin exception datatype may be extended by new
  1069   constructors at any time*)
  1070 structure Object = struct type T = exn end;
  1071 
  1072 
  1073 (* current directory *)
  1074 
  1075 val cd = OS.FileSys.chDir;
  1076 val pwd = OS.FileSys.getDir;
  1077 
  1078 
  1079 (* getenv *)
  1080 
  1081 fun getenv x =
  1082   (case OS.Process.getEnv x of
  1083     NONE => ""
  1084   | SOME y => y);
  1085 
  1086 fun getenv_strict x =
  1087   (case getenv x of
  1088     "" => error ("Undefined Isabelle environment variable: " ^ quote x)
  1089   | y => y);
  1090 
  1091 end;
  1092 
  1093 structure Basic_Library: BASIC_LIBRARY = Library;
  1094 open Basic_Library;
  1095 
  1096 datatype legacy = UnequalLengths;