src/Pure/library.ML
author wenzelm
Fri Oct 08 12:35:53 1993 +0100 (1993-10-08)
changeset 41 97aae241094b
parent 24 f3d4ff75d9f2
child 160 80ccb6c354ba
permissions -rw-r--r--
added cons, rcons, last_elem, sort_strings, take_suffix;
improved tack_on;
     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: booleans, lists, pairs, input/output, etc.
     7 *)
     8 
     9 
    10 (**** Booleans: operators for combining predicates ****)
    11 
    12 infix orf; 
    13 fun p orf q = fn x => p x orelse q x ;
    14 
    15 infix andf; 
    16 fun p andf q = fn x => p x andalso q x ;
    17 
    18 fun notf p x = not (p x) ;
    19 
    20 fun orl [] = false
    21   | orl (x::l) =  x  orelse  orl l;
    22 
    23 fun andl [] = true
    24   | andl (x::l) =  x  andalso  andl l;
    25 
    26 (*exists pred [x1,...,xn] ======>  pred(x1)  orelse  ...  orelse  pred(xn)*)
    27 fun exists (pred: 'a -> bool) : 'a list -> bool = 
    28   let fun boolf [] = false
    29         | boolf (x::l) = (pred x) orelse boolf l
    30   in boolf end;
    31 
    32 (*forall pred [x1,...,xn] ======>  pred(x1)  andalso  ...  andalso  pred(xn)*)
    33 fun forall (pred: 'a -> bool) : 'a list -> bool = 
    34   let fun boolf [] = true
    35         | boolf (x::l) = (pred x) andalso (boolf l)
    36   in boolf end;
    37 
    38 
    39 (*** Lists ***)
    40 
    41 exception LIST of string;
    42 
    43 (*discriminator and selectors for lists. *)
    44 fun null   []   = true
    45   | null (_::_) = false;
    46 
    47 fun hd   []   = raise LIST "hd"
    48   | hd (a::_) = a;
    49 
    50 fun tl   []   = raise LIST "tl"
    51   | tl (_::l) = l;
    52 
    53 
    54 (*curried cons and reverse cons*)
    55 
    56 fun cons x xs = x :: xs;
    57 
    58 fun rcons xs x = x :: xs;
    59 
    60 
    61 (*curried functions for pairing and reversed pairing*)
    62 fun pair x y = (x,y);
    63 fun rpair x y = (y,x);
    64 
    65 fun fst(x,y) = x and snd(x,y) = y;
    66 
    67 (*Handy combinators*)
    68 fun curry f x y = f(x,y);
    69 fun uncurry f(x,y) = f x y;
    70 fun I x = x  and  K x y = x;
    71 
    72 (*Combine two functions forming the union of their domains*)
    73 infix orelf;
    74 fun f orelf g = fn x => f x  handle Match=> g x;
    75 
    76 
    77 (*Application of (infix) operator to its left or right argument*)
    78 fun apl (x,f) y = f(x,y);
    79 fun apr (f,y) x = f(x,y);
    80 
    81 
    82 (*functional for pairs*)
    83 fun pairself f (x,y) = (f x, f y);
    84 
    85 (*Apply the function to a component of a pair*)
    86 fun apfst f (x, y) = (f x, y);
    87 fun apsnd f (x, y) = (x, f y);
    88 
    89 fun square (n: int) = n*n;
    90 
    91 fun fact 0 = 1
    92   | fact n = n * fact(n-1);
    93 
    94 
    95 (*The following versions of fold are designed to fit nicely with infixes.*)
    96 
    97 (*  (op @) (e, [x1,...,xn])  ======>   ((e @ x1) @ x2) ... @ xn
    98     for operators that associate to the left.  TAIL RECURSIVE*)
    99 fun foldl (f: 'a * 'b -> 'a) : 'a * 'b list -> 'a =
   100   let fun itl (e, [])  = e
   101         | itl (e, a::l) = itl (f(e,a), l)
   102   in  itl end;
   103 
   104 (*  (op @) ([x1,...,xn], e)  ======>   x1 @ (x2 ... @ (xn @ e))
   105     for operators that associate to the right.  Not tail recursive.*)
   106 fun foldr f (l,e) =
   107   let fun itr [] = e
   108         | itr (a::l) = f(a, itr l)
   109   in  itr l  end;
   110 
   111 (*  (op @) [x1,...,xn]  ======>   x1 @ (x2 ..(x[n-1]. @ xn))
   112     for n>0, operators that associate to the right.  Not tail recursive.*)
   113 fun foldr1 f l =
   114   let fun itr [x] = x
   115         | itr (x::l) = f(x, itr l)
   116   in  itr l  end;
   117 
   118 
   119 (*Length of a list.  Should unquestionably be a standard function*)
   120 local fun length1 (n, [ ])  = n   (*TAIL RECURSIVE*)
   121         | length1 (n, x::l) = length1 (n+1, l)   
   122 in  fun length l = length1 (0,l) end;
   123 
   124 
   125 (*Take the first n elements from l.*)
   126 fun take (n, []) = []
   127   | take (n, x::xs) = if n>0 then x::take(n-1,xs)  
   128                       else  [];
   129 
   130 (*Drop the first n elements from l.*)
   131 fun drop (_, [])    = []
   132   | drop (n, x::xs) = if n>0 then drop (n-1, xs) 
   133                              else x::xs;
   134 
   135 (*Return nth element of l, where 0 designates the first element;
   136   raise EXCEPTION if list too short.*)
   137 fun nth_elem NL = case (drop NL) of
   138     []   => raise LIST "nth_elem" 
   139   | x::l => x;
   140 
   141 
   142 (*Last element of a list*)
   143 fun last_elem [] = raise LIST "last_elem"
   144   | last_elem [x] = x
   145   | last_elem (_ :: xs) = last_elem xs;
   146 
   147 
   148 (*make the list [from, from+1, ..., to]*)
   149 infix upto;
   150 fun from upto to =
   151     if from>to then []  else  from :: ((from+1) upto to);
   152 
   153 (*make the list [from, from-1, ..., to]*)
   154 infix downto;
   155 fun from downto to =
   156     if from<to then []  else  from :: ((from-1) downto to);
   157 
   158 (* predicate: downto0(is,n) <=> is = [n,n-1,...,0] *)
   159 fun downto0(i::is,n) = i=n andalso downto0(is,n-1)
   160   | downto0([],n)    = n = ~1;
   161 
   162 (*Like Lisp's MAPC -- seq proc [x1,...,xn] evaluates 
   163   proc(x1); ... ; proc(xn) for side effects.*)
   164 fun seq (proc: 'a -> unit) : 'a list -> unit = 
   165   let fun seqf []     = ()
   166         | seqf (x::l) = (proc x;  seqf l)
   167   in  seqf end;
   168 
   169 
   170 (*** Balanced folding; access to balanced trees ***)
   171 
   172 exception Balance;	(*indicates non-positive argument to balancing fun*)
   173 
   174 (*Balanced folding; avoids deep nesting*)
   175 fun fold_bal f [x] = x
   176   | fold_bal f [] = raise Balance
   177   | fold_bal f xs =
   178       let val k = length xs div 2
   179       in  f (fold_bal f (take(k,xs)),
   180 	     fold_bal f (drop(k,xs)))  
   181       end;
   182 
   183 (*Construct something of the form f(...g(...(x)...)) for balanced access*)
   184 fun access_bal (f,g,x) n i =
   185   let fun acc n i = 	(* 1<=i<=n*)
   186           if n=1 then x else
   187 	  let val n2 = n div 2
   188 	  in  if i<=n2 then f (acc n2 i) 
   189 	               else g (acc (n-n2) (i-n2))
   190           end
   191   in  if 1<=i andalso i<=n then acc n i else raise Balance  end;
   192 
   193 (*Construct ALL such accesses; could try harder to share recursive calls!*)
   194 fun accesses_bal (f,g,x) n =
   195   let fun acc n =  
   196           if n=1 then [x] else 
   197 	  let val n2 = n div 2
   198 	      val acc2 = acc n2
   199 	  in  if n-n2=n2 then map f acc2 @ map g acc2
   200 	                 else map f acc2 @ map g (acc (n-n2)) end
   201   in  if 1<=n then acc n else raise Balance  end;
   202 
   203 
   204 (*** Input/Output ***)
   205 
   206 fun prs s = output(std_out,s);
   207 fun writeln s = prs (s ^ "\n");
   208 
   209 (*Print error message and abort to top level*)
   210 exception ERROR;
   211 fun error (msg) = (writeln msg;  raise ERROR);
   212 
   213 fun assert p msg = if p then () else error msg;
   214 fun deny p msg = if p then error msg else ();
   215 
   216 (*For the "test" target in Makefiles -- signifies successful termination*)
   217 fun maketest msg = 
   218     (writeln msg;
   219      output(open_out "test", "Test examples ran successfully\n"));
   220 
   221 (*print a list surrounded by the brackets lpar and rpar, with comma separator
   222   print nothing for empty list*)
   223 fun print_list (lpar, rpar, pre: 'a -> unit)  (l : 'a list) = 
   224     let fun prec(x) = (prs",";  pre(x)) 
   225     in  case l of
   226 	    [] => () 
   227 	  | x::l =>  (prs lpar;  pre x;  seq prec l;  prs rpar)
   228     end;
   229 
   230 (*print a list of items separated by newlines*)
   231 fun print_list_ln (pre: 'a -> unit)  : 'a list -> unit = 
   232     seq (fn x => (pre x;  writeln""));
   233 
   234 fun is_letter ch =
   235   (ord"A" <= ord ch)  andalso  (ord ch <= ord"Z")   orelse
   236   (ord"a" <= ord ch)  andalso  (ord ch <= ord"z");
   237 
   238 fun is_digit ch =
   239   (ord"0" <= ord ch)  andalso  (ord ch <= ord"9");
   240 
   241 (*letter or _ or prime (') *)
   242 fun is_quasi_letter "_" = true
   243   | is_quasi_letter "'" = true
   244   | is_quasi_letter ch  = is_letter ch;
   245 
   246 (*white space: blanks, tabs, newlines*)
   247 val is_blank : string -> bool = fn
   248      " " => true  |  "\t" => true  |  "\n" => true  |  _ => false;
   249 
   250 val is_letdig = is_quasi_letter orf is_digit;
   251 
   252 val to_lower =
   253   let
   254     fun lower ch =
   255       if ch >= "A" andalso ch <= "Z" then
   256         chr (ord ch - ord "A" + ord "a")
   257       else ch;
   258   in
   259     implode o (map lower) o explode
   260   end;
   261 
   262 
   263 (*** Timing ***)
   264 
   265 (*Unconditional timing function*)
   266 val timeit = cond_timeit true;
   267 
   268 (*Timed application function*)
   269 fun timeap f x = timeit(fn()=> f x);
   270 
   271 (*Timed "use" function, printing filenames*)
   272 fun time_use fname = timeit(fn()=> 
   273    (writeln("\n**** Starting " ^ fname ^ " ****");  use fname;  
   274     writeln("\n**** Finished " ^ fname ^ " ****")));  
   275 
   276 
   277 (*** Misc functions ***)
   278 
   279 (*Function exponentiation: f(...(f x)...) with n applications of f *)
   280 fun funpow n f x =
   281   let fun rep (0,x) = x
   282         | rep (n,x) = rep (n-1, f x)
   283   in  rep (n,x)  end;
   284 
   285 (*Combine two lists forming a list of pairs:
   286   [x1,...,xn] ~~ [y1,...,yn]  ======>   [(x1,y1), ..., (xn,yn)] *)
   287 infix ~~;
   288 fun []   ~~  []   = []
   289   | (x::xs) ~~ (y::ys) = (x,y) :: (xs ~~ ys)
   290   |  _   ~~   _   = raise LIST "~~";
   291 
   292 (*Inverse of ~~;  the old 'split'.
   293    [(x1,y1), ..., (xn,yn)]  ======>  ( [x1,...,xn] , [y1,...,yn] ) *)
   294 fun split_list (l: ('a*'b)list) = (map #1 l, map #2 l);
   295 
   296 (*make the list [x; x; ...; x] of length n*)
   297 fun replicate n (x: 'a) : 'a list =
   298   let fun rep (0,xs) = xs
   299         | rep (n,xs) = rep(n-1, x::xs) 
   300   in   if n<0 then raise LIST "replicate"
   301        else rep (n,[])
   302   end;
   303 
   304 (*Flatten a list of lists to a list.*)
   305 fun flat (ls: 'c list list) : 'c list = foldr (op @) (ls,[]);
   306 
   307 
   308 (*** polymorphic set operations ***)
   309 
   310 (*membership in a list*)
   311 infix mem;
   312 fun x mem []  =  false
   313   | x mem (y::l)  =  (x=y) orelse (x mem l);
   314 
   315 (*insertion into list if not already there*)
   316 infix ins;
   317 fun x ins xs = if x mem xs then  xs   else  x::xs;
   318 
   319 (*union of sets represented as lists: no repetitions*)
   320 infix union;
   321 fun   xs    union [] = xs
   322   |   []    union ys = ys
   323   | (x::xs) union ys = xs union (x ins ys);
   324 
   325 infix inter;
   326 fun   []    inter ys = []
   327   | (x::xs) inter ys = if x mem ys then x::(xs inter ys)
   328                                    else     xs inter ys;
   329 
   330 infix subset;
   331 fun   []    subset ys = true
   332   | (x::xs) subset ys = x mem ys   andalso  xs subset ys;
   333 
   334 (*removing an element from a list WITHOUT duplicates*)
   335 infix \;
   336 fun (y::ys) \ x = if x=y then ys else y::(ys \ x)
   337   |   []    \ x = [];
   338 
   339 infix \\;
   340 val op \\ = foldl (op \);
   341 
   342 (*** option stuff ***)
   343 
   344 datatype 'a option = None | Some of 'a;
   345 
   346 exception OPTION of string;
   347 
   348 fun the (Some x) = x
   349   | the None = raise OPTION "the";
   350 
   351 fun is_some (Some _) = true
   352   | is_some None = false;
   353 
   354 fun is_none (Some _) = false
   355   | is_none None = true;
   356 
   357 
   358 (*** Association lists ***)
   359 
   360 (*Association list lookup*)
   361 fun assoc ([], key) = None
   362   | assoc ((keyi,xi)::pairs, key) =
   363       if key=keyi then Some xi  else assoc (pairs,key);
   364 
   365 fun assocs ps x = case assoc(ps,x) of None => [] | Some(ys) => ys;
   366 
   367 (*Association list update*)
   368 fun overwrite(al,p as (key,_)) =
   369   let fun over((q as (keyi,_))::pairs) =
   370 	    if keyi=key then p::pairs else q::(over pairs)
   371 	| over[] = [p]
   372   in over al end;
   373 
   374 (*Copy the list preserving elements that satisfy the predicate*)
   375 fun filter (pred: 'a->bool) : 'a list -> 'a list = 
   376   let fun filt [] = []
   377         | filt (x::xs) =  if pred(x) then x :: filt xs  else  filt xs
   378   in  filt   end;
   379 
   380 fun filter_out f = filter (not o f);
   381 
   382 
   383 (*** List operations, generalized to an arbitrary equality function "eq"
   384      -- so what good are equality types?? ***)
   385 
   386 (*removing an element from a list -- possibly WITH duplicates*)
   387 fun gen_rem eq (xs,y) = filter_out (fn x => eq(x,y)) xs;
   388 
   389 (*generalized membership test*)
   390 fun gen_mem eq (x, [])     =  false
   391   | gen_mem eq (x, y::ys)  =  eq(x,y) orelse gen_mem eq (x,ys);
   392 
   393 (*generalized insertion*)
   394 fun gen_ins eq (x,xs) = if gen_mem eq (x,xs) then  xs   else  x::xs;
   395 
   396 (*generalized union*)
   397 fun gen_union eq (xs,[]) = xs
   398   | gen_union eq ([],ys) = ys
   399   | gen_union eq (x::xs,ys) = gen_union eq (xs, gen_ins eq (x,ys));
   400 
   401 (*Generalized association list lookup*)
   402 fun gen_assoc eq ([], key) = None
   403   | gen_assoc eq ((keyi,xi)::pairs, key) =
   404       if eq(key,keyi) then Some xi  else gen_assoc eq (pairs,key);
   405 
   406 (** Finding list elements and duplicates **)
   407 
   408 (* find the position of an element in a list *)
   409 fun find(x,ys) =
   410     let fun f(y::ys,i) = if x=y then i else f(ys,i+1)
   411           | f(_,_) = raise LIST "find"
   412     in f(ys,0) end;
   413 
   414 (*Returns the tail beginning with the first repeated element, or []. *)
   415 fun findrep [] = []
   416   | findrep (x::xs) = if  x mem xs  then  x::xs   else   findrep xs;
   417 
   418 fun distinct1 (seen, []) = rev seen
   419   | distinct1 (seen, x::xs) =
   420       if x mem seen then distinct1 (seen, xs)
   421     		    else distinct1 (x::seen, xs);
   422 
   423 (*Makes a list of the distinct members of the input*)
   424 fun distinct xs = distinct1([],xs);
   425 
   426 
   427 (*Use the keyfun to make a list of (x,key) pairs.*)
   428 fun make_keylist (keyfun: 'a->'b) : 'a list -> ('a * 'b) list =
   429   let fun keypair x = (x, keyfun x) 
   430   in   map keypair  end;
   431 
   432 (*Given a list of (x,key) pairs and a searchkey
   433   return the list of xs from each pair whose key equals searchkey*)
   434 fun keyfilter [] searchkey = []
   435   | keyfilter ((x,key)::pairs) searchkey = 
   436 	if key=searchkey then x :: keyfilter pairs searchkey
   437 	else keyfilter pairs searchkey;
   438 
   439 fun mapfilter (f: 'a -> 'b option) ([]: 'a list) = [] : 'b list
   440   | mapfilter f (x::xs) =
   441       case (f x) of
   442 	  None => mapfilter f xs
   443 	| Some y => y :: mapfilter f xs;
   444 
   445 
   446 (*Partition list into elements that satisfy predicate and those that don't.
   447   Preserves order of elements in both lists. *)
   448 fun partition (pred: 'a->bool) (ys: 'a list) : ('a list * 'a list) =
   449     let fun part ([], answer) = answer
   450 	  | part (x::xs, (ys, ns)) = if pred(x)
   451 	    then  part (xs, (x::ys, ns))
   452 	    else  part (xs, (ys, x::ns))
   453     in  part (rev ys, ([],[]))  end;
   454 
   455 
   456 fun partition_eq (eq:'a * 'a -> bool) =
   457     let fun part [] = []
   458 	  | part (x::ys) = let val (xs,xs') = partition (apl(x,eq)) ys
   459 			   in (x::xs)::(part xs') end
   460     in part end;
   461 
   462 
   463 (*Partition a list into buckets  [ bi, b(i+1),...,bj ]
   464    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
   465 fun partition_list p i j =
   466   let fun part k xs = 
   467             if k>j then 
   468               (case xs of [] => []
   469                          | _ => raise LIST "partition_list")
   470             else
   471 	    let val (ns,rest) = partition (p k) xs;
   472 	    in  ns :: part(k+1)rest  end
   473   in  part i end;
   474 
   475 
   476 (*Insertion sort.  Stable (does not reorder equal elements)
   477   'less' is less-than test on type 'a. *)
   478 fun sort (less: 'a*'a -> bool) = 
   479   let fun insert (x, []) = [x]
   480         | insert (x, y::ys) = 
   481               if less(y,x) then y :: insert (x,ys) else x::y::ys;
   482       fun sort1 [] = []
   483         | sort1 (x::xs) = insert (x, sort1 xs)
   484   in  sort1  end;
   485 
   486 (*sort strings*)
   487 val sort_strings = sort (op <= : string * string -> bool);
   488 
   489 
   490 (*Transitive Closure. Not Warshall's algorithm*)
   491 fun transitive_closure [] = []
   492   | transitive_closure ((x,ys)::ps) =
   493       let val qs = transitive_closure ps
   494           val zs = foldl (fn (zs,y) => assocs qs y union zs) (ys,ys)
   495           fun step(u,us) = (u, if x mem us then zs union us else us)
   496       in (x,zs) :: map step qs end;
   497 
   498 (*** Converting integers to strings, generating identifiers, etc. ***)
   499 
   500 (*Expand the number in the given base 
   501  example: radixpand(2, 8)  gives   [1, 0, 0, 0] *)
   502 fun radixpand (base,num) : int list =
   503   let fun radix (n,tail) =
   504   	if n<base then n :: tail
   505 	else radix (n div base, (n mod base) :: tail)
   506   in  radix (num,[])  end;
   507 
   508 (*Expands a number into a string of characters starting from "zerochar"
   509  example: radixstring(2,"0", 8)  gives  "1000" *)
   510 fun radixstring (base,zerochar,num) =
   511   let val offset = ord(zerochar); 
   512       fun chrof n = chr(offset+n)
   513   in  implode (map chrof (radixpand (base,num)))  end;
   514 
   515 fun string_of_int n = 
   516   if n < 0 then "~" ^ radixstring(10,"0",~n)  else radixstring(10,"0",n);
   517 
   518 val print_int = prs o string_of_int;
   519 
   520 local
   521 val a = ord("a") and z = ord("z") and A = ord("A") and Z = ord("Z")
   522 and k0 = ord("0") and k9 = ord("9")
   523 in
   524 
   525 (*Increment a list of letters like a reversed base 26 number.
   526   If head is "z",  bumps chars in tail.
   527   Digits are incremented as if they were integers.
   528   "_" and "'" are not changed.
   529   For making variants of identifiers. *)
   530 
   531 fun bump_int_list(c::cs) = if c="9" then "0" :: bump_int_list cs else
   532 	if k0 <= ord(c) andalso ord(c) < k9 then chr(ord(c)+1) :: cs
   533 	else "1" :: c :: cs
   534   | bump_int_list([]) = error("bump_int_list: not an identifier");
   535 
   536 fun bump_list([],d) = [d]
   537   | bump_list(["'"],d) = [d,"'"]
   538   | bump_list("z"::cs,_) = "a" :: bump_list(cs,"a")
   539   | bump_list("Z"::cs,_) = "A" :: bump_list(cs,"A")
   540   | bump_list("9"::cs,_) = "0" :: bump_int_list cs
   541   | bump_list(c::cs,_) = let val k = ord(c)
   542 	in if (a <= k andalso k < z) orelse (A <= k andalso k < Z) orelse
   543 	      (k0 <= k andalso k < k9) then chr(k+1) :: cs else
   544 	   if c="'" orelse c="_" then c :: bump_list(cs,"") else
   545 		error("bump_list: not legal in identifier: " ^
   546 			implode(rev(c::cs)))
   547 	end;
   548 
   549 end;
   550 
   551 fun bump_string s : string = implode (rev (bump_list(rev(explode s),"")));
   552 
   553 
   554 (*** Operations on integer lists ***)
   555 
   556 fun sum [] = 0
   557   | sum (n::ns) = n + sum ns;
   558 
   559 fun max[m : int]  = m
   560   | max(m::n::ns) = if m>n  then  max(m::ns)  else  max(n::ns)
   561   | max []        = raise LIST "max";
   562 
   563 fun min[m : int]  = m
   564   | min(m::n::ns) = if m<n  then  min(m::ns)  else  min(n::ns)
   565   | min []        = raise LIST "min";
   566 
   567 
   568 (*** Lexical scanning ***)
   569 
   570 (* [x1,...,xi,...,xn]  --->  ([x1,...,x(i-1)], [xi,..., xn])
   571    where xi is the first element that does not satisfy the predicate*)
   572 fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
   573   let fun take (rxs, []) = (rev rxs, [])
   574 	| take (rxs, x::xs) =
   575 	    if  pred x  then  take(x::rxs, xs)  else  (rev rxs, x::xs)
   576   in  take([],xs)  end;
   577 
   578 (* [x1,...,xi,...,xn]  --->  ([x1,...,xi], [x(i+1),..., xn])
   579    where xi is the last element that does not satisfy the predicate*)
   580 fun take_suffix _ [] = ([], [])
   581   | take_suffix pred (x :: xs) =
   582       (case take_suffix pred xs of
   583         ([], sffx) => if pred x then ([], x :: sffx) else ([x], sffx)
   584       | (prfx, sffx) => (x :: prfx, sffx));
   585 
   586 
   587 infix prefix;
   588 fun [] prefix _ = true
   589   | (x::xs) prefix (y::ys) = (x=y) andalso (xs prefix ys)
   590   | _ prefix _ = false;
   591 
   592 (* [x1, x2, ..., xn] ---> [x1, s, x2, s, ..., s, xn] *)
   593 fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
   594   | separate _ xs = xs;
   595 
   596 (*space_implode "..." (explode "hello");  gives  "h...e...l...l...o" *)
   597 fun space_implode a bs = implode (separate a bs); 
   598 
   599 (*simple quoting (does not escape special chars) *)
   600 fun quote s = "\"" ^ s ^ "\"";
   601 
   602 (*Concatenate messages, one per line, into a string*)
   603 val cat_lines = implode o (map (apr(op^,"\n")));
   604 
   605 (*Scan a list of characters into "words" composed of "letters" (recognized
   606   by is_let) and separated by any number of non-"letters".*)
   607 fun scanwords is_let cs = 
   608   let fun scan1 [] = []
   609 	| scan1 cs =
   610 	    let val (lets, rest) = take_prefix is_let cs
   611 	    in  implode lets :: scanwords is_let rest  end;
   612   in  scan1 (#2 (take_prefix (not o is_let) cs))  end;
   613 
   614 
   615 (*** Operations on filenames ***)
   616 
   617 (*Convert Unix filename of the form path/file to "path/" and "file" ;
   618   if filename contains no slash, then it returns "" and "file" *)
   619 fun split_filename name =
   620   let val (file,path) = take_prefix (apr(op<>,"/")) (rev (explode name))
   621   in  (implode(rev path), implode(rev file)) end;
   622 
   623 (*Merge splitted filename (path and file);
   624   if path does not end with one a slash is appended *)
   625 fun tack_on "" name = name
   626   | tack_on path name =
   627       if last_elem (explode path) = "/" then path ^ name
   628       else path ^ "/" ^ name;
   629 
   630 (*Remove the extension of a filename, i.e. the part after the last '.' *)
   631 fun remove_ext name =
   632   let val (file,_) = take_prefix (apr(op<>,".")) (rev (explode name))
   633   in implode (rev file) end;
   634