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