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