src/Pure/library.ML
author clasohm
Mon Jan 29 14:16:13 1996 +0100 (1996-01-29)
changeset 1460 5a6f2aabd538
parent 1458 fd510875fb71
child 1576 af8f43f742a0
permissions -rw-r--r--
inserted tabs again
     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 trees,
     8 input / output, timing, filenames, misc functions.
     9 *)
    10 
    11 infix |> ~~ \ \\ orelf ins orf andf prefix upto downto mem union inter subset
    12       subdir_of;
    13 
    14 
    15 structure Library =
    16 struct
    17 
    18 (** functions **)
    19 
    20 (*handy combinators*)
    21 fun curry f x y = f (x, y);
    22 fun uncurry f (x, y) = f x y;
    23 fun I x = x;
    24 fun K x y = x;
    25 
    26 (*reverse apply*)
    27 fun (x |> f) = f x;
    28 
    29 (*combine two functions forming the union of their domains*)
    30 fun f orelf g = fn x => f x handle Match => g x;
    31 
    32 (*application of (infix) operator to its left or right argument*)
    33 fun apl (x, f) y = f (x, y);
    34 fun apr (f, y) x = f (x, y);
    35 
    36 (*functional for pairs*)
    37 fun pairself f (x, y) = (f x, f y);
    38 
    39 (*function exponentiation: f(...(f x)...) with n applications of f*)
    40 fun funpow n f x =
    41   let fun rep (0, x) = x
    42         | rep (n, x) = rep (n - 1, f x)
    43   in rep (n, x) end;
    44 
    45 
    46 
    47 (** options **)
    48 
    49 datatype 'a option = None | Some of 'a;
    50 
    51 exception OPTION of string;
    52 
    53 fun the (Some x) = x
    54   | the None = raise OPTION "the";
    55 
    56 fun if_none None y = y
    57   | if_none (Some x) _ = x;
    58 
    59 fun is_some (Some _) = true
    60   | is_some None = false;
    61 
    62 fun is_none (Some _) = false
    63   | is_none None = true;
    64 
    65 fun apsome f (Some x) = Some (f x)
    66   | apsome _ None = None;
    67 
    68 
    69 
    70 (** pairs **)
    71 
    72 fun pair x y = (x, y);
    73 fun rpair x y = (y, x);
    74 
    75 fun fst (x, y) = x;
    76 fun snd (x, y) = y;
    77 
    78 fun eq_fst ((x1, _), (x2, _)) = x1 = x2;
    79 fun eq_snd ((_, y1), (_, y2)) = y1 = y2;
    80 
    81 fun swap (x, y) = (y, x);
    82 
    83 (*apply the function to a component of a pair*)
    84 fun apfst f (x, y) = (f x, y);
    85 fun apsnd f (x, y) = (x, f y);
    86 
    87 
    88 
    89 (** booleans **)
    90 
    91 (* equality *)
    92 
    93 fun equal x y = x = y;
    94 fun not_equal x y = x <> y;
    95 
    96 
    97 (* operators for combining predicates *)
    98 
    99 fun p orf q = fn x => p x orelse q x;
   100 
   101 fun p andf q = fn x => p x andalso q x;
   102 
   103 fun notf p x = not (p x);
   104 
   105 
   106 (* predicates on lists *)
   107 
   108 fun orl [] = false
   109   | orl (x :: xs) = x orelse orl xs;
   110 
   111 fun andl [] = true
   112   | andl (x :: xs) = x andalso andl xs;
   113 
   114 (*exists pred [x1, ..., xn] ===> pred x1 orelse ... orelse pred xn*)
   115 fun exists (pred: 'a -> bool) : 'a list -> bool =
   116   let fun boolf [] = false
   117         | boolf (x :: xs) = pred x orelse boolf xs
   118   in boolf end;
   119 
   120 (*forall pred [x1, ..., xn] ===> pred x1 andalso ... andalso pred xn*)
   121 fun forall (pred: 'a -> bool) : 'a list -> bool =
   122   let fun boolf [] = true
   123         | boolf (x :: xs) = pred x andalso boolf xs
   124   in boolf end;
   125 
   126 
   127 (* flags *)
   128 
   129 fun set flag = (flag := true; true);
   130 fun reset flag = (flag := false; false);
   131 fun toggle flag = (flag := not (! flag); ! flag);
   132 
   133 
   134 
   135 (** lists **)
   136 
   137 exception LIST of string;
   138 
   139 fun null [] = true
   140   | null (_ :: _) = false;
   141 
   142 fun hd [] = raise LIST "hd"
   143   | hd (x :: _) = x;
   144 
   145 fun tl [] = raise LIST "tl"
   146   | tl (_ :: xs) = xs;
   147 
   148 fun cons x xs = x :: xs;
   149 
   150 
   151 (* fold *)
   152 
   153 (*the following versions of fold are designed to fit nicely with infixes*)
   154 
   155 (*  (op @) (e, [x1, ..., xn])  ===>  ((e @ x1) @ x2) ... @ xn
   156     for operators that associate to the left (TAIL RECURSIVE)*)
   157 fun foldl (f: 'a * 'b -> 'a) : 'a * 'b list -> 'a =
   158   let fun itl (e, [])  = e
   159         | itl (e, a::l) = itl (f(e, a), l)
   160   in  itl end;
   161 
   162 (*  (op @) ([x1, ..., xn], e)  ===>   x1 @ (x2 ... @ (xn @ e))
   163     for operators that associate to the right (not tail recursive)*)
   164 fun foldr f (l, e) =
   165   let fun itr [] = e
   166         | itr (a::l) = f(a, itr l)
   167   in  itr l  end;
   168 
   169 (*  (op @) [x1, ..., xn]  ===>   x1 @ (x2 ... @ (x[n-1] @ xn))
   170     for n > 0, operators that associate to the right (not tail recursive)*)
   171 fun foldr1 f l =
   172   let fun itr [x] = x                       (* FIXME [] case: elim warn (?) *)
   173         | itr (x::l) = f(x, itr l)
   174   in  itr l  end;
   175 
   176 
   177 (* basic list functions *)
   178 
   179 (*length of a list, should unquestionably be a standard function*)
   180 local fun length1 (n, [])  = n   (*TAIL RECURSIVE*)
   181         | length1 (n, x :: xs) = length1 (n + 1, xs)
   182 in  fun length l = length1 (0, l) end;
   183 
   184 (*take the first n elements from a list*)
   185 fun take (n, []) = []
   186   | take (n, x :: xs) =
   187       if n > 0 then x :: take (n - 1, xs) else [];
   188 
   189 (*drop the first n elements from a list*)
   190 fun drop (n, []) = []
   191   | drop (n, x :: xs) =
   192       if n > 0 then drop (n - 1, xs) else x :: xs;
   193 
   194 (*return nth element of a list, where 0 designates the first element;
   195   raise EXCEPTION if list too short*)
   196 fun nth_elem NL =
   197   (case drop NL of
   198     [] => raise LIST "nth_elem"
   199   | x :: _ => x);
   200 
   201 (*last element of a list*)
   202 fun last_elem [] = raise LIST "last_elem"
   203   | last_elem [x] = x
   204   | last_elem (_ :: xs) = last_elem xs;
   205 
   206 (*find the position of an element in a list*)
   207 fun find (x, ys) =
   208   let fun f (y :: ys, i) = if x = y then i else f (ys, i + 1)
   209         | f (_, _) = raise LIST "find"
   210   in f (ys, 0) end;
   211 
   212 (*flatten a list of lists to a list*)
   213 fun flat (ls: 'c list list) : 'c list = foldr (op @) (ls, []);
   214 
   215 
   216 (*like Lisp's MAPC -- seq proc [x1, ..., xn] evaluates
   217   (proc x1; ...; proc xn) for side effects*)
   218 fun seq (proc: 'a -> unit) : 'a list -> unit =
   219   let fun seqf [] = ()
   220         | seqf (x :: xs) = (proc x; seqf xs)
   221   in seqf end;
   222 
   223 
   224 (*separate s [x1, x2, ..., xn]  ===>  [x1, s, x2, s, ..., s, xn]*)
   225 fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
   226   | separate _ xs = xs;
   227 
   228 (*make the list [x, x, ..., x] of length n*)
   229 fun replicate n (x: 'a) : 'a list =
   230   let fun rep (0, xs) = xs
   231         | rep (n, xs) = rep (n - 1, x :: xs)
   232   in
   233     if n < 0 then raise LIST "replicate"
   234     else rep (n, [])
   235   end;
   236 
   237 
   238 (* filter *)
   239 
   240 (*copy the list preserving elements that satisfy the predicate*)
   241 fun filter (pred: 'a->bool) : 'a list -> 'a list =
   242   let fun filt [] = []
   243         | filt (x :: xs) = if pred x then x :: filt xs else filt xs
   244   in filt end;
   245 
   246 fun filter_out f = filter (not o f);
   247 
   248 
   249 fun mapfilter (f: 'a -> 'b option) ([]: 'a list) = [] : 'b list
   250   | mapfilter f (x :: xs) =
   251       (case f x of
   252         None => mapfilter f xs
   253       | Some y => y :: mapfilter f xs);
   254 
   255 
   256 fun find_first _ [] = None
   257   | find_first pred (x :: xs) =
   258       if pred x then Some x else find_first pred xs;
   259 
   260 
   261 (* lists of pairs *)
   262 
   263 fun map2 _ ([], []) = []
   264   | map2 f (x :: xs, y :: ys) = (f (x, y) :: map2 f (xs, ys))
   265   | map2 _ _ = raise LIST "map2";
   266 
   267 fun exists2 _ ([], []) = false
   268   | exists2 pred (x :: xs, y :: ys) = pred (x, y) orelse exists2 pred (xs, ys)
   269   | exists2 _ _ = raise LIST "exists2";
   270 
   271 fun forall2 _ ([], []) = true
   272   | forall2 pred (x :: xs, y :: ys) = pred (x, y) andalso forall2 pred (xs, ys)
   273   | forall2 _ _ = raise LIST "forall2";
   274 
   275 (*combine two lists forming a list of pairs:
   276   [x1, ..., xn] ~~ [y1, ..., yn]  ===>  [(x1, y1), ..., (xn, yn)]*)
   277 fun [] ~~ [] = []
   278   | (x :: xs) ~~ (y :: ys) = (x, y) :: (xs ~~ ys)
   279   | _ ~~ _ = raise LIST "~~";
   280 
   281 
   282 (*inverse of ~~; the old 'split':
   283   [(x1, y1), ..., (xn, yn)]  ===>  ([x1, ..., xn], [y1, ..., yn])*)
   284 fun split_list (l: ('a * 'b) list) = (map #1 l, map #2 l);
   285 
   286 
   287 (* prefixes, suffixes *)
   288 
   289 fun [] prefix _ = true
   290   | (x :: xs) prefix (y :: ys) = x = y andalso (xs prefix ys)
   291   | _ prefix _ = false;
   292 
   293 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., x(i-1)], [xi, ..., xn])
   294    where xi is the first element that does not satisfy the predicate*)
   295 fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
   296   let fun take (rxs, []) = (rev rxs, [])
   297         | take (rxs, x :: xs) =
   298             if  pred x  then  take(x :: rxs, xs)  else  (rev rxs, x :: xs)
   299   in  take([], xs)  end;
   300 
   301 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., xi], [x(i+1), ..., xn])
   302    where xi is the last element that does not satisfy the predicate*)
   303 fun take_suffix _ [] = ([], [])
   304   | take_suffix pred (x :: xs) =
   305       (case take_suffix pred xs of
   306         ([], sffx) => if pred x then ([], x :: sffx) else ([x], sffx)
   307       | (prfx, sffx) => (x :: prfx, sffx));
   308 
   309 
   310 
   311 (** integers **)
   312 
   313 fun inc i = i := ! i + 1;
   314 fun dec i = i := ! i - 1;
   315 
   316 
   317 (* lists of integers *)
   318 
   319 (*make the list [from, from + 1, ..., to]*)
   320 fun from upto to =
   321   if from > to then [] else from :: ((from + 1) upto to);
   322 
   323 (*make the list [from, from - 1, ..., to]*)
   324 fun from downto to =
   325   if from < to then [] else from :: ((from - 1) downto to);
   326 
   327 (*predicate: downto0 (is, n) <=> is = [n, n - 1, ..., 0]*)
   328 fun downto0 (i :: is, n) = i = n andalso downto0 (is, n - 1)
   329   | downto0 ([], n) = n = ~1;
   330 
   331 
   332 (* operations on integer lists *)
   333 
   334 fun sum [] = 0
   335   | sum (n :: ns) = n + sum ns;
   336 
   337 fun max [m:int] = m
   338   | max (m :: n :: ns) = if m > n then max (m :: ns) else max (n :: ns)
   339   | max [] = raise LIST "max";
   340 
   341 fun min [m:int] = m
   342   | min (m :: n :: ns) = if m < n then min (m :: ns) else min (n :: ns)
   343   | min [] = raise LIST "min";
   344 
   345 
   346 (* convert integers to strings *)
   347 
   348 (*expand the number in the given base;
   349   example: radixpand (2, 8) gives [1, 0, 0, 0]*)
   350 fun radixpand (base, num) : int list =
   351   let
   352     fun radix (n, tail) =
   353       if n < base then n :: tail
   354       else radix (n div base, (n mod base) :: tail)
   355   in radix (num, []) end;
   356 
   357 (*expands a number into a string of characters starting from "zerochar";
   358   example: radixstring (2, "0", 8) gives "1000"*)
   359 fun radixstring (base, zerochar, num) =
   360   let val offset = ord zerochar;
   361       fun chrof n = chr (offset + n)
   362   in implode (map chrof (radixpand (base, num))) end;
   363 
   364 
   365 fun string_of_int n =
   366   if n < 0 then "~" ^ radixstring (10, "0", ~n) else radixstring (10, "0", n);
   367 
   368 
   369 
   370 (** strings **)
   371 
   372 fun is_letter ch =
   373   ord "A" <= ord ch andalso ord ch <= ord "Z" orelse
   374   ord "a" <= ord ch andalso ord ch <= ord "z";
   375 
   376 fun is_digit ch =
   377   ord "0" <= ord ch andalso ord ch <= ord "9";
   378 
   379 (*letter or _ or prime (')*)
   380 fun is_quasi_letter "_" = true
   381   | is_quasi_letter "'" = true
   382   | is_quasi_letter ch = is_letter ch;
   383 
   384 (*white space: blanks, tabs, newlines, formfeeds*)
   385 val is_blank : string -> bool =
   386   fn " " => true | "\t" => true | "\n" => true | "\^L" => true | _ => false;
   387 
   388 val is_letdig = is_quasi_letter orf is_digit;
   389 
   390 
   391 (*lower all chars of string*)
   392 val to_lower =
   393   let
   394     fun lower ch =
   395       if ch >= "A" andalso ch <= "Z" then
   396         chr (ord ch - ord "A" + ord "a")
   397       else ch;
   398   in implode o (map lower) o explode end;
   399 
   400 
   401 (*enclose in brackets*)
   402 fun enclose lpar rpar str = lpar ^ str ^ rpar;
   403 
   404 (*simple quoting (does not escape special chars)*)
   405 val quote = enclose "\"" "\"";
   406 
   407 (*space_implode "..." (explode "hello"); gives "h...e...l...l...o"*)
   408 fun space_implode a bs = implode (separate a bs);
   409 
   410 val commas = space_implode ", ";
   411 val commas_quote = commas o map quote;
   412 
   413 (*concatenate messages, one per line, into a string*)
   414 val cat_lines = space_implode "\n";
   415 
   416 (*space_explode "." "h.e..l.lo"; gives ["h", "e", "l", "lo"]*)
   417 fun space_explode sep s =
   418   let fun divide [] "" = []
   419         | divide [] part = [part]
   420         | divide (c::s) part =
   421             if c = sep then
   422               (if part = "" then divide s "" else part :: divide s "")
   423             else divide s (part ^ c)
   424   in divide (explode s) "" end;
   425 
   426 
   427 (** lists as sets **)
   428 
   429 (*membership in a list*)
   430 fun x mem [] = false
   431   | x mem (y :: ys) = x = y orelse x mem ys;
   432 
   433 (*generalized membership test*)
   434 fun gen_mem eq (x, []) = false
   435   | gen_mem eq (x, y :: ys) = eq (x, y) orelse gen_mem eq (x, ys);
   436 
   437 
   438 (*insertion into list if not already there*)
   439 fun x ins xs = if x mem xs then xs else x :: xs;
   440 
   441 (*generalized insertion*)
   442 fun gen_ins eq (x, xs) = if gen_mem eq (x, xs) then xs else x :: xs;
   443 
   444 
   445 (*union of sets represented as lists: no repetitions*)
   446 fun xs union [] = xs
   447   | [] union ys = ys
   448   | (x :: xs) union ys = xs union (x ins ys);
   449 
   450 (*generalized union*)
   451 fun gen_union eq (xs, []) = xs
   452   | gen_union eq ([], ys) = ys
   453   | gen_union eq (x :: xs, ys) = gen_union eq (xs, gen_ins eq (x, ys));
   454 
   455 
   456 (*intersection*)
   457 fun [] inter ys = []
   458   | (x :: xs) inter ys =
   459       if x mem ys then x :: (xs inter ys) else xs inter ys;
   460 
   461 
   462 (*subset*)
   463 fun [] subset ys = true
   464   | (x :: xs) subset ys = x mem ys andalso xs subset ys;
   465 
   466 fun gen_subset eq (xs, ys) = forall (fn x => gen_mem eq (x, ys)) xs;
   467 
   468 
   469 (*eq_set*)
   470 
   471 fun eq_set (xs, ys) =
   472   xs = ys orelse (xs subset ys andalso ys subset xs);
   473 
   474 
   475 (*removing an element from a list WITHOUT duplicates*)
   476 fun (y :: ys) \ x = if x = y then ys else y :: (ys \ x)
   477   | [] \ x = [];
   478 
   479 val op \\ = foldl (op \);
   480 
   481 (*removing an element from a list -- possibly WITH duplicates*)
   482 fun gen_rem eq (xs, y) = filter_out (fn x => eq (x, y)) xs;
   483 
   484 val gen_rems = foldl o gen_rem;
   485 
   486 
   487 (*makes a list of the distinct members of the input; preserves order, takes
   488   first of equal elements*)
   489 fun gen_distinct eq lst =
   490   let
   491     val memb = gen_mem eq;
   492 
   493     fun dist (rev_seen, []) = rev rev_seen
   494       | dist (rev_seen, x :: xs) =
   495           if memb (x, rev_seen) then dist (rev_seen, xs)
   496           else dist (x :: rev_seen, xs);
   497   in
   498     dist ([], lst)
   499   end;
   500 
   501 val distinct = gen_distinct (op =);
   502 
   503 
   504 (*returns the tail beginning with the first repeated element, or []*)
   505 fun findrep [] = []
   506   | findrep (x :: xs) = if x mem xs then x :: xs else findrep xs;
   507 
   508 
   509 (*returns a list containing all repeated elements exactly once; preserves
   510   order, takes first of equal elements*)
   511 fun gen_duplicates eq lst =
   512   let
   513     val memb = gen_mem eq;
   514 
   515     fun dups (rev_dups, []) = rev rev_dups
   516       | dups (rev_dups, x :: xs) =
   517           if memb (x, rev_dups) orelse not (memb (x, xs)) then
   518             dups (rev_dups, xs)
   519           else dups (x :: rev_dups, xs);
   520   in
   521     dups ([], lst)
   522   end;
   523 
   524 val duplicates = gen_duplicates (op =);
   525 
   526 
   527 
   528 (** association lists **)
   529 
   530 (*association list lookup*)
   531 fun assoc ([], key) = None
   532   | assoc ((keyi, xi) :: pairs, key) =
   533       if key = keyi then Some xi else assoc (pairs, key);
   534 
   535 fun assocs ps x =
   536   (case assoc (ps, x) of
   537     None => []
   538   | Some ys => ys);
   539 
   540 (*two-fold association list lookup*)
   541 fun assoc2 (aal, (key1, key2)) =
   542   (case assoc (aal, key1) of
   543     Some al => assoc (al, key2)
   544   | None => None);
   545 
   546 (*generalized association list lookup*)
   547 fun gen_assoc eq ([], key) = None
   548   | gen_assoc eq ((keyi, xi) :: pairs, key) =
   549       if eq (key, keyi) then Some xi else gen_assoc eq (pairs, key);
   550 
   551 (*association list update*)
   552 fun overwrite (al, p as (key, _)) =
   553   let fun over ((q as (keyi, _)) :: pairs) =
   554             if keyi = key then p :: pairs else q :: (over pairs)
   555         | over [] = [p]
   556   in over al end;
   557 
   558 
   559 
   560 (** generic tables **)
   561 
   562 (*Tables are supposed to be 'efficient' encodings of lists of elements distinct
   563   wrt. an equality "eq". The extend and merge operations below are optimized
   564   for long-term space efficiency.*)
   565 
   566 (*append (new) elements to a table*)
   567 fun generic_extend _ _ _ tab [] = tab
   568   | generic_extend eq dest_tab mk_tab tab1 lst2 =
   569       let
   570         val lst1 = dest_tab tab1;
   571         val new_lst2 = gen_rems eq (lst2, lst1);
   572       in
   573         if null new_lst2 then tab1
   574         else mk_tab (lst1 @ new_lst2)
   575       end;
   576 
   577 (*append (new) elements of 2nd table to 1st table*)
   578 fun generic_merge eq dest_tab mk_tab tab1 tab2 =
   579   let
   580     val lst1 = dest_tab tab1;
   581     val lst2 = dest_tab tab2;
   582     val new_lst2 = gen_rems eq (lst2, lst1);
   583   in
   584     if null new_lst2 then tab1
   585     else if gen_subset eq (lst1, lst2) then tab2
   586     else mk_tab (lst1 @ new_lst2)
   587   end;
   588 
   589 
   590 (*lists as tables*)
   591 val extend_list = generic_extend (op =) I I;
   592 val merge_lists = generic_merge (op =) I I;
   593 
   594 fun merge_rev_lists xs [] = xs
   595   | merge_rev_lists [] ys = ys
   596   | merge_rev_lists xs (y :: ys) =
   597       (if y mem xs then I else cons y) (merge_rev_lists xs ys);
   598 
   599 
   600 
   601 (** balanced trees **)
   602 
   603 exception Balance;      (*indicates non-positive argument to balancing fun*)
   604 
   605 (*balanced folding; avoids deep nesting*)
   606 fun fold_bal f [x] = x
   607   | fold_bal f [] = raise Balance
   608   | fold_bal f xs =
   609       let val k = length xs div 2
   610       in  f (fold_bal f (take(k, xs)),
   611              fold_bal f (drop(k, xs)))
   612       end;
   613 
   614 (*construct something of the form f(...g(...(x)...)) for balanced access*)
   615 fun access_bal (f, g, x) n i =
   616   let fun acc n i =     (*1<=i<=n*)
   617           if n=1 then x else
   618           let val n2 = n div 2
   619           in  if i<=n2 then f (acc n2 i)
   620                        else g (acc (n-n2) (i-n2))
   621           end
   622   in  if 1<=i andalso i<=n then acc n i else raise Balance  end;
   623 
   624 (*construct ALL such accesses; could try harder to share recursive calls!*)
   625 fun accesses_bal (f, g, x) n =
   626   let fun acc n =
   627           if n=1 then [x] else
   628           let val n2 = n div 2
   629               val acc2 = acc n2
   630           in  if n-n2=n2 then map f acc2 @ map g acc2
   631                          else map f acc2 @ map g (acc (n-n2)) end
   632   in  if 1<=n then acc n else raise Balance  end;
   633 
   634 
   635 
   636 (** input / output **)
   637 
   638 fun prs s = output (std_out, s);
   639 fun writeln s = prs (s ^ "\n");
   640 
   641 
   642 (*print error message and abort to top level*)
   643 exception ERROR;
   644 fun error msg = (writeln msg; raise ERROR);
   645 fun sys_error msg = (writeln "*** SYSTEM ERROR ***"; error msg);
   646 
   647 fun assert p msg = if p then () else error msg;
   648 fun deny p msg = if p then error msg else ();
   649 
   650 (*Assert pred for every member of l, generating a message if pred fails*)
   651 fun assert_all pred l msg_fn = 
   652   let fun asl [] = ()
   653 	| asl (x::xs) = if pred x then asl xs
   654 	                else error (msg_fn x)
   655   in  asl l  end;
   656 
   657 (* FIXME close file (?) *)
   658 (*for the "test" target in Makefiles -- signifies successful termination*)
   659 fun maketest msg =
   660   (writeln msg; output (open_out "test", "Test examples ran successfully\n"));
   661 
   662 
   663 (*print a list surrounded by the brackets lpar and rpar, with comma separator
   664   print nothing for empty list*)
   665 fun print_list (lpar, rpar, pre: 'a -> unit) (l : 'a list) =
   666   let fun prec x = (prs ","; pre x)
   667   in
   668     (case l of
   669       [] => ()
   670     | x::l => (prs lpar; pre x; seq prec l; prs rpar))
   671   end;
   672 
   673 (*print a list of items separated by newlines*)
   674 fun print_list_ln (pre: 'a -> unit) : 'a list -> unit =
   675   seq (fn x => (pre x; writeln ""));
   676 
   677 
   678 val print_int = prs o string_of_int;
   679 
   680 
   681 
   682 (** timing **)
   683 
   684 (*unconditional timing function*)
   685 val timeit = cond_timeit true;
   686 
   687 (*timed application function*)
   688 fun timeap f x = timeit (fn () => f x);
   689 
   690 (*timed "use" function, printing filenames*)
   691 fun time_use fname = timeit (fn () =>
   692   (writeln ("\n**** Starting " ^ fname ^ " ****"); use fname;
   693    writeln ("\n**** Finished " ^ fname ^ " ****")));
   694 
   695 (*For Makefiles: use the file, but exit with error code if errors found.*)
   696 fun exit_use fname = use fname handle _ => exit 1;
   697 
   698 
   699 (** filenames and paths **)
   700 
   701 (*Convert UNIX filename of the form "path/file" to "path/" and "file";
   702   if filename contains no slash, then it returns "" and "file"*)
   703 val split_filename =
   704   (pairself implode) o take_suffix (not_equal "/") o explode;
   705 
   706 val base_name = #2 o split_filename;
   707 
   708 (*Merge splitted filename (path and file);
   709   if path does not end with one a slash is appended*)
   710 fun tack_on "" name = name
   711   | tack_on path name =
   712       if last_elem (explode path) = "/" then path ^ name
   713       else path ^ "/" ^ name;
   714 
   715 (*Remove the extension of a filename, i.e. the part after the last '.'*)
   716 val remove_ext = implode o #1 o take_suffix (not_equal ".") o explode;
   717 
   718 (*Make relative path to reach an absolute location from a different one*)
   719 fun relative_path cur_path dest_path =
   720   let (*Remove common beginning of both paths and make relative path*)
   721       fun mk_relative [] [] = []
   722         | mk_relative [] ds = ds
   723         | mk_relative cs [] = map (fn _ => "..") cs
   724         | mk_relative (c::cs) (d::ds) =
   725             if c = d then mk_relative cs ds
   726             else ".." :: map (fn _ => "..") cs @ (d::ds);
   727   in if cur_path = "" orelse hd (explode cur_path) <> "/" orelse
   728         dest_path = "" orelse hd (explode dest_path) <> "/" then
   729        error "Relative or empty path passed to relative_path"
   730      else ();
   731      space_implode "/" (mk_relative (space_explode "/" cur_path)
   732                                     (space_explode "/" dest_path))
   733   end;
   734 
   735 (*Determine if absolute path1 is a subdirectory of absolute path2*)
   736 fun path1 subdir_of path2 =
   737   if hd (explode path1) <> "/" orelse hd (explode path2) <> "/" then
   738     error "Relative or empty path passed to subdir_of"
   739   else (space_explode "/" path2) prefix (space_explode "/" path1);
   740 
   741 fun absolute_path cwd file =
   742   let fun rm_points [] result = rev result
   743         | rm_points (".."::ds) result = rm_points ds (tl result)
   744         | rm_points ("."::ds) result = rm_points ds result
   745         | rm_points (d::ds) result = rm_points ds (d::result);
   746   in if file = "" then ""
   747      else if hd (explode file) = "/" then file
   748      else "/" ^ space_implode "/"
   749                   (rm_points (space_explode "/" (tack_on cwd file)) [])
   750   end;
   751 
   752 
   753 (** misc functions **)
   754 
   755 (*use the keyfun to make a list of (x, key) pairs*)
   756 fun make_keylist (keyfun: 'a->'b) : 'a list -> ('a * 'b) list =
   757   let fun keypair x = (x, keyfun x)
   758   in map keypair end;
   759 
   760 (*given a list of (x, key) pairs and a searchkey
   761   return the list of xs from each pair whose key equals searchkey*)
   762 fun keyfilter [] searchkey = []
   763   | keyfilter ((x, key) :: pairs) searchkey =
   764       if key = searchkey then x :: keyfilter pairs searchkey
   765       else keyfilter pairs searchkey;
   766 
   767 
   768 (*Partition list into elements that satisfy predicate and those that don't.
   769   Preserves order of elements in both lists.*)
   770 fun partition (pred: 'a->bool) (ys: 'a list) : ('a list * 'a list) =
   771     let fun part ([], answer) = answer
   772           | part (x::xs, (ys, ns)) = if pred(x)
   773             then  part (xs, (x::ys, ns))
   774             else  part (xs, (ys, x::ns))
   775     in  part (rev ys, ([], []))  end;
   776 
   777 
   778 fun partition_eq (eq:'a * 'a -> bool) =
   779     let fun part [] = []
   780           | part (x::ys) = let val (xs, xs') = partition (apl(x, eq)) ys
   781                            in (x::xs)::(part xs') end
   782     in part end;
   783 
   784 
   785 (*Partition a list into buckets  [ bi, b(i+1), ..., bj ]
   786    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
   787 fun partition_list p i j =
   788   let fun part k xs =
   789             if k>j then
   790               (case xs of [] => []
   791                          | _ => raise LIST "partition_list")
   792             else
   793             let val (ns, rest) = partition (p k) xs;
   794             in  ns :: part(k+1)rest  end
   795   in  part i end;
   796 
   797 
   798 (* sorting *)
   799 
   800 (*insertion sort; stable (does not reorder equal elements)
   801   'less' is less-than test on type 'a*)
   802 fun sort (less: 'a*'a -> bool) =
   803   let fun insert (x, []) = [x]
   804         | insert (x, y::ys) =
   805               if less(y, x) then y :: insert (x, ys) else x::y::ys;
   806       fun sort1 [] = []
   807         | sort1 (x::xs) = insert (x, sort1 xs)
   808   in  sort1  end;
   809 
   810 (*sort strings*)
   811 val sort_strings = sort (op <= : string * string -> bool);
   812 
   813 
   814 (* transitive closure (not Warshall's algorithm) *)
   815 
   816 fun transitive_closure [] = []
   817   | transitive_closure ((x, ys)::ps) =
   818       let val qs = transitive_closure ps
   819           val zs = foldl (fn (zs, y) => assocs qs y union zs) (ys, ys)
   820           fun step(u, us) = (u, if x mem us then zs union us else us)
   821       in (x, zs) :: map step qs end;
   822 
   823 
   824 (* generating identifiers *)
   825 
   826 local
   827   val a = ord "a" and z = ord "z" and A = ord "A" and Z = ord "Z"
   828   and k0 = ord "0" and k9 = ord "9"
   829 in
   830 
   831 (*Increment a list of letters like a reversed base 26 number.
   832   If head is "z", bumps chars in tail.
   833   Digits are incremented as if they were integers.
   834   "_" and "'" are not changed.
   835   For making variants of identifiers.*)
   836 
   837 fun bump_int_list(c::cs) = if c="9" then "0" :: bump_int_list cs else
   838         if k0 <= ord(c) andalso ord(c) < k9 then chr(ord(c)+1) :: cs
   839         else "1" :: c :: cs
   840   | bump_int_list([]) = error("bump_int_list: not an identifier");
   841 
   842 fun bump_list([], d) = [d]
   843   | bump_list(["'"], d) = [d, "'"]
   844   | bump_list("z"::cs, _) = "a" :: bump_list(cs, "a")
   845   | bump_list("Z"::cs, _) = "A" :: bump_list(cs, "A")
   846   | bump_list("9"::cs, _) = "0" :: bump_int_list cs
   847   | bump_list(c::cs, _) = let val k = ord(c)
   848         in if (a <= k andalso k < z) orelse (A <= k andalso k < Z) orelse
   849               (k0 <= k andalso k < k9) then chr(k+1) :: cs else
   850            if c="'" orelse c="_" then c :: bump_list(cs, "") else
   851                 error("bump_list: not legal in identifier: " ^
   852                         implode(rev(c::cs)))
   853         end;
   854 
   855 end;
   856 
   857 fun bump_string s : string = implode (rev (bump_list(rev(explode s), "")));
   858 
   859 
   860 (* lexical scanning *)
   861 
   862 (*scan a list of characters into "words" composed of "letters" (recognized by
   863   is_let) and separated by any number of non-"letters"*)
   864 fun scanwords is_let cs =
   865   let fun scan1 [] = []
   866         | scan1 cs =
   867             let val (lets, rest) = take_prefix is_let cs
   868             in implode lets :: scanwords is_let rest end;
   869   in scan1 (#2 (take_prefix (not o is_let) cs)) end;
   870 
   871 end;
   872 
   873 open Library;