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