src/Pure/library.ML
author wenzelm
Thu Jul 02 17:26:47 1998 +0200 (1998-07-02)
changeset 5112 9e74cf11e4a4
parent 5037 224887671646
child 5285 2d1425492fb3
permissions -rw-r--r--
Symbol.beginning;
     1 (*  Title:      Pure/library.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Copyright   1992  University of Cambridge
     5 
     6 Basic library: functions, options, pairs, booleans, lists, integers,
     7 strings, lists as sets, association lists, generic tables, balanced
     8 trees, orders, I/O and diagnostics, timing, misc.
     9 *)
    10 
    11 infix |> ~~ \ \\ ins ins_string ins_int orf andf prefix upto downto
    12   mem mem_int mem_string union union_int union_string inter inter_int
    13   inter_string subset subset_int subset_string;
    14 
    15 signature LIBRARY =
    16 sig
    17   (*functions*)
    18   val curry: ('a * 'b -> 'c) -> 'a -> 'b -> 'c
    19   val uncurry: ('a -> 'b -> 'c) -> 'a * 'b -> 'c
    20   val I: 'a -> 'a
    21   val K: 'a -> 'b -> 'a
    22   val |> : 'a * ('a -> 'b) -> 'b
    23   val apl: 'a * ('a * 'b -> 'c) -> 'b -> 'c
    24   val apr: ('a * 'b -> 'c) * 'b -> 'a -> 'c
    25   val funpow: int -> ('a -> 'a) -> 'a -> 'a
    26 
    27   (*stamps*)
    28   type stamp
    29   val stamp: unit -> stamp
    30 
    31   (*options*)
    32   datatype 'a option = None | Some of 'a
    33   exception OPTION
    34   val the: 'a option -> 'a
    35   val if_none: 'a option -> 'a -> 'a
    36   val is_some: 'a option -> bool
    37   val is_none: 'a option -> bool
    38   val apsome: ('a -> 'b) -> 'a option -> 'b option
    39   val can: ('a -> 'b) -> 'a -> bool
    40   val try: ('a -> 'b) -> 'a -> 'b option
    41 
    42   (*pairs*)
    43   val pair: 'a -> 'b -> 'a * 'b
    44   val rpair: 'a -> 'b -> 'b * 'a
    45   val fst: 'a * 'b -> 'a
    46   val snd: 'a * 'b -> 'b
    47   val eq_fst: (''a * 'b) * (''a * 'c) -> bool
    48   val eq_snd: ('a * ''b) * ('c * ''b) -> bool
    49   val swap: 'a * 'b -> 'b * 'a
    50   val apfst: ('a -> 'b) -> 'a * 'c -> 'b * 'c
    51   val apsnd: ('a -> 'b) -> 'c * 'a -> 'c * 'b
    52   val pairself: ('a -> 'b) -> 'a * 'a -> 'b * 'b
    53 
    54   (*booleans*)
    55   val equal: ''a -> ''a -> bool
    56   val not_equal: ''a -> ''a -> bool
    57   val orf: ('a -> bool) * ('a -> bool) -> 'a -> bool
    58   val andf: ('a -> bool) * ('a -> bool) -> 'a -> bool
    59   val exists: ('a -> bool) -> 'a list -> bool
    60   val forall: ('a -> bool) -> 'a list -> bool
    61   val set: bool ref -> bool
    62   val reset: bool ref -> bool
    63   val toggle: bool ref -> bool
    64   val setmp: 'a ref -> 'a -> ('b -> 'c) -> 'b -> 'c
    65 
    66   (*lists*)
    67   exception LIST of string
    68   val null: 'a list -> bool
    69   val hd: 'a list -> 'a
    70   val tl: 'a list -> 'a list
    71   val cons: 'a -> 'a list -> 'a list
    72   val append: 'a list -> 'a list -> 'a list
    73   val foldl: ('a * 'b -> 'a) -> 'a * 'b list -> 'a
    74   val foldr: ('a * 'b -> 'b) -> 'a list * 'b -> 'b
    75   val foldr1: ('a * 'a -> 'a) -> 'a list -> 'a
    76   val foldl_map: ('a * 'b -> 'a * 'c) -> 'a * 'b list -> 'a * 'c list
    77   val length: 'a list -> int
    78   val take: int * 'a list -> 'a list
    79   val drop: int * 'a list -> 'a list
    80   val dropwhile: ('a -> bool) -> 'a list -> 'a list
    81   val nth_elem: int * 'a list -> 'a
    82   val last_elem: 'a list -> 'a
    83   val split_last: 'a list -> 'a list * 'a
    84   val nth_update: 'a -> int * 'a list -> 'a list
    85   val find_index: ('a -> bool) -> 'a list -> int
    86   val find_index_eq: ''a -> ''a list -> int
    87   val find_first: ('a -> bool) -> 'a list -> 'a option
    88   val get_first: ('a -> 'b option) -> 'a list -> 'b option
    89   val flat: 'a list list -> 'a list
    90   val seq: ('a -> unit) -> 'a list -> unit
    91   val separate: 'a -> 'a list -> 'a list
    92   val replicate: int -> 'a -> 'a list
    93   val multiply: 'a list * 'a list list -> 'a list list
    94   val filter: ('a -> bool) -> 'a list -> 'a list
    95   val filter_out: ('a -> bool) -> 'a list -> 'a list
    96   val mapfilter: ('a -> 'b option) -> 'a list -> 'b list
    97   val map2: ('a * 'b -> 'c) -> 'a list * 'b list -> 'c list
    98   val exists2: ('a * 'b -> bool) -> 'a list * 'b list -> bool
    99   val forall2: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   100   val seq2: ('a * 'b -> unit) -> 'a list * 'b list -> unit
   101   val ~~ : 'a list * 'b list -> ('a * 'b) list
   102   val split_list: ('a * 'b) list -> 'a list * 'b list
   103   val prefix: ''a list * ''a list -> bool
   104   val take_prefix: ('a -> bool) -> 'a list -> 'a list * 'a list
   105   val take_suffix: ('a -> bool) -> 'a list -> 'a list * 'a list
   106 
   107   (*integers*)
   108   val inc: int ref -> int
   109   val dec: int ref -> int
   110   val upto: int * int -> int list
   111   val downto: int * int -> int list
   112   val downto0: int list * int -> bool
   113   val radixpand: int * int -> int list
   114   val radixstring: int * string * int -> string
   115   val string_of_int: int -> string
   116   val string_of_indexname: string * int -> string
   117 
   118   (*strings*)
   119   val enclose: string -> string -> string -> string
   120   val quote: string -> string
   121   val space_implode: string -> string list -> string
   122   val commas: string list -> string
   123   val commas_quote: string list -> string
   124   val cat_lines: string list -> string
   125   val space_explode: string -> string -> string list
   126   val split_lines: string -> string list
   127 
   128   (*lists as sets*)
   129   val mem: ''a * ''a list -> bool
   130   val mem_int: int * int list -> bool
   131   val mem_string: string * string list -> bool
   132   val gen_mem: ('a * 'b -> bool) -> 'a * 'b list -> bool
   133   val ins: ''a * ''a list -> ''a list
   134   val ins_int: int * int list -> int list
   135   val ins_string: string * string list -> string list
   136   val gen_ins: ('a * 'a -> bool) -> 'a * 'a list -> 'a list
   137   val union: ''a list * ''a list -> ''a list
   138   val union_int: int list * int list -> int list
   139   val union_string: string list * string list -> string list
   140   val gen_union: ('a * 'a -> bool) -> 'a list * 'a list -> 'a list
   141   val inter: ''a list * ''a list -> ''a list
   142   val inter_int: int list * int list -> int list
   143   val inter_string: string list * string list -> string list
   144   val subset: ''a list * ''a list -> bool
   145   val subset_int: int list * int list -> bool
   146   val subset_string: string list * string list -> bool
   147   val eq_set: ''a list * ''a list -> bool
   148   val eq_set_string: string list * string list -> bool
   149   val gen_subset: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   150   val \ : ''a list * ''a -> ''a list
   151   val \\ : ''a list * ''a list -> ''a list
   152   val gen_rem: ('a * 'b -> bool) -> 'a list * 'b -> 'a list
   153   val gen_rems: ('a * 'b -> bool) -> 'a list * 'b list -> 'a list
   154   val gen_distinct: ('a * 'a -> bool) -> 'a list -> 'a list
   155   val distinct: ''a list -> ''a list
   156   val findrep: ''a list -> ''a list
   157   val gen_duplicates: ('a * 'a -> bool) -> 'a list -> 'a list
   158   val duplicates: ''a list -> ''a list
   159 
   160   (*association lists*)
   161   val assoc: (''a * 'b) list * ''a -> 'b option
   162   val assoc_int: (int * 'a) list * int -> 'a option
   163   val assoc_string: (string * 'a) list * string -> 'a option
   164   val assoc_string_int: ((string * int) * 'a) list * (string * int) -> 'a option
   165   val assocs: (''a * 'b list) list -> ''a -> 'b list
   166   val assoc2: (''a * (''b * 'c) list) list * (''a * ''b) -> 'c option
   167   val gen_assoc: ('a * 'b -> bool) -> ('b * 'c) list * 'a -> 'c option
   168   val overwrite: (''a * 'b) list * (''a * 'b) -> (''a * 'b) list
   169   val gen_overwrite: ('a * 'a -> bool) -> ('a * 'b) list * ('a * 'b) -> ('a * 'b) list
   170 
   171   (*generic tables*)
   172   val generic_extend: ('a * 'a -> bool)
   173     -> ('b -> 'a list) -> ('a list -> 'b) -> 'b -> 'a list -> 'b
   174   val generic_merge: ('a * 'a -> bool) -> ('b -> 'a list) -> ('a list -> 'b) -> 'b -> 'b -> 'b
   175   val extend_list: ''a list -> ''a list -> ''a list
   176   val merge_lists: ''a list -> ''a list -> ''a list
   177   val merge_alists: (''a * 'b) list -> (''a * 'b) list -> (''a * 'b) list
   178   val merge_rev_lists: ''a list -> ''a list -> ''a list
   179 
   180   (*balanced trees*)
   181   exception Balance
   182   val fold_bal: ('a * 'a -> 'a) -> 'a list -> 'a
   183   val access_bal: ('a -> 'a) * ('a -> 'a) * 'a -> int -> int -> 'a
   184   val accesses_bal: ('a -> 'a) * ('a -> 'a) * 'a -> int -> 'a list
   185 
   186   (*orders*)
   187   datatype order = EQUAL | GREATER | LESS
   188   val rev_order: order -> order
   189   val make_ord: ('a * 'a -> bool) -> 'a * 'a -> order
   190   val int_ord: int * int -> order
   191   val string_ord: string * string -> order
   192   val prod_ord: ('a * 'b -> order) -> ('c * 'd -> order) -> ('a * 'c) * ('b * 'd) -> order
   193   val dict_ord: ('a * 'b -> order) -> 'a list * 'b list -> order
   194   val list_ord: ('a * 'b -> order) -> 'a list * 'b list -> order
   195   val sort: ('a * 'a -> order) -> 'a list -> 'a list
   196   val sort_strings: string list -> string list
   197   val sort_wrt: ('a -> string) -> 'a list -> 'a list
   198 
   199   (*I/O and diagnostics*)
   200   val cd: string -> unit
   201   val pwd: unit -> string
   202   val prs_fn: (string -> unit) ref
   203   val warning_fn: (string -> unit) ref
   204   val error_fn: (string -> unit) ref
   205   val prs: string -> unit
   206   val writeln: string -> unit
   207   val warning: string -> unit
   208   exception ERROR
   209   val error_msg: string -> unit
   210   val error: string -> 'a
   211   val sys_error: string -> 'a
   212   val assert: bool -> string -> unit
   213   val deny: bool -> string -> unit
   214   val assert_all: ('a -> bool) -> 'a list -> ('a -> string) -> unit
   215   datatype 'a error = Error of string | OK of 'a
   216   val get_error: 'a error -> string option
   217   val get_ok: 'a error -> 'a option
   218   val handle_error: ('a -> 'b) -> 'a -> 'b error
   219   exception ERROR_MESSAGE of string
   220   val transform_error: ('a -> 'b) -> 'a -> 'b
   221 
   222   (*timing*)
   223   val cond_timeit: bool -> (unit -> 'a) -> 'a
   224   val timeit: (unit -> 'a) -> 'a
   225   val timeap: ('a -> 'b) -> 'a -> 'b
   226 
   227   (*misc*)
   228   val make_keylist: ('a -> 'b) -> 'a list -> ('a * 'b) list
   229   val keyfilter: ('a * ''b) list -> ''b -> 'a list
   230   val partition: ('a -> bool) -> 'a list -> 'a list * 'a list
   231   val partition_eq: ('a * 'a -> bool) -> 'a list -> 'a list list
   232   val partition_list: (int -> 'a -> bool) -> int -> int -> 'a list -> 'a list list
   233   val transitive_closure: (string * string list) list -> (string * string list) list
   234   val init_gensym: unit -> unit
   235   val gensym: string -> string
   236   val bump_int_list: string list -> string list
   237   val bump_list: string list * string -> string list
   238   val bump_string: string -> string
   239   val scanwords: (string -> bool) -> string list -> string list
   240   datatype 'a mtree = Join of 'a * 'a mtree list
   241 end;
   242 
   243 structure Library: LIBRARY =
   244 struct
   245 
   246 
   247 (** functions **)
   248 
   249 (*handy combinators*)
   250 fun curry f x y = f (x, y);
   251 fun uncurry f (x, y) = f x y;
   252 fun I x = x;
   253 fun K x y = x;
   254 
   255 (*reverse apply*)
   256 fun (x |> f) = f x;
   257 
   258 (*application of (infix) operator to its left or right argument*)
   259 fun apl (x, f) y = f (x, y);
   260 fun apr (f, y) x = f (x, y);
   261 
   262 (*function exponentiation: f(...(f x)...) with n applications of f*)
   263 fun funpow n f x =
   264   let fun rep (0, x) = x
   265         | rep (n, x) = rep (n - 1, f x)
   266   in rep (n, x) end;
   267 
   268 
   269 
   270 (** stamps **)
   271 
   272 type stamp = unit ref;
   273 val stamp: unit -> stamp = ref;
   274 
   275 
   276 
   277 (** options **)
   278 
   279 datatype 'a option = None | Some of 'a;
   280 
   281 exception OPTION;
   282 
   283 fun the (Some x) = x
   284   | the None = raise OPTION;
   285 
   286 (*strict!*)
   287 fun if_none None y = y
   288   | if_none (Some x) _ = x;
   289 
   290 fun is_some (Some _) = true
   291   | is_some None = false;
   292 
   293 fun is_none (Some _) = false
   294   | is_none None = true;
   295 
   296 fun apsome f (Some x) = Some (f x)
   297   | apsome _ None = None;
   298 
   299 (*handle partial functions*)
   300 fun can f x = (f x; true) handle _ => false;
   301 fun try f x = Some (f x) handle _ => None;
   302 
   303 
   304 
   305 (** pairs **)
   306 
   307 fun pair x y = (x, y);
   308 fun rpair x y = (y, x);
   309 
   310 fun fst (x, y) = x;
   311 fun snd (x, y) = y;
   312 
   313 fun eq_fst ((x1, _), (x2, _)) = x1 = x2;
   314 fun eq_snd ((_, y1), (_, y2)) = y1 = y2;
   315 
   316 fun swap (x, y) = (y, x);
   317 
   318 (*apply function to components*)
   319 fun apfst f (x, y) = (f x, y);
   320 fun apsnd f (x, y) = (x, f y);
   321 fun pairself f (x, y) = (f x, f y);
   322 
   323 
   324 
   325 (** booleans **)
   326 
   327 (* equality *)
   328 
   329 fun equal x y = x = y;
   330 fun not_equal x y = x <> y;
   331 
   332 
   333 (* operators for combining predicates *)
   334 
   335 fun (p orf q) = fn x => p x orelse q x;
   336 fun (p andf q) = fn x => p x andalso q x;
   337 
   338 
   339 (* predicates on lists *)
   340 
   341 (*exists pred [x1, ..., xn] ===> pred x1 orelse ... orelse pred xn*)
   342 fun exists (pred: 'a -> bool) : 'a list -> bool =
   343   let fun boolf [] = false
   344         | boolf (x :: xs) = pred x orelse boolf xs
   345   in boolf end;
   346 
   347 (*forall pred [x1, ..., xn] ===> pred x1 andalso ... andalso pred xn*)
   348 fun forall (pred: 'a -> bool) : 'a list -> bool =
   349   let fun boolf [] = true
   350         | boolf (x :: xs) = pred x andalso boolf xs
   351   in boolf end;
   352 
   353 
   354 (* flags *)
   355 
   356 fun set flag = (flag := true; true);
   357 fun reset flag = (flag := false; false);
   358 fun toggle flag = (flag := not (! flag); ! flag);
   359 
   360 (*temporarily set flag, handling errors*)
   361 fun setmp flag value f x =
   362   let
   363     val orig_value = ! flag;
   364     fun return y = (flag := orig_value; y);
   365   in
   366     flag := value;
   367     return (f x handle exn => (return (); raise exn))
   368   end;
   369 
   370 
   371 
   372 (** lists **)
   373 
   374 exception LIST of string;
   375 
   376 fun null [] = true
   377   | null (_ :: _) = false;
   378 
   379 fun hd [] = raise LIST "hd"
   380   | hd (x :: _) = x;
   381 
   382 fun tl [] = raise LIST "tl"
   383   | tl (_ :: xs) = xs;
   384 
   385 fun cons x xs = x :: xs;
   386 
   387 fun append xs ys = xs @ ys;
   388 
   389 
   390 (* fold *)
   391 
   392 (*the following versions of fold are designed to fit nicely with infixes*)
   393 
   394 (*  (op @) (e, [x1, ..., xn])  ===>  ((e @ x1) @ x2) ... @ xn
   395     for operators that associate to the left (TAIL RECURSIVE)*)
   396 fun foldl (f: 'a * 'b -> 'a) : 'a * 'b list -> 'a =
   397   let fun itl (e, [])  = e
   398         | itl (e, a::l) = itl (f(e, a), l)
   399   in  itl end;
   400 
   401 (*  (op @) ([x1, ..., xn], e)  ===>   x1 @ (x2 ... @ (xn @ e))
   402     for operators that associate to the right (not tail recursive)*)
   403 fun foldr f (l, e) =
   404   let fun itr [] = e
   405         | itr (a::l) = f(a, itr l)
   406   in  itr l  end;
   407 
   408 (*  (op @) [x1, ..., xn]  ===>   x1 @ (x2 ... @ (x[n-1] @ xn))
   409     for n > 0, operators that associate to the right (not tail recursive)*)
   410 fun foldr1 f l =
   411   let fun itr [x] = x
   412         | itr (x::l) = f(x, itr l)
   413   in  itr l  end;
   414 
   415 fun foldl_map _ (x, []) = (x, [])
   416   | foldl_map f (x, y :: ys) =
   417       let
   418         val (x', y') = f (x, y);
   419         val (x'', ys') = foldl_map f (x', ys);
   420       in (x'', y' :: ys') end;
   421 
   422 
   423 (* basic list functions *)
   424 
   425 (*length of a list, should unquestionably be a standard function*)
   426 local fun length1 (n, [])  = n   (*TAIL RECURSIVE*)
   427         | length1 (n, x :: xs) = length1 (n + 1, xs)
   428 in  fun length l = length1 (0, l) end;
   429 
   430 (*take the first n elements from a list*)
   431 fun take (n, []) = []
   432   | take (n, x :: xs) =
   433       if n > 0 then x :: take (n - 1, xs) else [];
   434 
   435 (*drop the first n elements from a list*)
   436 fun drop (n, []) = []
   437   | drop (n, x :: xs) =
   438       if n > 0 then drop (n - 1, xs) else x :: xs;
   439 
   440 fun dropwhile P [] = []
   441   | dropwhile P (ys as x::xs) = if P x then dropwhile P xs else ys;
   442 
   443 (*return nth element of a list, where 0 designates the first element;
   444   raise EXCEPTION if list too short*)
   445 fun nth_elem NL =
   446   (case drop NL of
   447     [] => raise LIST "nth_elem"
   448   | x :: _ => x);
   449 
   450 (*last element of a list*)
   451 fun last_elem [] = raise LIST "last_elem"
   452   | last_elem [x] = x
   453   | last_elem (_ :: xs) = last_elem xs;
   454 
   455 (*rear decomposition*)
   456 fun split_last [] = raise LIST "split_last"
   457   | split_last [x] = ([], x)
   458   | split_last (x :: xs) = apfst (cons x) (split_last xs);
   459 
   460 (*update nth element*)
   461 fun nth_update x (n, xs) =
   462   let
   463     val prfx = take (n, xs);
   464     val sffx = drop (n, xs);
   465   in
   466     (case sffx of
   467       [] => raise LIST "nth_update"
   468     | _ :: sffx' => prfx @ (x :: sffx'))
   469   end;
   470 
   471 (*find the position of an element in a list*)
   472 fun find_index pred =
   473   let fun find _ [] = ~1
   474         | find n (x :: xs) = if pred x then n else find (n + 1) xs;
   475   in find 0 end;
   476 
   477 fun find_index_eq x = find_index (equal x);
   478 
   479 (*find first element satisfying predicate*)
   480 fun find_first _ [] = None
   481   | find_first pred (x :: xs) =
   482       if pred x then Some x else find_first pred xs;
   483 
   484 (*get first element by lookup function*)
   485 fun get_first _ [] = None
   486   | get_first f (x :: xs) =
   487       (case f x of
   488         None => get_first f xs
   489       | some => some);
   490 
   491 (*flatten a list of lists to a list*)
   492 fun flat (ls: 'c list list) : 'c list = foldr (op @) (ls, []);
   493 
   494 (*like Lisp's MAPC -- seq proc [x1, ..., xn] evaluates
   495   (proc x1; ...; proc xn) for side effects*)
   496 fun seq (proc: 'a -> unit) : 'a list -> unit =
   497   let fun seqf [] = ()
   498         | seqf (x :: xs) = (proc x; seqf xs)
   499   in seqf end;
   500 
   501 (*separate s [x1, x2, ..., xn]  ===>  [x1, s, x2, s, ..., s, xn]*)
   502 fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
   503   | separate _ xs = xs;
   504 
   505 (*make the list [x, x, ..., x] of length n*)
   506 fun replicate n (x: 'a) : 'a list =
   507   let fun rep (0, xs) = xs
   508         | rep (n, xs) = rep (n - 1, x :: xs)
   509   in
   510     if n < 0 then raise LIST "replicate"
   511     else rep (n, [])
   512   end;
   513 
   514 (*multiply [a, b, c, ...] * [xs, ys, zs, ...]*)
   515 fun multiply ([], _) = []
   516   | multiply (x :: xs, yss) = map (cons x) yss @ multiply (xs, yss);
   517 
   518 
   519 (* filter *)
   520 
   521 (*copy the list preserving elements that satisfy the predicate*)
   522 fun filter (pred: 'a->bool) : 'a list -> 'a list =
   523   let fun filt [] = []
   524         | filt (x :: xs) = if pred x then x :: filt xs else filt xs
   525   in filt end;
   526 
   527 fun filter_out f = filter (not o f);
   528 
   529 fun mapfilter (f: 'a -> 'b option) ([]: 'a list) = [] : 'b list
   530   | mapfilter f (x :: xs) =
   531       (case f x of
   532         None => mapfilter f xs
   533       | Some y => y :: mapfilter f xs);
   534 
   535 
   536 (* lists of pairs *)
   537 
   538 fun map2 _ ([], []) = []
   539   | map2 f (x :: xs, y :: ys) = (f (x, y) :: map2 f (xs, ys))
   540   | map2 _ _ = raise LIST "map2";
   541 
   542 fun exists2 _ ([], []) = false
   543   | exists2 pred (x :: xs, y :: ys) = pred (x, y) orelse exists2 pred (xs, ys)
   544   | exists2 _ _ = raise LIST "exists2";
   545 
   546 fun forall2 _ ([], []) = true
   547   | forall2 pred (x :: xs, y :: ys) = pred (x, y) andalso forall2 pred (xs, ys)
   548   | forall2 _ _ = raise LIST "forall2";
   549 
   550 fun seq2 _ ([], []) = ()
   551   | seq2 f (x :: xs, y :: ys) = (f (x, y); seq2 f (xs, ys))
   552   | seq2 _ _ = raise LIST "seq2";
   553 
   554 (*combine two lists forming a list of pairs:
   555   [x1, ..., xn] ~~ [y1, ..., yn]  ===>  [(x1, y1), ..., (xn, yn)]*)
   556 fun [] ~~ [] = []
   557   | (x :: xs) ~~ (y :: ys) = (x, y) :: (xs ~~ ys)
   558   | _ ~~ _ = raise LIST "~~";
   559 
   560 (*inverse of ~~; the old 'split':
   561   [(x1, y1), ..., (xn, yn)]  ===>  ([x1, ..., xn], [y1, ..., yn])*)
   562 fun split_list (l: ('a * 'b) list) = (map #1 l, map #2 l);
   563 
   564 
   565 (* prefixes, suffixes *)
   566 
   567 fun [] prefix _ = true
   568   | (x :: xs) prefix (y :: ys) = x = y andalso (xs prefix ys)
   569   | _ prefix _ = false;
   570 
   571 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., x(i-1)], [xi, ..., xn])
   572    where xi is the first element that does not satisfy the predicate*)
   573 fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
   574   let fun take (rxs, []) = (rev rxs, [])
   575         | take (rxs, x :: xs) =
   576             if  pred x  then  take(x :: rxs, xs)  else  (rev rxs, x :: xs)
   577   in  take([], xs)  end;
   578 
   579 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., xi], [x(i+1), ..., xn])
   580    where xi is the last element that does not satisfy the predicate*)
   581 fun take_suffix _ [] = ([], [])
   582   | take_suffix pred (x :: xs) =
   583       (case take_suffix pred xs of
   584         ([], sffx) => if pred x then ([], x :: sffx) else ([x], sffx)
   585       | (prfx, sffx) => (x :: prfx, sffx));
   586 
   587 
   588 
   589 (** integers **)
   590 
   591 fun inc i = (i := ! i + 1; ! i);
   592 fun dec i = (i := ! i - 1; ! i);
   593 
   594 
   595 (* lists of integers *)
   596 
   597 (*make the list [from, from + 1, ..., to]*)
   598 fun (from upto to) =
   599   if from > to then [] else from :: ((from + 1) upto to);
   600 
   601 (*make the list [from, from - 1, ..., to]*)
   602 fun (from downto to) =
   603   if from < to then [] else from :: ((from - 1) downto to);
   604 
   605 (*predicate: downto0 (is, n) <=> is = [n, n - 1, ..., 0]*)
   606 fun downto0 (i :: is, n) = i = n andalso downto0 (is, n - 1)
   607   | downto0 ([], n) = n = ~1;
   608 
   609 
   610 (* convert integers to strings *)
   611 
   612 (*expand the number in the given base;
   613   example: radixpand (2, 8) gives [1, 0, 0, 0]*)
   614 fun radixpand (base, num) : int list =
   615   let
   616     fun radix (n, tail) =
   617       if n < base then n :: tail
   618       else radix (n div base, (n mod base) :: tail)
   619   in radix (num, []) end;
   620 
   621 (*expands a number into a string of characters starting from "zerochar";
   622   example: radixstring (2, "0", 8) gives "1000"*)
   623 fun radixstring (base, zerochar, num) =
   624   let val offset = ord zerochar;
   625       fun chrof n = chr (offset + n)
   626   in implode (map chrof (radixpand (base, num))) end;
   627 
   628 
   629 val string_of_int = Int.toString;
   630 
   631 fun string_of_indexname (a,0) = a
   632   | string_of_indexname (a,i) = a ^ "_" ^ Int.toString i;
   633 
   634 
   635 
   636 (** strings **)
   637 
   638 (*enclose in brackets*)
   639 fun enclose lpar rpar str = lpar ^ str ^ rpar;
   640 
   641 (*simple quoting (does not escape special chars)*)
   642 val quote = enclose "\"" "\"";
   643 
   644 (*space_implode "..." (explode "hello") = "h...e...l...l...o"*)
   645 fun space_implode a bs = implode (separate a bs);
   646 
   647 val commas = space_implode ", ";
   648 val commas_quote = commas o map quote;
   649 
   650 (*concatenate messages, one per line, into a string*)
   651 val cat_lines = space_implode "\n";
   652 
   653 (*space_explode "." "h.e..l.lo" = ["h", "e", "", "l", "lo"]*)
   654 fun space_explode _ "" = []
   655   | space_explode sep str =
   656       let
   657         fun expl chs =
   658           (case take_prefix (not_equal sep) chs of
   659             (cs, []) => [implode cs]
   660           | (cs, _ :: cs') => implode cs :: expl cs');
   661       in expl (explode str) end;
   662 
   663 val split_lines = space_explode "\n";
   664 
   665 
   666 
   667 (** lists as sets **)
   668 
   669 (*membership in a list*)
   670 fun x mem [] = false
   671   | x mem (y :: ys) = x = y orelse x mem ys;
   672 
   673 (*membership in a list, optimized version for ints*)
   674 fun (x:int) mem_int [] = false
   675   | x mem_int (y :: ys) = x = y orelse x mem_int ys;
   676 
   677 (*membership in a list, optimized version for strings*)
   678 fun (x:string) mem_string [] = false
   679   | x mem_string (y :: ys) = x = y orelse x mem_string ys;
   680 
   681 (*generalized membership test*)
   682 fun gen_mem eq (x, []) = false
   683   | gen_mem eq (x, y :: ys) = eq (x, y) orelse gen_mem eq (x, ys);
   684 
   685 
   686 (*insertion into list if not already there*)
   687 fun (x ins xs) = if x mem xs then xs else x :: xs;
   688 
   689 (*insertion into list, optimized version for ints*)
   690 fun (x ins_int xs) = if x mem_int xs then xs else x :: xs;
   691 
   692 (*insertion into list, optimized version for strings*)
   693 fun (x ins_string xs) = if x mem_string xs then xs else x :: xs;
   694 
   695 (*generalized insertion*)
   696 fun gen_ins eq (x, xs) = if gen_mem eq (x, xs) then xs else x :: xs;
   697 
   698 
   699 (*union of sets represented as lists: no repetitions*)
   700 fun xs union [] = xs
   701   | [] union ys = ys
   702   | (x :: xs) union ys = xs union (x ins ys);
   703 
   704 (*union of sets, optimized version for ints*)
   705 fun (xs:int list) union_int [] = xs
   706   | [] union_int ys = ys
   707   | (x :: xs) union_int ys = xs union_int (x ins_int ys);
   708 
   709 (*union of sets, optimized version for strings*)
   710 fun (xs:string list) union_string [] = xs
   711   | [] union_string ys = ys
   712   | (x :: xs) union_string ys = xs union_string (x ins_string ys);
   713 
   714 (*generalized union*)
   715 fun gen_union eq (xs, []) = xs
   716   | gen_union eq ([], ys) = ys
   717   | gen_union eq (x :: xs, ys) = gen_union eq (xs, gen_ins eq (x, ys));
   718 
   719 
   720 (*intersection*)
   721 fun [] inter ys = []
   722   | (x :: xs) inter ys =
   723       if x mem ys then x :: (xs inter ys) else xs inter ys;
   724 
   725 (*intersection, optimized version for ints*)
   726 fun ([]:int list) inter_int ys = []
   727   | (x :: xs) inter_int ys =
   728       if x mem_int ys then x :: (xs inter_int ys) else xs inter_int ys;
   729 
   730 (*intersection, optimized version for strings *)
   731 fun ([]:string list) inter_string ys = []
   732   | (x :: xs) inter_string ys =
   733       if x mem_string ys then x :: (xs inter_string ys) else xs inter_string ys;
   734 
   735 
   736 (*subset*)
   737 fun [] subset ys = true
   738   | (x :: xs) subset ys = x mem ys andalso xs subset ys;
   739 
   740 (*subset, optimized version for ints*)
   741 fun ([]:int list) subset_int ys = true
   742   | (x :: xs) subset_int ys = x mem_int ys andalso xs subset_int ys;
   743 
   744 (*subset, optimized version for strings*)
   745 fun ([]:string list) subset_string ys = true
   746   | (x :: xs) subset_string ys = x mem_string ys andalso xs subset_string ys;
   747 
   748 (*set equality*)
   749 fun eq_set (xs, ys) =
   750   xs = ys orelse (xs subset ys andalso ys subset xs);
   751 
   752 (*set equality for strings*)
   753 fun eq_set_string ((xs:string list), ys) =
   754   xs = ys orelse (xs subset_string ys andalso ys subset_string xs);
   755 
   756 fun gen_subset eq (xs, ys) = forall (fn x => gen_mem eq (x, ys)) xs;
   757 
   758 
   759 (*removing an element from a list WITHOUT duplicates*)
   760 fun (y :: ys) \ x = if x = y then ys else y :: (ys \ x)
   761   | [] \ x = [];
   762 
   763 fun ys \\ xs = foldl (op \) (ys,xs);
   764 
   765 (*removing an element from a list -- possibly WITH duplicates*)
   766 fun gen_rem eq (xs, y) = filter_out (fn x => eq (x, y)) xs;
   767 
   768 fun gen_rems eq = foldl (gen_rem eq);
   769 
   770 
   771 (*makes a list of the distinct members of the input; preserves order, takes
   772   first of equal elements*)
   773 fun gen_distinct eq lst =
   774   let
   775     val memb = gen_mem eq;
   776 
   777     fun dist (rev_seen, []) = rev rev_seen
   778       | dist (rev_seen, x :: xs) =
   779           if memb (x, rev_seen) then dist (rev_seen, xs)
   780           else dist (x :: rev_seen, xs);
   781   in
   782     dist ([], lst)
   783   end;
   784 
   785 fun distinct l = gen_distinct (op =) l;
   786 
   787 
   788 (*returns the tail beginning with the first repeated element, or []*)
   789 fun findrep [] = []
   790   | findrep (x :: xs) = if x mem xs then x :: xs else findrep xs;
   791 
   792 
   793 (*returns a list containing all repeated elements exactly once; preserves
   794   order, takes first of equal elements*)
   795 fun gen_duplicates eq lst =
   796   let
   797     val memb = gen_mem eq;
   798 
   799     fun dups (rev_dups, []) = rev rev_dups
   800       | dups (rev_dups, x :: xs) =
   801           if memb (x, rev_dups) orelse not (memb (x, xs)) then
   802             dups (rev_dups, xs)
   803           else dups (x :: rev_dups, xs);
   804   in
   805     dups ([], lst)
   806   end;
   807 
   808 fun duplicates l = gen_duplicates (op =) l;
   809 
   810 
   811 
   812 (** association lists **)
   813 
   814 (*association list lookup*)
   815 fun assoc ([], key) = None
   816   | assoc ((keyi, xi) :: pairs, key) =
   817       if key = keyi then Some xi else assoc (pairs, key);
   818 
   819 (*association list lookup, optimized version for ints*)
   820 fun assoc_int ([], (key:int)) = None
   821   | assoc_int ((keyi, xi) :: pairs, key) =
   822       if key = keyi then Some xi else assoc_int (pairs, key);
   823 
   824 (*association list lookup, optimized version for strings*)
   825 fun assoc_string ([], (key:string)) = None
   826   | assoc_string ((keyi, xi) :: pairs, key) =
   827       if key = keyi then Some xi else assoc_string (pairs, key);
   828 
   829 (*association list lookup, optimized version for string*ints*)
   830 fun assoc_string_int ([], (key:string*int)) = None
   831   | assoc_string_int ((keyi, xi) :: pairs, key) =
   832       if key = keyi then Some xi else assoc_string_int (pairs, key);
   833 
   834 fun assocs ps x =
   835   (case assoc (ps, x) of
   836     None => []
   837   | Some ys => ys);
   838 
   839 (*two-fold association list lookup*)
   840 fun assoc2 (aal, (key1, key2)) =
   841   (case assoc (aal, key1) of
   842     Some al => assoc (al, key2)
   843   | None => None);
   844 
   845 (*generalized association list lookup*)
   846 fun gen_assoc eq ([], key) = None
   847   | gen_assoc eq ((keyi, xi) :: pairs, key) =
   848       if eq (key, keyi) then Some xi else gen_assoc eq (pairs, key);
   849 
   850 (*association list update*)
   851 fun overwrite (al, p as (key, _)) =
   852   let fun over ((q as (keyi, _)) :: pairs) =
   853             if keyi = key then p :: pairs else q :: (over pairs)
   854         | over [] = [p]
   855   in over al end;
   856 
   857 fun gen_overwrite eq (al, p as (key, _)) =
   858   let fun over ((q as (keyi, _)) :: pairs) =
   859             if eq (keyi, key) then p :: pairs else q :: (over pairs)
   860         | over [] = [p]
   861   in over al end;
   862 
   863 
   864 
   865 (** generic tables **)
   866 
   867 (*Tables are supposed to be 'efficient' encodings of lists of elements distinct
   868   wrt. an equality "eq". The extend and merge operations below are optimized
   869   for long-term space efficiency.*)
   870 
   871 (*append (new) elements to a table*)
   872 fun generic_extend _ _ _ tab [] = tab
   873   | generic_extend eq dest_tab mk_tab tab1 lst2 =
   874       let
   875         val lst1 = dest_tab tab1;
   876         val new_lst2 = gen_rems eq (lst2, lst1);
   877       in
   878         if null new_lst2 then tab1
   879         else mk_tab (lst1 @ new_lst2)
   880       end;
   881 
   882 (*append (new) elements of 2nd table to 1st table*)
   883 fun generic_merge eq dest_tab mk_tab tab1 tab2 =
   884   let
   885     val lst1 = dest_tab tab1;
   886     val lst2 = dest_tab tab2;
   887     val new_lst2 = gen_rems eq (lst2, lst1);
   888   in
   889     if null new_lst2 then tab1
   890     else if gen_subset eq (lst1, lst2) then tab2
   891     else mk_tab (lst1 @ new_lst2)
   892   end;
   893 
   894 
   895 (*lists as tables*)
   896 fun extend_list tab = generic_extend (op =) I I tab;
   897 fun merge_lists tab = generic_merge (op =) I I tab;
   898 fun merge_alists tab = generic_merge eq_fst I I tab;
   899 
   900 fun merge_rev_lists xs [] = xs
   901   | merge_rev_lists [] ys = ys
   902   | merge_rev_lists xs (y :: ys) =
   903       (if y mem xs then I else cons y) (merge_rev_lists xs ys);
   904 
   905 
   906 
   907 (** balanced trees **)
   908 
   909 exception Balance;      (*indicates non-positive argument to balancing fun*)
   910 
   911 (*balanced folding; avoids deep nesting*)
   912 fun fold_bal f [x] = x
   913   | fold_bal f [] = raise Balance
   914   | fold_bal f xs =
   915       let val k = length xs div 2
   916       in  f (fold_bal f (take(k, xs)),
   917              fold_bal f (drop(k, xs)))
   918       end;
   919 
   920 (*construct something of the form f(...g(...(x)...)) for balanced access*)
   921 fun access_bal (f, g, x) n i =
   922   let fun acc n i =     (*1<=i<=n*)
   923           if n=1 then x else
   924           let val n2 = n div 2
   925           in  if i<=n2 then f (acc n2 i)
   926                        else g (acc (n-n2) (i-n2))
   927           end
   928   in  if 1<=i andalso i<=n then acc n i else raise Balance  end;
   929 
   930 (*construct ALL such accesses; could try harder to share recursive calls!*)
   931 fun accesses_bal (f, g, x) n =
   932   let fun acc n =
   933           if n=1 then [x] else
   934           let val n2 = n div 2
   935               val acc2 = acc n2
   936           in  if n-n2=n2 then map f acc2 @ map g acc2
   937                          else map f acc2 @ map g (acc (n-n2)) end
   938   in  if 1<=n then acc n else raise Balance  end;
   939 
   940 
   941 
   942 (** orders **)
   943 
   944 datatype order = LESS | EQUAL | GREATER;
   945 
   946 fun rev_order LESS = GREATER
   947   | rev_order EQUAL = EQUAL
   948   | rev_order GREATER = LESS;
   949 
   950 (*assume rel is a linear strict order*)
   951 fun make_ord rel (x, y) =
   952   if rel (x, y) then LESS
   953   else if rel (y, x) then GREATER
   954   else EQUAL;
   955 
   956 fun int_ord (i, j: int) =
   957   if i < j then LESS
   958   else if i = j then EQUAL
   959   else GREATER;
   960 
   961 fun string_ord (a, b: string) =
   962   if a < b then LESS
   963   else if a = b then EQUAL
   964   else GREATER;
   965 
   966 (*lexicographic product*)
   967 fun prod_ord a_ord b_ord ((x, y), (x', y')) =
   968   (case a_ord (x, x') of EQUAL => b_ord (y, y') | ord => ord);
   969 
   970 (*dictionary order -- in general NOT well-founded!*)
   971 fun dict_ord _ ([], []) = EQUAL
   972   | dict_ord _ ([], _ :: _) = LESS
   973   | dict_ord _ (_ :: _, []) = GREATER
   974   | dict_ord elem_ord (x :: xs, y :: ys) =
   975       (case elem_ord (x, y) of EQUAL => dict_ord elem_ord (xs, ys) | ord => ord);
   976 
   977 (*lexicographic product of lists*)
   978 fun list_ord elem_ord (xs, ys) =
   979   prod_ord int_ord (dict_ord elem_ord) ((length xs, xs), (length ys, ys));
   980 
   981 
   982 (* sorting *)
   983 
   984 (*quicksort (stable, i.e. does not reorder equal elements)*)
   985 fun sort ord =
   986   let
   987     fun qsort xs =
   988       let val len = length xs in
   989         if len <= 1 then xs
   990         else
   991           let val (lts, eqs, gts) = part (nth_elem (len div 2, xs)) xs in
   992             qsort lts @ eqs @ qsort gts
   993           end
   994       end
   995     and part _ [] = ([], [], [])
   996       | part pivot (x :: xs) = add (ord (x, pivot)) x (part pivot xs)
   997     and add LESS x (lts, eqs, gts) = (x :: lts, eqs, gts)
   998       | add EQUAL x (lts, eqs, gts) = (lts, x :: eqs, gts)
   999       | add GREATER x (lts, eqs, gts) = (lts, eqs, x :: gts);
  1000   in qsort end;
  1001 
  1002 (*sort strings*)
  1003 val sort_strings = sort string_ord;
  1004 fun sort_wrt sel xs = sort (string_ord o pairself sel) xs;
  1005 
  1006 
  1007 
  1008 (** input / output and diagnostics **)
  1009 
  1010 val cd = OS.FileSys.chDir;
  1011 val pwd = OS.FileSys.getDir;
  1012 
  1013 
  1014 local
  1015   fun out s =
  1016     (TextIO.output (TextIO.stdOut, s); TextIO.flushOut TextIO.stdOut);
  1017 
  1018   fun prefix_lines prfx txt =
  1019     txt |> split_lines |> map (fn s => prfx ^ s ^ "\n") |> implode;
  1020 in
  1021 
  1022 (*hooks for output channels: normal, warning, error*)
  1023 val prs_fn = ref (fn s => out s);
  1024 val warning_fn = ref (fn s => out (prefix_lines "### " s));
  1025 val error_fn = ref (fn s => out (prefix_lines "*** " s));
  1026 
  1027 end;
  1028 
  1029 fun prs s = !prs_fn s;
  1030 fun writeln s = prs (s ^ "\n");
  1031 
  1032 fun warning s = !warning_fn s;
  1033 
  1034 (*print error message and abort to top level*)
  1035 exception ERROR;
  1036 fun error_msg s = !error_fn s;
  1037 fun error s = (error_msg s; raise ERROR);
  1038 fun sys_error msg = error ("## SYSTEM ERROR ##\n" ^ msg);
  1039 
  1040 fun assert p msg = if p then () else error msg;
  1041 fun deny p msg = if p then error msg else ();
  1042 
  1043 (*Assert pred for every member of l, generating a message if pred fails*)
  1044 fun assert_all pred l msg_fn =
  1045   let fun asl [] = ()
  1046         | asl (x::xs) = if pred x then asl xs else error (msg_fn x)
  1047   in asl l end;
  1048 
  1049 
  1050 (* handle errors capturing messages *)
  1051 
  1052 datatype 'a error =
  1053   Error of string |
  1054   OK of 'a;
  1055 
  1056 fun get_error (Error msg) = Some msg
  1057   | get_error _ = None;
  1058 
  1059 fun get_ok (OK x) = Some x
  1060   | get_ok _ = None;
  1061 
  1062 datatype 'a result =
  1063   Result of 'a |
  1064   Exn of exn;
  1065 
  1066 fun handle_error f x =
  1067   let
  1068     val buffer = ref ([]: string list);
  1069     fun capture s = buffer := ! buffer @ [s];
  1070     fun err_msg () = if not (null (! buffer)) then error_msg (cat_lines (! buffer)) else ();
  1071   in
  1072     (case Result (setmp error_fn capture f x) handle exn => Exn exn of
  1073       Result y => (err_msg (); OK y)
  1074     | Exn ERROR => Error (cat_lines (! buffer))
  1075     | Exn exn => (err_msg (); raise exn))
  1076   end;
  1077 
  1078 
  1079 (* transform ERROR into ERROR_MESSAGE *)
  1080 
  1081 exception ERROR_MESSAGE of string;
  1082 
  1083 fun transform_error f x =
  1084   (case handle_error f x of
  1085     OK y => y
  1086   | Error msg => raise ERROR_MESSAGE msg);
  1087 
  1088 
  1089 
  1090 (** timing **)
  1091 
  1092 (*a conditional timing function: applies f to () and, if the flag is true,
  1093   prints its runtime*)
  1094 fun cond_timeit flag f =
  1095   if flag then
  1096     let val start = startTiming()
  1097         val result = f ()
  1098     in
  1099 	writeln (endTiming start);  result
  1100     end
  1101   else f ();
  1102 
  1103 (*unconditional timing function*)
  1104 fun timeit x = cond_timeit true x;
  1105 
  1106 (*timed application function*)
  1107 fun timeap f x = timeit (fn () => f x);
  1108 
  1109 
  1110 
  1111 (** misc **)
  1112 
  1113 (*use the keyfun to make a list of (x, key) pairs*)
  1114 fun make_keylist (keyfun: 'a->'b) : 'a list -> ('a * 'b) list =
  1115   let fun keypair x = (x, keyfun x)
  1116   in map keypair end;
  1117 
  1118 (*given a list of (x, key) pairs and a searchkey
  1119   return the list of xs from each pair whose key equals searchkey*)
  1120 fun keyfilter [] searchkey = []
  1121   | keyfilter ((x, key) :: pairs) searchkey =
  1122       if key = searchkey then x :: keyfilter pairs searchkey
  1123       else keyfilter pairs searchkey;
  1124 
  1125 
  1126 (*Partition list into elements that satisfy predicate and those that don't.
  1127   Preserves order of elements in both lists.*)
  1128 fun partition (pred: 'a->bool) (ys: 'a list) : ('a list * 'a list) =
  1129     let fun part ([], answer) = answer
  1130           | part (x::xs, (ys, ns)) = if pred(x)
  1131             then  part (xs, (x::ys, ns))
  1132             else  part (xs, (ys, x::ns))
  1133     in  part (rev ys, ([], []))  end;
  1134 
  1135 
  1136 fun partition_eq (eq:'a * 'a -> bool) =
  1137     let fun part [] = []
  1138           | part (x::ys) = let val (xs, xs') = partition (apl(x, eq)) ys
  1139                            in (x::xs)::(part xs') end
  1140     in part end;
  1141 
  1142 
  1143 (*Partition a list into buckets  [ bi, b(i+1), ..., bj ]
  1144    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
  1145 fun partition_list p i j =
  1146   let fun part k xs =
  1147             if k>j then
  1148               (case xs of [] => []
  1149                          | _ => raise LIST "partition_list")
  1150             else
  1151             let val (ns, rest) = partition (p k) xs;
  1152             in  ns :: part(k+1)rest  end
  1153   in  part i end;
  1154 
  1155 
  1156 (* transitive closure (not Warshall's algorithm) *)
  1157 
  1158 fun transitive_closure [] = []
  1159   | transitive_closure ((x, ys)::ps) =
  1160       let val qs = transitive_closure ps
  1161           val zs = foldl (fn (zs, y) => assocs qs y union_string zs) (ys, ys)
  1162           fun step(u, us) = (u, if x mem_string us then zs union_string us 
  1163                                 else us)
  1164       in (x, zs) :: map step qs end;
  1165 
  1166 
  1167 (* generating identifiers *)
  1168 
  1169 (** Freshly generated identifiers; supplied prefix MUST start with a letter **)
  1170 local
  1171 (*Maps 0-63 to A-Z, a-z, 0-9 or _ or ' for generating random identifiers*)
  1172 fun char i =      if i<26 then chr (ord "A" + i)
  1173 	     else if i<52 then chr (ord "a" + i - 26)
  1174 	     else if i<62 then chr (ord"0" + i - 52)
  1175 	     else if i=62 then "_"
  1176 	     else  (*i=63*)    "'";
  1177 
  1178 val charVec = Vector.tabulate (64, char);
  1179 
  1180 fun newid n = 
  1181   let 
  1182   in  implode (map (fn i => Vector.sub(charVec,i)) (radixpand (64,n)))  end;
  1183 
  1184 val seedr = ref 0;
  1185 
  1186 in
  1187 
  1188 fun init_gensym() = (seedr := 0);
  1189 
  1190 fun gensym pre = pre ^ (#1(newid (!seedr), inc seedr));
  1191 end;
  1192 
  1193 
  1194 local
  1195 (*Identifies those character codes legal in identifiers.
  1196   chould use Basis Library character functions if Poly/ML provided characters*)
  1197 fun idCode k = (ord "a" <= k andalso k < ord "z") orelse 
  1198                (ord "A" <= k andalso k < ord "Z") orelse
  1199                (ord "0" <= k andalso k < ord "9");
  1200 
  1201 val idCodeVec = Vector.tabulate (256, idCode);
  1202 
  1203 in
  1204 
  1205 (*Increment a list of letters like a reversed base 26 number.
  1206   If head is "z", bumps chars in tail.
  1207   Digits are incremented as if they were integers.
  1208   "_" and "'" are not changed.
  1209   For making variants of identifiers.*)
  1210 
  1211 fun bump_int_list(c::cs) = 
  1212 	if c="9" then "0" :: bump_int_list cs 
  1213 	else
  1214         if "0" <= c andalso c < "9" then chr(ord(c)+1) :: cs
  1215         else "1" :: c :: cs
  1216   | bump_int_list([]) = error("bump_int_list: not an identifier");
  1217 
  1218 fun bump_list([], d) = [d]
  1219   | bump_list(["'"], d) = [d, "'"]
  1220   | bump_list("z"::cs, _) = "a" :: bump_list(cs, "a")
  1221   | bump_list("Z"::cs, _) = "A" :: bump_list(cs, "A")
  1222   | bump_list("9"::cs, _) = "0" :: bump_int_list cs
  1223   | bump_list(c::cs, _) = 
  1224         let val k = ord(c)
  1225         in if Vector.sub(idCodeVec,k) then chr(k+1) :: cs 
  1226 	   else
  1227            if c="'" orelse c="_" then c :: bump_list(cs, "") 
  1228 	   else error("bump_list: not legal in identifier: " ^
  1229 		      implode(rev(c::cs)))
  1230         end;
  1231 
  1232 end;
  1233 
  1234 fun bump_string s : string = implode (rev (bump_list(rev(explode s), "")));
  1235 
  1236 
  1237 (* lexical scanning *)
  1238 
  1239 (*scan a list of characters into "words" composed of "letters" (recognized by
  1240   is_let) and separated by any number of non-"letters"*)
  1241 fun scanwords is_let cs =
  1242   let fun scan1 [] = []
  1243         | scan1 cs =
  1244             let val (lets, rest) = take_prefix is_let cs
  1245             in implode lets :: scanwords is_let rest end;
  1246   in scan1 (#2 (take_prefix (not o is_let) cs)) end;
  1247 
  1248 
  1249 
  1250 (* Variable-branching trees: for proof terms etc. *)
  1251 datatype 'a mtree = Join of 'a * 'a mtree list;
  1252 
  1253 
  1254 end;
  1255 
  1256 open Library;