src/Pure/library.ML
changeset 0 a5a9c433f639
child 24 f3d4ff75d9f2
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/Pure/library.ML	Thu Sep 16 12:20:38 1993 +0200
     1.3 @@ -0,0 +1,585 @@
     1.4 +(*  Title: 	library
     1.5 +    ID:         $Id$
     1.6 +    Author: 	Lawrence C Paulson, Cambridge University Computer Laboratory
     1.7 +    Copyright   1992  University of Cambridge
     1.8 +
     1.9 +Basic library: booleans, lists, pairs, input/output, etc.
    1.10 +*)
    1.11 +
    1.12 +
    1.13 +(**** Booleans: operators for combining predicates ****)
    1.14 +
    1.15 +infix orf; 
    1.16 +fun p orf q = fn x => p x orelse q x ;
    1.17 +
    1.18 +infix andf; 
    1.19 +fun p andf q = fn x => p x andalso q x ;
    1.20 +
    1.21 +fun notf p x = not (p x) ;
    1.22 +
    1.23 +fun orl [] = false
    1.24 +  | orl (x::l) =  x  orelse  orl l;
    1.25 +
    1.26 +fun andl [] = true
    1.27 +  | andl (x::l) =  x  andalso  andl l;
    1.28 +
    1.29 +(*exists pred [x1,...,xn] ======>  pred(x1)  orelse  ...  orelse  pred(xn)*)
    1.30 +fun exists (pred: 'a -> bool) : 'a list -> bool = 
    1.31 +  let fun boolf [] = false
    1.32 +        | boolf (x::l) = (pred x) orelse boolf l
    1.33 +  in boolf end;
    1.34 +
    1.35 +(*forall pred [x1,...,xn] ======>  pred(x1)  andalso  ...  andalso  pred(xn)*)
    1.36 +fun forall (pred: 'a -> bool) : 'a list -> bool = 
    1.37 +  let fun boolf [] = true
    1.38 +        | boolf (x::l) = (pred x) andalso (boolf l)
    1.39 +  in boolf end;
    1.40 +
    1.41 +
    1.42 +(*** Lists ***)
    1.43 +
    1.44 +exception LIST of string;
    1.45 +
    1.46 +(*discriminator and selectors for lists. *)
    1.47 +fun null   []   = true
    1.48 +  | null (_::_) = false;
    1.49 +
    1.50 +fun hd   []   = raise LIST "hd"
    1.51 +  | hd (a::_) = a;
    1.52 +
    1.53 +fun tl   []   = raise LIST "tl"
    1.54 +  | tl (_::l) = l;
    1.55 +
    1.56 +
    1.57 +(*curried functions for pairing and reversed pairing*)
    1.58 +fun pair x y = (x,y);
    1.59 +fun rpair x y = (y,x);
    1.60 +
    1.61 +fun fst(x,y) = x and snd(x,y) = y;
    1.62 +
    1.63 +(*Handy combinators*)
    1.64 +fun curry f x y = f(x,y);
    1.65 +fun uncurry f(x,y) = f x y;
    1.66 +fun I x = x  and  K x y = x;
    1.67 +
    1.68 +(*Combine two functions forming the union of their domains*)
    1.69 +infix orelf;
    1.70 +fun f orelf g = fn x => f x  handle Match=> g x;
    1.71 +
    1.72 +
    1.73 +(*Application of (infix) operator to its left or right argument*)
    1.74 +fun apl (x,f) y = f(x,y);
    1.75 +fun apr (f,y) x = f(x,y);
    1.76 +
    1.77 +
    1.78 +(*functional for pairs*)
    1.79 +fun pairself f (x,y) = (f x, f y);
    1.80 +
    1.81 +(*Apply the function to a component of a pair*)
    1.82 +fun apfst f (x, y) = (f x, y);
    1.83 +fun apsnd f (x, y) = (x, f y);
    1.84 +
    1.85 +fun square (n: int) = n*n;
    1.86 +
    1.87 +fun fact 0 = 1
    1.88 +  | fact n = n * fact(n-1);
    1.89 +
    1.90 +
    1.91 +(*The following versions of fold are designed to fit nicely with infixes.*)
    1.92 +
    1.93 +(*  (op @) (e, [x1,...,xn])  ======>   ((e @ x1) @ x2) ... @ xn
    1.94 +    for operators that associate to the left.  TAIL RECURSIVE*)
    1.95 +fun foldl (f: 'a * 'b -> 'a) : 'a * 'b list -> 'a =
    1.96 +  let fun itl (e, [])  = e
    1.97 +        | itl (e, a::l) = itl (f(e,a), l)
    1.98 +  in  itl end;
    1.99 +
   1.100 +(*  (op @) ([x1,...,xn], e)  ======>   x1 @ (x2 ... @ (xn @ e))
   1.101 +    for operators that associate to the right.  Not tail recursive.*)
   1.102 +fun foldr f (l,e) =
   1.103 +  let fun itr [] = e
   1.104 +        | itr (a::l) = f(a, itr l)
   1.105 +  in  itr l  end;
   1.106 +
   1.107 +(*  (op @) [x1,...,xn]  ======>   x1 @ (x2 ..(x[n-1]. @ xn))
   1.108 +    for n>0, operators that associate to the right.  Not tail recursive.*)
   1.109 +fun foldr1 f l =
   1.110 +  let fun itr [x] = x
   1.111 +        | itr (x::l) = f(x, itr l)
   1.112 +  in  itr l  end;
   1.113 +
   1.114 +
   1.115 +(*Length of a list.  Should unquestionably be a standard function*)
   1.116 +local fun length1 (n, [ ])  = n   (*TAIL RECURSIVE*)
   1.117 +        | length1 (n, x::l) = length1 (n+1, l)   
   1.118 +in  fun length l = length1 (0,l) end;
   1.119 +
   1.120 +
   1.121 +(*Take the first n elements from l.*)
   1.122 +fun take (n, []) = []
   1.123 +  | take (n, x::xs) = if n>0 then x::take(n-1,xs)  
   1.124 +                      else  [];
   1.125 +
   1.126 +(*Drop the first n elements from l.*)
   1.127 +fun drop (_, [])    = []
   1.128 +  | drop (n, x::xs) = if n>0 then drop (n-1, xs) 
   1.129 +                             else x::xs;
   1.130 +
   1.131 +(*Return nth element of l, where 0 designates the first element;
   1.132 +  raise EXCEPTION if list too short.*)
   1.133 +fun nth_elem NL = case (drop NL) of
   1.134 +    []   => raise LIST "nth_elem" 
   1.135 +  | x::l => x;
   1.136 +
   1.137 +
   1.138 +(*make the list [from, from+1, ..., to]*)
   1.139 +infix upto;
   1.140 +fun from upto to =
   1.141 +    if from>to then []  else  from :: ((from+1) upto to);
   1.142 +
   1.143 +(*make the list [from, from-1, ..., to]*)
   1.144 +infix downto;
   1.145 +fun from downto to =
   1.146 +    if from<to then []  else  from :: ((from-1) downto to);
   1.147 +
   1.148 +(* predicate: downto0(is,n) <=> is = [n,n-1,...,0] *)
   1.149 +fun downto0(i::is,n) = i=n andalso downto0(is,n-1)
   1.150 +  | downto0([],n)    = n = ~1;
   1.151 +
   1.152 +(*Like Lisp's MAPC -- seq proc [x1,...,xn] evaluates 
   1.153 +  proc(x1); ... ; proc(xn) for side effects.*)
   1.154 +fun seq (proc: 'a -> unit) : 'a list -> unit = 
   1.155 +  let fun seqf []     = ()
   1.156 +        | seqf (x::l) = (proc x;  seqf l)
   1.157 +  in  seqf end;
   1.158 +
   1.159 +
   1.160 +(*** Balanced folding; access to balanced trees ***)
   1.161 +
   1.162 +exception Balance;	(*indicates non-positive argument to balancing fun*)
   1.163 +
   1.164 +(*Balanced folding; avoids deep nesting*)
   1.165 +fun fold_bal f [x] = x
   1.166 +  | fold_bal f [] = raise Balance
   1.167 +  | fold_bal f xs =
   1.168 +      let val k = length xs div 2
   1.169 +      in  f (fold_bal f (take(k,xs)),
   1.170 +	     fold_bal f (drop(k,xs)))  
   1.171 +      end;
   1.172 +
   1.173 +(*Construct something of the form f(...g(...(x)...)) for balanced access*)
   1.174 +fun access_bal (f,g,x) n i =
   1.175 +  let fun acc n i = 	(* 1<=i<=n*)
   1.176 +          if n=1 then x else
   1.177 +	  let val n2 = n div 2
   1.178 +	  in  if i<=n2 then f (acc n2 i) 
   1.179 +	               else g (acc (n-n2) (i-n2))
   1.180 +          end
   1.181 +  in  if 1<=i andalso i<=n then acc n i else raise Balance  end;
   1.182 +
   1.183 +(*Construct ALL such accesses; could try harder to share recursive calls!*)
   1.184 +fun accesses_bal (f,g,x) n =
   1.185 +  let fun acc n =  
   1.186 +          if n=1 then [x] else 
   1.187 +	  let val n2 = n div 2
   1.188 +	      val acc2 = acc n2
   1.189 +	  in  if n-n2=n2 then map f acc2 @ map g acc2
   1.190 +	                 else map f acc2 @ map g (acc (n-n2)) end
   1.191 +  in  if 1<=n then acc n else raise Balance  end;
   1.192 +
   1.193 +
   1.194 +(*** Input/Output ***)
   1.195 +
   1.196 +fun prs s = output(std_out,s);
   1.197 +fun writeln s = prs (s ^ "\n");
   1.198 +
   1.199 +(*Print error message and abort to top level*)
   1.200 +exception ERROR;
   1.201 +fun error (msg) = (writeln msg;  raise ERROR);
   1.202 +
   1.203 +fun assert p msg = if p then () else error msg;
   1.204 +fun deny p msg = if p then error msg else ();
   1.205 +
   1.206 +(*For the "test" target in Makefiles -- signifies successful termination*)
   1.207 +fun maketest msg = 
   1.208 +    (writeln msg;
   1.209 +     output(open_out "test", "Test examples ran successfully\n"));
   1.210 +
   1.211 +(*print a list surrounded by the brackets lpar and rpar, with comma separator
   1.212 +  print nothing for empty list*)
   1.213 +fun print_list (lpar, rpar, pre: 'a -> unit)  (l : 'a list) = 
   1.214 +    let fun prec(x) = (prs",";  pre(x)) 
   1.215 +    in  case l of
   1.216 +	    [] => () 
   1.217 +	  | x::l =>  (prs lpar;  pre x;  seq prec l;  prs rpar)
   1.218 +    end;
   1.219 +
   1.220 +(*print a list of items separated by newlines*)
   1.221 +fun print_list_ln (pre: 'a -> unit)  : 'a list -> unit = 
   1.222 +    seq (fn x => (pre x;  writeln""));
   1.223 +
   1.224 +fun is_letter ch =
   1.225 +  (ord"A" <= ord ch)  andalso  (ord ch <= ord"Z")   orelse
   1.226 +  (ord"a" <= ord ch)  andalso  (ord ch <= ord"z");
   1.227 +
   1.228 +fun is_digit ch =
   1.229 +  (ord"0" <= ord ch)  andalso  (ord ch <= ord"9");
   1.230 +
   1.231 +(*letter or _ or prime (') *)
   1.232 +fun is_quasi_letter "_" = true
   1.233 +  | is_quasi_letter "'" = true
   1.234 +  | is_quasi_letter ch  = is_letter ch;
   1.235 +
   1.236 +(*white space: blanks, tabs, newlines*)
   1.237 +val is_blank : string -> bool = fn
   1.238 +     " " => true  |  "\t" => true  |  "\n" => true  |  _ => false;
   1.239 +
   1.240 +val is_letdig = is_quasi_letter orf is_digit;
   1.241 +
   1.242 +val to_lower =
   1.243 +  let
   1.244 +    fun lower ch =
   1.245 +      if ch >= "A" andalso ch <= "Z" then
   1.246 +        chr (ord ch - ord "A" + ord "a")
   1.247 +      else ch;
   1.248 +  in
   1.249 +    implode o (map lower) o explode
   1.250 +  end;
   1.251 +
   1.252 +
   1.253 +(*** Timing ***)
   1.254 +
   1.255 +(*Unconditional timing function*)
   1.256 +val timeit = cond_timeit true;
   1.257 +
   1.258 +(*Timed application function*)
   1.259 +fun timeap f x = timeit(fn()=> f x);
   1.260 +
   1.261 +(*Timed "use" function, printing filenames*)
   1.262 +fun time_use fname = timeit(fn()=> 
   1.263 +   (writeln("\n**** Starting " ^ fname ^ " ****");  use fname;  
   1.264 +    writeln("\n**** Finished " ^ fname ^ " ****")));  
   1.265 +
   1.266 +
   1.267 +(*** Misc functions ***)
   1.268 +
   1.269 +(*Function exponentiation: f(...(f x)...) with n applications of f *)
   1.270 +fun funpow n f x =
   1.271 +  let fun rep (0,x) = x
   1.272 +        | rep (n,x) = rep (n-1, f x)
   1.273 +  in  rep (n,x)  end;
   1.274 +
   1.275 +(*Combine two lists forming a list of pairs:
   1.276 +  [x1,...,xn] ~~ [y1,...,yn]  ======>   [(x1,y1), ..., (xn,yn)] *)
   1.277 +infix ~~;
   1.278 +fun []   ~~  []   = []
   1.279 +  | (x::xs) ~~ (y::ys) = (x,y) :: (xs ~~ ys)
   1.280 +  |  _   ~~   _   = raise LIST "~~";
   1.281 +
   1.282 +(*Inverse of ~~;  the old 'split'.
   1.283 +   [(x1,y1), ..., (xn,yn)]  ======>  ( [x1,...,xn] , [y1,...,yn] ) *)
   1.284 +fun split_list (l: ('a*'b)list) = (map #1 l, map #2 l);
   1.285 +
   1.286 +(*make the list [x; x; ...; x] of length n*)
   1.287 +fun replicate n (x: 'a) : 'a list =
   1.288 +  let fun rep (0,xs) = xs
   1.289 +        | rep (n,xs) = rep(n-1, x::xs) 
   1.290 +  in   if n<0 then raise LIST "replicate"
   1.291 +       else rep (n,[])
   1.292 +  end;
   1.293 +
   1.294 +(*Flatten a list of lists to a list.*)
   1.295 +fun flat (ls: 'c list list) : 'c list = foldr (op @) (ls,[]);
   1.296 +
   1.297 +
   1.298 +(*** polymorphic set operations ***)
   1.299 +
   1.300 +(*membership in a list*)
   1.301 +infix mem;
   1.302 +fun x mem []  =  false
   1.303 +  | x mem (y::l)  =  (x=y) orelse (x mem l);
   1.304 +
   1.305 +(*insertion into list if not already there*)
   1.306 +infix ins;
   1.307 +fun x ins xs = if x mem xs then  xs   else  x::xs;
   1.308 +
   1.309 +(*union of sets represented as lists: no repetitions*)
   1.310 +infix union;
   1.311 +fun   xs    union [] = xs
   1.312 +  |   []    union ys = ys
   1.313 +  | (x::xs) union ys = xs union (x ins ys);
   1.314 +
   1.315 +infix inter;
   1.316 +fun   []    inter ys = []
   1.317 +  | (x::xs) inter ys = if x mem ys then x::(xs inter ys)
   1.318 +                                   else     xs inter ys;
   1.319 +
   1.320 +infix subset;
   1.321 +fun   []    subset ys = true
   1.322 +  | (x::xs) subset ys = x mem ys   andalso  xs subset ys;
   1.323 +
   1.324 +(*removing an element from a list WITHOUT duplicates*)
   1.325 +infix \;
   1.326 +fun (y::ys) \ x = if x=y then ys else y::(ys \ x)
   1.327 +  |   []    \ x = [];
   1.328 +
   1.329 +infix \\;
   1.330 +val op \\ = foldl (op \);
   1.331 +
   1.332 +(*** option stuff ***)
   1.333 +
   1.334 +datatype 'a option = None | Some of 'a;
   1.335 +
   1.336 +exception OPTION of string;
   1.337 +
   1.338 +fun the (Some x) = x
   1.339 +  | the None = raise OPTION "the";
   1.340 +
   1.341 +fun is_some (Some _) = true
   1.342 +  | is_some None = false;
   1.343 +
   1.344 +fun is_none (Some _) = false
   1.345 +  | is_none None = true;
   1.346 +
   1.347 +
   1.348 +(*** Association lists ***)
   1.349 +
   1.350 +(*Association list lookup*)
   1.351 +fun assoc ([], key) = None
   1.352 +  | assoc ((keyi,xi)::pairs, key) =
   1.353 +      if key=keyi then Some xi  else assoc (pairs,key);
   1.354 +
   1.355 +fun assocs ps x = case assoc(ps,x) of None => [] | Some(ys) => ys;
   1.356 +
   1.357 +(*Association list update*)
   1.358 +fun overwrite(al,p as (key,_)) =
   1.359 +  let fun over((q as (keyi,_))::pairs) =
   1.360 +	    if keyi=key then p::pairs else q::(over pairs)
   1.361 +	| over[] = [p]
   1.362 +  in over al end;
   1.363 +
   1.364 +(*Copy the list preserving elements that satisfy the predicate*)
   1.365 +fun filter (pred: 'a->bool) : 'a list -> 'a list = 
   1.366 +  let fun filt [] = []
   1.367 +        | filt (x::xs) =  if pred(x) then x :: filt xs  else  filt xs
   1.368 +  in  filt   end;
   1.369 +
   1.370 +fun filter_out f = filter (not o f);
   1.371 +
   1.372 +
   1.373 +(*** List operations, generalized to an arbitrary equality function "eq"
   1.374 +     -- so what good are equality types?? ***)
   1.375 +
   1.376 +(*removing an element from a list -- possibly WITH duplicates*)
   1.377 +fun gen_rem eq (xs,y) = filter_out (fn x => eq(x,y)) xs;
   1.378 +
   1.379 +(*generalized membership test*)
   1.380 +fun gen_mem eq (x, [])     =  false
   1.381 +  | gen_mem eq (x, y::ys)  =  eq(x,y) orelse gen_mem eq (x,ys);
   1.382 +
   1.383 +(*generalized insertion*)
   1.384 +fun gen_ins eq (x,xs) = if gen_mem eq (x,xs) then  xs   else  x::xs;
   1.385 +
   1.386 +(*generalized union*)
   1.387 +fun gen_union eq (xs,[]) = xs
   1.388 +  | gen_union eq ([],ys) = ys
   1.389 +  | gen_union eq (x::xs,ys) = gen_union eq (xs, gen_ins eq (x,ys));
   1.390 +
   1.391 +(*Generalized association list lookup*)
   1.392 +fun gen_assoc eq ([], key) = None
   1.393 +  | gen_assoc eq ((keyi,xi)::pairs, key) =
   1.394 +      if eq(key,keyi) then Some xi  else gen_assoc eq (pairs,key);
   1.395 +
   1.396 +(** Finding list elements and duplicates **)
   1.397 +
   1.398 +(* find the position of an element in a list *)
   1.399 +fun find(x,ys) =
   1.400 +    let fun f(y::ys,i) = if x=y then i else f(ys,i+1)
   1.401 +          | f(_,_) = raise LIST "find"
   1.402 +    in f(ys,0) end;
   1.403 +
   1.404 +(*Returns the tail beginning with the first repeated element, or []. *)
   1.405 +fun findrep [] = []
   1.406 +  | findrep (x::xs) = if  x mem xs  then  x::xs   else   findrep xs;
   1.407 +
   1.408 +fun distinct1 (seen, []) = rev seen
   1.409 +  | distinct1 (seen, x::xs) =
   1.410 +      if x mem seen then distinct1 (seen, xs)
   1.411 +    		    else distinct1 (x::seen, xs);
   1.412 +
   1.413 +(*Makes a list of the distinct members of the input*)
   1.414 +fun distinct xs = distinct1([],xs);
   1.415 +
   1.416 +
   1.417 +(*Use the keyfun to make a list of (x,key) pairs.*)
   1.418 +fun make_keylist (keyfun: 'a->'b) : 'a list -> ('a * 'b) list =
   1.419 +  let fun keypair x = (x, keyfun x) 
   1.420 +  in   map keypair  end;
   1.421 +
   1.422 +(*Given a list of (x,key) pairs and a searchkey
   1.423 +  return the list of xs from each pair whose key equals searchkey*)
   1.424 +fun keyfilter [] searchkey = []
   1.425 +  | keyfilter ((x,key)::pairs) searchkey = 
   1.426 +	if key=searchkey then x :: keyfilter pairs searchkey
   1.427 +	else keyfilter pairs searchkey;
   1.428 +
   1.429 +fun mapfilter (f: 'a -> 'b option) ([]: 'a list) = [] : 'b list
   1.430 +  | mapfilter f (x::xs) =
   1.431 +      case (f x) of
   1.432 +	  None => mapfilter f xs
   1.433 +	| Some y => y :: mapfilter f xs;
   1.434 +
   1.435 +
   1.436 +(*Partition list into elements that satisfy predicate and those that don't.
   1.437 +  Preserves order of elements in both lists. *)
   1.438 +fun partition (pred: 'a->bool) (ys: 'a list) : ('a list * 'a list) =
   1.439 +    let fun part ([], answer) = answer
   1.440 +	  | part (x::xs, (ys, ns)) = if pred(x)
   1.441 +	    then  part (xs, (x::ys, ns))
   1.442 +	    else  part (xs, (ys, x::ns))
   1.443 +    in  part (rev ys, ([],[]))  end;
   1.444 +
   1.445 +
   1.446 +fun partition_eq (eq:'a * 'a -> bool) =
   1.447 +    let fun part [] = []
   1.448 +	  | part (x::ys) = let val (xs,xs') = partition (apl(x,eq)) ys
   1.449 +			   in (x::xs)::(part xs') end
   1.450 +    in part end;
   1.451 +
   1.452 +
   1.453 +(*Partition a list into buckets  [ bi, b(i+1),...,bj ]
   1.454 +   putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
   1.455 +fun partition_list p i j =
   1.456 +  let fun part k xs = 
   1.457 +            if k>j then 
   1.458 +              (case xs of [] => []
   1.459 +                         | _ => raise LIST "partition_list")
   1.460 +            else
   1.461 +	    let val (ns,rest) = partition (p k) xs;
   1.462 +	    in  ns :: part(k+1)rest  end
   1.463 +  in  part i end;
   1.464 +
   1.465 +
   1.466 +(*Insertion sort.  Stable (does not reorder equal elements)
   1.467 +  'less' is less-than test on type 'a. *)
   1.468 +fun sort (less: 'a*'a -> bool) = 
   1.469 +  let fun insert (x, []) = [x]
   1.470 +        | insert (x, y::ys) = 
   1.471 +              if less(y,x) then y :: insert (x,ys) else x::y::ys;
   1.472 +      fun sort1 [] = []
   1.473 +        | sort1 (x::xs) = insert (x, sort1 xs)
   1.474 +  in  sort1  end;
   1.475 +
   1.476 +(*Transitive Closure. Not Warshall's algorithm*)
   1.477 +fun transitive_closure [] = []
   1.478 +  | transitive_closure ((x,ys)::ps) =
   1.479 +      let val qs = transitive_closure ps
   1.480 +          val zs = foldl (fn (zs,y) => assocs qs y union zs) (ys,ys)
   1.481 +          fun step(u,us) = (u, if x mem us then zs union us else us)
   1.482 +      in (x,zs) :: map step qs end;
   1.483 +
   1.484 +(*** Converting integers to strings, generating identifiers, etc. ***)
   1.485 +
   1.486 +(*Expand the number in the given base 
   1.487 + example: radixpand(2, 8)  gives   [1, 0, 0, 0] *)
   1.488 +fun radixpand (base,num) : int list =
   1.489 +  let fun radix (n,tail) =
   1.490 +  	if n<base then n :: tail
   1.491 +	else radix (n div base, (n mod base) :: tail)
   1.492 +  in  radix (num,[])  end;
   1.493 +
   1.494 +(*Expands a number into a string of characters starting from "zerochar"
   1.495 + example: radixstring(2,"0", 8)  gives  "1000" *)
   1.496 +fun radixstring (base,zerochar,num) =
   1.497 +  let val offset = ord(zerochar); 
   1.498 +      fun chrof n = chr(offset+n)
   1.499 +  in  implode (map chrof (radixpand (base,num)))  end;
   1.500 +
   1.501 +fun string_of_int n = 
   1.502 +  if n < 0 then "~" ^ radixstring(10,"0",~n)  else radixstring(10,"0",n);
   1.503 +
   1.504 +val print_int = prs o string_of_int;
   1.505 +
   1.506 +local
   1.507 +val a = ord("a") and z = ord("z") and A = ord("A") and Z = ord("Z")
   1.508 +and k0 = ord("0") and k9 = ord("9")
   1.509 +in
   1.510 +
   1.511 +(*Increment a list of letters like a reversed base 26 number.
   1.512 +  If head is "z",  bumps chars in tail.
   1.513 +  Digits are incremented as if they were integers.
   1.514 +  "_" and "'" are not changed.
   1.515 +  For making variants of identifiers. *)
   1.516 +
   1.517 +fun bump_int_list(c::cs) = if c="9" then "0" :: bump_int_list cs else
   1.518 +	if k0 <= ord(c) andalso ord(c) < k9 then chr(ord(c)+1) :: cs
   1.519 +	else "1" :: c :: cs
   1.520 +  | bump_int_list([]) = error("bump_int_list: not an identifier");
   1.521 +
   1.522 +fun bump_list([],d) = [d]
   1.523 +  | bump_list(["'"],d) = [d,"'"]
   1.524 +  | bump_list("z"::cs,_) = "a" :: bump_list(cs,"a")
   1.525 +  | bump_list("Z"::cs,_) = "A" :: bump_list(cs,"A")
   1.526 +  | bump_list("9"::cs,_) = "0" :: bump_int_list cs
   1.527 +  | bump_list(c::cs,_) = let val k = ord(c)
   1.528 +	in if (a <= k andalso k < z) orelse (A <= k andalso k < Z) orelse
   1.529 +	      (k0 <= k andalso k < k9) then chr(k+1) :: cs else
   1.530 +	   if c="'" orelse c="_" then c :: bump_list(cs,"") else
   1.531 +		error("bump_list: not legal in identifier: " ^
   1.532 +			implode(rev(c::cs)))
   1.533 +	end;
   1.534 +
   1.535 +end;
   1.536 +
   1.537 +fun bump_string s : string = implode (rev (bump_list(rev(explode s),"")));
   1.538 +
   1.539 +
   1.540 +(*** Operations on integer lists ***)
   1.541 +
   1.542 +fun sum [] = 0
   1.543 +  | sum (n::ns) = n + sum ns;
   1.544 +
   1.545 +fun max[m : int]  = m
   1.546 +  | max(m::n::ns) = if m>n  then  max(m::ns)  else  max(n::ns)
   1.547 +  | max []        = raise LIST "max";
   1.548 +
   1.549 +fun min[m : int]  = m
   1.550 +  | min(m::n::ns) = if m<n  then  min(m::ns)  else  min(n::ns)
   1.551 +  | min []        = raise LIST "min";
   1.552 +
   1.553 +
   1.554 +(*** Lexical scanning ***)
   1.555 +
   1.556 +(* [x1,...,xi,...,xn]  --->  ([x1,...,x(i-1)], [xi,..., xn])
   1.557 +   where xi is the first element that does not satisfy the predicate*)
   1.558 +fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
   1.559 +  let fun take (rxs, []) = (rev rxs, [])
   1.560 +	| take (rxs, x::xs) =
   1.561 +	    if  pred x  then  take(x::rxs, xs)  else  (rev rxs, x::xs)
   1.562 +  in  take([],xs)  end;
   1.563 +
   1.564 +infix prefix;
   1.565 +fun [] prefix _ = true
   1.566 +  | (x::xs) prefix (y::ys) = (x=y) andalso (xs prefix ys)
   1.567 +  | _ prefix _ = false;
   1.568 +
   1.569 +(* [x1, x2, ..., xn] ---> [x1, s, x2, s, ..., s, xn] *)
   1.570 +fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
   1.571 +  | separate _ xs = xs;
   1.572 +
   1.573 +(*space_implode "..." (explode "hello");  gives  "h...e...l...l...o" *)
   1.574 +fun space_implode a bs = implode (separate a bs); 
   1.575 +
   1.576 +fun quote s = "\"" ^ s ^ "\"";
   1.577 +
   1.578 +(*Concatenate messages, one per line, into a string*)
   1.579 +val cat_lines = implode o (map (apr(op^,"\n")));
   1.580 +
   1.581 +(*Scan a list of characters into "words" composed of "letters" (recognized
   1.582 +  by is_let) and separated by any number of non-"letters".*)
   1.583 +fun scanwords is_let cs = 
   1.584 +  let fun scan1 [] = []
   1.585 +	| scan1 cs =
   1.586 +	    let val (lets, rest) = take_prefix is_let cs
   1.587 +	    in  implode lets :: scanwords is_let rest  end;
   1.588 +  in  scan1 (#2 (take_prefix (not o is_let) cs))  end;