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