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