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