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