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