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