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