src/Pure/library.ML
author wenzelm
Mon Jun 21 16:41:06 2004 +0200 (2004-06-21)
changeset 14990 582b655da757
parent 14981 e73f8140af78
child 15035 8c57751cd43f
permissions -rw-r--r--
pretty_abbr;
     1 (*  Title:      Pure/library.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Author:     Markus Wenzel, TU Munich
     5 
     6 Basic library: functions, options, pairs, booleans, lists, integers,
     7 rational numbers, strings, lists as sets, association lists, generic
     8 tables, balanced trees, orders, current directory, misc.
     9 *)
    10 
    11 infix |> |>> |>>> ~~ \ \\ ins ins_string ins_int orf andf prefix upto downto
    12   mem mem_int mem_string union union_int union_string inter inter_int
    13   inter_string subset subset_int subset_string;
    14 
    15 infix 3 oo ooo oooo;
    16 
    17 signature LIBRARY =
    18 sig
    19   (*functions*)
    20   val curry: ('a * 'b -> 'c) -> 'a -> 'b -> 'c
    21   val uncurry: ('a -> 'b -> 'c) -> 'a * 'b -> 'c
    22   val I: 'a -> 'a
    23   val K: 'a -> 'b -> 'a
    24   val |> : 'a * ('a -> 'b) -> 'b
    25   val |>> : ('a * 'b) * ('a -> 'c) -> 'c * 'b
    26   val |>>> : ('a * 'b) * ('a -> 'c * 'd) -> 'c * ('b * 'd)
    27   val apl: 'a * ('a * 'b -> 'c) -> 'b -> 'c
    28   val apr: ('a * 'b -> 'c) * 'b -> 'a -> 'c
    29   val funpow: int -> ('a -> 'a) -> 'a -> 'a
    30   val oo: ('a -> 'b) * ('c -> 'd -> 'a) -> 'c -> 'd -> 'b
    31   val ooo: ('a -> 'b) * ('c -> 'd -> 'e -> 'a) -> 'c -> 'd -> 'e -> 'b
    32   val oooo: ('a -> 'b) * ('c -> 'd -> 'e -> 'f -> 'a) -> 'c -> 'd -> 'e -> 'f -> 'b
    33 
    34   (*stamps*)
    35   type stamp
    36   val stamp: unit -> stamp
    37 
    38   (*options*)
    39   datatype 'a option = None | Some of 'a
    40   exception OPTION
    41   val the: 'a option -> 'a
    42   val if_none: 'a option -> 'a -> 'a
    43   val is_some: 'a option -> bool
    44   val is_none: 'a option -> bool
    45   val apsome: ('a -> 'b) -> 'a option -> 'b option
    46   exception ERROR
    47   val try: ('a -> 'b) -> 'a -> 'b option
    48   val can: ('a -> 'b) -> 'a -> bool
    49   datatype 'a result = Result of 'a | Exn of exn
    50   val capture: ('a -> 'b) -> 'a -> 'b result
    51   val release: 'a result -> 'a
    52   val get_result: 'a result -> 'a option
    53   val get_exn: 'a result -> exn option
    54 
    55   (*pairs*)
    56   val pair: 'a -> 'b -> 'a * 'b
    57   val rpair: 'a -> 'b -> 'b * 'a
    58   val fst: 'a * 'b -> 'a
    59   val snd: 'a * 'b -> 'b
    60   val eq_fst: (''a * 'b) * (''a * 'c) -> bool
    61   val eq_snd: ('a * ''b) * ('c * ''b) -> bool
    62   val swap: 'a * 'b -> 'b * 'a
    63   val apfst: ('a -> 'b) -> 'a * 'c -> 'b * 'c
    64   val apsnd: ('a -> 'b) -> 'c * 'a -> 'c * 'b
    65   val pairself: ('a -> 'b) -> 'a * 'a -> 'b * 'b
    66 
    67   (*booleans*)
    68   val equal: ''a -> ''a -> bool
    69   val not_equal: ''a -> ''a -> bool
    70   val orf: ('a -> bool) * ('a -> bool) -> 'a -> bool
    71   val andf: ('a -> bool) * ('a -> bool) -> 'a -> bool
    72   val exists: ('a -> bool) -> 'a list -> bool
    73   val forall: ('a -> bool) -> 'a list -> bool
    74   val set: bool ref -> bool
    75   val reset: bool ref -> bool
    76   val toggle: bool ref -> bool
    77   val change: 'a ref -> ('a -> 'a) -> unit
    78   val setmp: 'a ref -> 'a -> ('b -> 'c) -> 'b -> 'c
    79   val conditional: bool -> (unit -> unit) -> unit
    80 
    81   (*lists*)
    82   exception LIST of string
    83   val null: 'a list -> bool
    84   val hd: 'a list -> 'a
    85   val tl: 'a list -> 'a list
    86   val cons: 'a -> 'a list -> 'a list
    87   val single: 'a -> 'a list
    88   val append: 'a list -> 'a list -> 'a list
    89   val rev_append: 'a list -> 'a list -> 'a list
    90   val apply: ('a -> 'a) list -> 'a -> 'a
    91   val foldl: ('a * 'b -> 'a) -> 'a * 'b list -> 'a
    92   val foldr: ('a * 'b -> 'b) -> 'a list * 'b -> 'b
    93   val foldr1: ('a * 'a -> 'a) -> 'a list -> 'a
    94   val fold: ('a -> 'b -> 'b) -> 'a list -> 'b -> 'b
    95   val foldl_map: ('a * 'b -> 'a * 'c) -> 'a * 'b list -> 'a * 'c list
    96   val foldln: ('a * int -> 'b -> 'b) -> 'a list -> 'b -> 'b
    97   val length: 'a list -> int
    98   val take: int * 'a list -> 'a list
    99   val drop: int * 'a list -> 'a list
   100   val splitAt: int * 'a list -> 'a list * 'a list
   101   val dropwhile: ('a -> bool) -> 'a list -> 'a list
   102   val nth_elem: int * 'a list -> 'a
   103   val map_nth_elem: int -> ('a -> 'a) -> 'a list -> 'a list
   104   val last_elem: 'a list -> 'a
   105   val split_last: 'a list -> 'a list * 'a
   106   val nth_update: 'a -> int * 'a list -> 'a list
   107   val find_index: ('a -> bool) -> 'a list -> int
   108   val find_index_eq: ''a -> ''a list -> int
   109   val find_first: ('a -> bool) -> 'a list -> 'a option
   110   val get_first: ('a -> 'b option) -> 'a list -> 'b option
   111   val flat: 'a list list -> 'a list
   112   val unflat: 'a list list -> 'b list -> 'b list list
   113   val seq: ('a -> unit) -> 'a list -> unit
   114   val separate: 'a -> 'a list -> 'a list
   115   val replicate: int -> 'a -> 'a list
   116   val multiply: 'a list * 'a list list -> 'a list list
   117   val product: 'a list -> 'b list -> ('a * 'b) list
   118   val filter: ('a -> bool) -> 'a list -> 'a list
   119   val filter_out: ('a -> bool) -> 'a list -> 'a list
   120   val mapfilter: ('a -> 'b option) -> 'a list -> 'b list
   121   val map2: ('a * 'b -> 'c) -> 'a list * 'b list -> 'c list
   122   val exists2: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   123   val forall2: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   124   val seq2: ('a * 'b -> unit) -> 'a list * 'b list -> unit
   125   val ~~ : 'a list * 'b list -> ('a * 'b) list
   126   val split_list: ('a * 'b) list -> 'a list * 'b list
   127   val equal_lists: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   128   val prefix: ''a list * ''a list -> bool
   129   val take_prefix: ('a -> bool) -> 'a list -> 'a list * 'a list
   130   val take_suffix: ('a -> bool) -> 'a list -> 'a list * 'a list
   131   val prefixes1: 'a list -> 'a list list
   132   val suffixes1: 'a list -> 'a list list
   133 
   134   (*integers*)
   135   val gcd: int * int -> int
   136   val lcm: int * int -> int
   137   val inc: int ref -> int
   138   val dec: int ref -> int
   139   val upto: int * int -> int list
   140   val downto: int * int -> int list
   141   val downto0: int list * int -> bool
   142   val radixpand: int * int -> int list
   143   val radixstring: int * string * int -> string
   144   val string_of_int: int -> string
   145   val string_of_indexname: string * int -> string
   146   val read_radixint: int * string list -> int * string list
   147   val read_int: string list -> int * string list
   148   val oct_char: string -> string
   149 
   150   (*rational numbers*)
   151   type rat
   152   exception RAT of string
   153   val rep_rat: rat -> int * int
   154   val ratadd: rat * rat -> rat
   155   val ratmul: rat * rat -> rat
   156   val ratinv: rat -> rat
   157   val int_ratdiv: int * int -> rat
   158   val ratneg: rat -> rat
   159   val rat_of_int: int -> rat
   160 
   161   (*strings*)
   162   val nth_elem_string: int * string -> string
   163   val foldl_string: ('a * string -> 'a) -> 'a * string -> 'a
   164   val exists_string: (string -> bool) -> string -> bool
   165   val enclose: string -> string -> string -> string
   166   val unenclose: string -> string
   167   val quote: string -> string
   168   val space_implode: string -> string list -> string
   169   val commas: string list -> string
   170   val commas_quote: string list -> string
   171   val cat_lines: string list -> string
   172   val space_explode: string -> string -> string list
   173   val split_lines: string -> string list
   174   val prefix_lines: string -> string -> string
   175   val untabify: string list -> string list
   176   val suffix: string -> string -> string
   177   val unsuffix: string -> string -> string
   178   val replicate_string: int -> string -> string
   179   val translate_string: (string -> string) -> string -> string
   180 
   181   (*lists as sets*)
   182   val mem: ''a * ''a list -> bool
   183   val mem_int: int * int list -> bool
   184   val mem_string: string * string list -> bool
   185   val gen_mem: ('a * 'b -> bool) -> 'a * 'b list -> bool
   186   val ins: ''a * ''a list -> ''a list
   187   val ins_int: int * int list -> int list
   188   val ins_string: string * string list -> string list
   189   val gen_ins: ('a * 'a -> bool) -> 'a * 'a list -> 'a list
   190   val union: ''a list * ''a list -> ''a list
   191   val union_int: int list * int list -> int list
   192   val union_string: string list * string list -> string list
   193   val gen_union: ('a * 'a -> bool) -> 'a list * 'a list -> 'a list
   194   val gen_inter: ('a * 'b -> bool) -> 'a list * 'b list -> 'a list
   195   val inter: ''a list * ''a list -> ''a list
   196   val inter_int: int list * int list -> int list
   197   val inter_string: string list * string list -> string list
   198   val subset: ''a list * ''a list -> bool
   199   val subset_int: int list * int list -> bool
   200   val subset_string: string list * string list -> bool
   201   val eq_set: ''a list * ''a list -> bool
   202   val eq_set_string: string list * string list -> bool
   203   val gen_subset: ('a * 'b -> bool) -> 'a list * 'b list -> bool
   204   val \ : ''a list * ''a -> ''a list
   205   val \\ : ''a list * ''a list -> ''a list
   206   val gen_rem: ('a * 'b -> bool) -> 'a list * 'b -> 'a list
   207   val gen_rems: ('a * 'b -> bool) -> 'a list * 'b list -> 'a list
   208   val gen_distinct: ('a * 'a -> bool) -> 'a list -> 'a list
   209   val distinct: ''a list -> ''a list
   210   val findrep: ''a list -> ''a list
   211   val gen_duplicates: ('a * 'a -> bool) -> 'a list -> 'a list
   212   val duplicates: ''a list -> ''a list
   213 
   214   (*association lists*)
   215   val assoc: (''a * 'b) list * ''a -> 'b option
   216   val assoc_int: (int * 'a) list * int -> 'a option
   217   val assoc_string: (string * 'a) list * string -> 'a option
   218   val assoc_string_int: ((string * int) * 'a) list * (string * int) -> 'a option
   219   val assocs: (''a * 'b list) list -> ''a -> 'b list
   220   val assoc2: (''a * (''b * 'c) list) list * (''a * ''b) -> 'c option
   221   val gen_assoc: ('a * 'b -> bool) -> ('b * 'c) list * 'a -> 'c option
   222   val overwrite: (''a * 'b) list * (''a * 'b) -> (''a * 'b) list
   223   val gen_overwrite: ('a * 'a -> bool) -> ('a * 'b) list * ('a * 'b) -> ('a * 'b) list
   224 
   225   (*lists as tables*)
   226   val gen_merge_lists: ('a * 'a -> bool) -> 'a list -> 'a list -> 'a list
   227   val gen_merge_lists': ('a * 'a -> bool) -> 'a list -> 'a list -> 'a list
   228   val merge_lists: ''a list -> ''a list -> ''a list
   229   val merge_lists': ''a list -> ''a list -> ''a list
   230   val merge_alists: (''a * 'b) list -> (''a * 'b) list -> (''a * 'b) list
   231 
   232   (*balanced trees*)
   233   exception Balance
   234   val fold_bal: ('a * 'a -> 'a) -> 'a list -> 'a
   235   val access_bal: ('a -> 'a) * ('a -> 'a) * 'a -> int -> int -> 'a
   236   val accesses_bal: ('a -> 'a) * ('a -> 'a) * 'a -> int -> 'a list
   237 
   238   (*orders*)
   239   val rev_order: order -> order
   240   val make_ord: ('a * 'a -> bool) -> 'a * 'a -> order
   241   val int_ord: int * int -> order
   242   val string_ord: string * string -> order
   243   val prod_ord: ('a * 'b -> order) -> ('c * 'd -> order) -> ('a * 'c) * ('b * 'd) -> order
   244   val dict_ord: ('a * 'b -> order) -> 'a list * 'b list -> order
   245   val list_ord: ('a * 'b -> order) -> 'a list * 'b list -> order
   246   val sort: ('a * 'a -> order) -> 'a list -> 'a list
   247   val sort_strings: string list -> string list
   248   val sort_wrt: ('a -> string) -> 'a list -> 'a list
   249   val unique_strings: string list -> string list
   250 
   251   (*random numbers*)
   252   exception RANDOM
   253   val random: unit -> real
   254   val random_range: int -> int -> int
   255   val one_of: 'a list -> 'a
   256   val frequency: (int * 'a) list -> 'a
   257 
   258   (*current directory*)
   259   val cd: string -> unit
   260   val pwd: unit -> string
   261 
   262   (*misc*)
   263   val make_keylist: ('a -> 'b) -> 'a list -> ('a * 'b) list
   264   val keyfilter: ('a * ''b) list -> ''b -> 'a list
   265   val partition: ('a -> bool) -> 'a list -> 'a list * 'a list
   266   val partition_eq: ('a * 'a -> bool) -> 'a list -> 'a list list
   267   val partition_list: (int -> 'a -> bool) -> int -> int -> 'a list -> 'a list list
   268   val gensym: string -> string
   269   val scanwords: (string -> bool) -> string list -> string list
   270 end;
   271 
   272 structure Library: LIBRARY =
   273 struct
   274 
   275 
   276 (** functions **)
   277 
   278 (*handy combinators*)
   279 fun curry f x y = f (x, y);
   280 fun uncurry f (x, y) = f x y;
   281 fun I x = x;
   282 fun K x y = x;
   283 
   284 (*reverse apply*)
   285 fun (x |> f) = f x;
   286 fun ((x, y) |>> f) = (f x, y);
   287 fun ((x, y) |>>> f) = let val (x', z) = f x in (x', (y, z)) end;
   288 
   289 (*application of (infix) operator to its left or right argument*)
   290 fun apl (x, f) y = f (x, y);
   291 fun apr (f, y) x = f (x, y);
   292 
   293 (*function exponentiation: f(...(f x)...) with n applications of f*)
   294 fun funpow n f x =
   295   let fun rep (0, x) = x
   296         | rep (n, x) = rep (n - 1, f x)
   297   in rep (n, x) end;
   298 
   299 (*concatenation: 2 and 3 args*)
   300 fun (f oo g) x y = f (g x y);
   301 fun (f ooo g) x y z = f (g x y z);
   302 fun (f oooo g) x y z w = f (g x y z w);
   303 
   304 
   305 
   306 (** stamps **)
   307 
   308 type stamp = unit ref;
   309 val stamp: unit -> stamp = ref;
   310 
   311 
   312 
   313 (** options **)
   314 
   315 datatype 'a option = None | Some of 'a;
   316 
   317 exception OPTION;
   318 
   319 fun the (Some x) = x
   320   | the None = raise OPTION;
   321 
   322 (*strict!*)
   323 fun if_none None y = y
   324   | if_none (Some x) _ = x;
   325 
   326 fun is_some (Some _) = true
   327   | is_some None = false;
   328 
   329 fun is_none (Some _) = false
   330   | is_none None = true;
   331 
   332 fun apsome f (Some x) = Some (f x)
   333   | apsome _ None = None;
   334 
   335 
   336 (* exception handling *)
   337 
   338 exception ERROR;
   339 
   340 fun try f x = Some (f x)
   341   handle Interrupt => raise Interrupt | ERROR => raise ERROR | _ => None;
   342 
   343 fun can f x = is_some (try f x);
   344 
   345 
   346 datatype 'a result =
   347   Result of 'a |
   348   Exn of exn;
   349 
   350 fun capture f x = Result (f x) handle e => Exn e;
   351 
   352 fun release (Result y) = y
   353   | release (Exn e) = raise e;
   354 
   355 fun get_result (Result x) = Some x
   356   | get_result _ = None;
   357 
   358 fun get_exn (Exn exn) = Some exn
   359   | get_exn _ = None;
   360 
   361 
   362 
   363 (** pairs **)
   364 
   365 fun pair x y = (x, y);
   366 fun rpair x y = (y, x);
   367 
   368 fun fst (x, y) = x;
   369 fun snd (x, y) = y;
   370 
   371 fun eq_fst ((x1, _), (x2, _)) = x1 = x2;
   372 fun eq_snd ((_, y1), (_, y2)) = y1 = y2;
   373 
   374 fun swap (x, y) = (y, x);
   375 
   376 (*apply function to components*)
   377 fun apfst f (x, y) = (f x, y);
   378 fun apsnd f (x, y) = (x, f y);
   379 fun pairself f (x, y) = (f x, f y);
   380 
   381 
   382 
   383 (** booleans **)
   384 
   385 (* equality *)
   386 
   387 fun equal x y = x = y;
   388 fun not_equal x y = x <> y;
   389 
   390 
   391 (* operators for combining predicates *)
   392 
   393 fun (p orf q) = fn x => p x orelse q x;
   394 fun (p andf q) = fn x => p x andalso q x;
   395 
   396 
   397 (* predicates on lists *)
   398 
   399 (*exists pred [x1, ..., xn] ===> pred x1 orelse ... orelse pred xn*)
   400 fun exists (pred: 'a -> bool) : 'a list -> bool =
   401   let fun boolf [] = false
   402         | boolf (x :: xs) = pred x orelse boolf xs
   403   in boolf end;
   404 
   405 (*forall pred [x1, ..., xn] ===> pred x1 andalso ... andalso pred xn*)
   406 fun forall (pred: 'a -> bool) : 'a list -> bool =
   407   let fun boolf [] = true
   408         | boolf (x :: xs) = pred x andalso boolf xs
   409   in boolf end;
   410 
   411 
   412 (* flags *)
   413 
   414 fun set flag = (flag := true; true);
   415 fun reset flag = (flag := false; false);
   416 fun toggle flag = (flag := not (! flag); ! flag);
   417 
   418 fun change r f = r := f (! r);
   419 
   420 (*temporarily set flag, handling exceptions*)
   421 fun setmp flag value f x =
   422   let
   423     val orig_value = ! flag;
   424     fun return y = (flag := orig_value; y);
   425   in
   426     flag := value;
   427     return (f x handle exn => (return (); raise exn))
   428   end;
   429 
   430 
   431 (* conditional execution *)
   432 
   433 fun conditional b f = if b then f () else ();
   434 
   435 
   436 
   437 (** lists **)
   438 
   439 exception LIST of string;
   440 
   441 fun null [] = true
   442   | null (_ :: _) = false;
   443 
   444 fun hd [] = raise LIST "hd"
   445   | hd (x :: _) = x;
   446 
   447 fun tl [] = raise LIST "tl"
   448   | tl (_ :: xs) = xs;
   449 
   450 fun cons x xs = x :: xs;
   451 fun single x = [x];
   452 
   453 fun append xs ys = xs @ ys;
   454 
   455 (* tail recursive version *)
   456 fun rev_append [] ys = ys
   457   | rev_append (x :: xs) ys = rev_append xs (x :: ys);
   458 
   459 fun apply [] x = x
   460   | apply (f :: fs) x = apply fs (f x);
   461 
   462 
   463 (* fold *)
   464 
   465 (*the following versions of fold are designed to fit nicely with infixes*)
   466 
   467 (*  (op @) (e, [x1, ..., xn])  ===>  ((e @ x1) @ x2) ... @ xn
   468     for operators that associate to the left (TAIL RECURSIVE)*)
   469 fun foldl (f: 'a * 'b -> 'a) : 'a * 'b list -> 'a =
   470   let fun itl (e, [])  = e
   471         | itl (e, a::l) = itl (f(e, a), l)
   472   in  itl end;
   473 
   474 (*  (op @) ([x1, ..., xn], e)  ===>   x1 @ (x2 ... @ (xn @ e))
   475     for operators that associate to the right (not tail recursive)*)
   476 fun foldr f (l, e) =
   477   let fun itr [] = e
   478         | itr (a::l) = f(a, itr l)
   479   in  itr l  end;
   480 
   481 (*  (op @) [x1, ..., xn]  ===>   x1 @ (x2 ... @ (x[n-1] @ xn))
   482     for n > 0, operators that associate to the right (not tail recursive)*)
   483 fun foldr1 f l =
   484   let fun itr [x] = x
   485         | itr (x::l) = f(x, itr l)
   486   in  itr l  end;
   487 
   488 fun fold f xs y = foldl (fn (y', x) => f x y') (y, xs);
   489 
   490 fun foldl_map _ (x, []) = (x, [])
   491   | foldl_map f (x, y :: ys) =
   492       let
   493         val (x', y') = f (x, y);
   494         val (x'', ys') = foldl_map f (x', ys);
   495       in (x'', y' :: ys') end;
   496 
   497 fun foldln f xs e = fst (foldl (fn ((e,i), x) => (f (x,i) e, i+1)) ((e,1),xs));
   498 
   499 (* basic list functions *)
   500 
   501 (*length of a list, should unquestionably be a standard function*)
   502 local fun length1 (n, [])  = n   (*TAIL RECURSIVE*)
   503         | length1 (n, x :: xs) = length1 (n + 1, xs)
   504 in  fun length l = length1 (0, l) end;
   505 
   506 (*take the first n elements from a list*)
   507 fun take (n, []) = []
   508   | take (n, x :: xs) =
   509       if n > 0 then x :: take (n - 1, xs) else [];
   510 
   511 (*drop the first n elements from a list*)
   512 fun drop (n, []) = []
   513   | drop (n, x :: xs) =
   514       if n > 0 then drop (n - 1, xs) else x :: xs;
   515 
   516 fun splitAt(n,[]) = ([],[])
   517   | splitAt(n,xs as x::ys) =
   518       if n>0 then let val (ps,qs) = splitAt(n-1,ys) in (x::ps,qs) end
   519       else ([],xs)
   520 
   521 fun dropwhile P [] = []
   522   | dropwhile P (ys as x::xs) = if P x then dropwhile P xs else ys;
   523 
   524 (*return nth element of a list, where 0 designates the first element;
   525   raise EXCEPTION if list too short*)
   526 fun nth_elem NL =
   527   (case drop NL of
   528     [] => raise LIST "nth_elem"
   529   | x :: _ => x);
   530 
   531 fun map_nth_elem 0 f (x :: xs) = f x :: xs
   532   | map_nth_elem n f (x :: xs) = x :: map_nth_elem (n - 1) f xs
   533   | map_nth_elem _ _ [] = raise LIST "map_nth_elem";
   534 
   535 (*last element of a list*)
   536 fun last_elem [] = raise LIST "last_elem"
   537   | last_elem [x] = x
   538   | last_elem (_ :: xs) = last_elem xs;
   539 
   540 (*rear decomposition*)
   541 fun split_last [] = raise LIST "split_last"
   542   | split_last [x] = ([], x)
   543   | split_last (x :: xs) = apfst (cons x) (split_last xs);
   544 
   545 (*update nth element*)
   546 fun nth_update x n_xs =
   547     (case splitAt n_xs of
   548       (_,[]) => raise LIST "nth_update"
   549     | (prfx, _ :: sffx') => prfx @ (x :: sffx'))
   550 
   551 (*find the position of an element in a list*)
   552 fun find_index pred =
   553   let fun find _ [] = ~1
   554         | find n (x :: xs) = if pred x then n else find (n + 1) xs;
   555   in find 0 end;
   556 
   557 fun find_index_eq x = find_index (equal x);
   558 
   559 (*find first element satisfying predicate*)
   560 fun find_first _ [] = None
   561   | find_first pred (x :: xs) =
   562       if pred x then Some x else find_first pred xs;
   563 
   564 (*get first element by lookup function*)
   565 fun get_first _ [] = None
   566   | get_first f (x :: xs) =
   567       (case f x of
   568         None => get_first f xs
   569       | some => some);
   570 
   571 (*flatten a list of lists to a list*)
   572 fun flat (ls: 'c list list) : 'c list = foldr (op @) (ls, []);
   573 
   574 fun unflat (xs :: xss) ys =
   575       let val (ps,qs) = splitAt(length xs,ys)
   576       in ps :: unflat xss qs end
   577   | unflat [] [] = []
   578   | unflat _ _ = raise LIST "unflat";
   579 
   580 (*like Lisp's MAPC -- seq proc [x1, ..., xn] evaluates
   581   (proc x1; ...; proc xn) for side effects*)
   582 fun seq (proc: 'a -> unit) : 'a list -> unit =
   583   let fun seqf [] = ()
   584         | seqf (x :: xs) = (proc x; seqf xs)
   585   in seqf end;
   586 
   587 (*separate s [x1, x2, ..., xn]  ===>  [x1, s, x2, s, ..., s, xn]*)
   588 fun separate s (x :: (xs as _ :: _)) = x :: s :: separate s xs
   589   | separate _ xs = xs;
   590 
   591 (*make the list [x, x, ..., x] of length n*)
   592 fun replicate n (x: 'a) : 'a list =
   593   let fun rep (0, xs) = xs
   594         | rep (n, xs) = rep (n - 1, x :: xs)
   595   in
   596     if n < 0 then raise LIST "replicate"
   597     else rep (n, [])
   598   end;
   599 
   600 fun translate_string f = String.translate (f o String.str);
   601 
   602 (*multiply [a, b, c, ...] * [xs, ys, zs, ...]*)
   603 fun multiply ([], _) = []
   604   | multiply (x :: xs, yss) = map (cons x) yss @ multiply (xs, yss);
   605 
   606 (*direct product*)
   607 fun product _ [] = []
   608   | product [] _ = []
   609   | product (x :: xs) ys = map (pair x) ys @ product xs ys;
   610 
   611 
   612 (* filter *)
   613 
   614 (*copy the list preserving elements that satisfy the predicate*)
   615 fun filter (pred: 'a->bool) : 'a list -> 'a list =
   616   let fun filt [] = []
   617         | filt (x :: xs) = if pred x then x :: filt xs else filt xs
   618   in filt end;
   619 
   620 fun filter_out f = filter (not o f);
   621 
   622 fun mapfilter (f: 'a -> 'b option) ([]: 'a list) = [] : 'b list
   623   | mapfilter f (x :: xs) =
   624       (case f x of
   625         None => mapfilter f xs
   626       | Some y => y :: mapfilter f xs);
   627 
   628 
   629 (* lists of pairs *)
   630 
   631 fun map2 _ ([], []) = []
   632   | map2 f (x :: xs, y :: ys) = (f (x, y) :: map2 f (xs, ys))
   633   | map2 _ _ = raise LIST "map2";
   634 
   635 fun exists2 _ ([], []) = false
   636   | exists2 pred (x :: xs, y :: ys) = pred (x, y) orelse exists2 pred (xs, ys)
   637   | exists2 _ _ = raise LIST "exists2";
   638 
   639 fun forall2 _ ([], []) = true
   640   | forall2 pred (x :: xs, y :: ys) = pred (x, y) andalso forall2 pred (xs, ys)
   641   | forall2 _ _ = raise LIST "forall2";
   642 
   643 fun seq2 _ ([], []) = ()
   644   | seq2 f (x :: xs, y :: ys) = (f (x, y); seq2 f (xs, ys))
   645   | seq2 _ _ = raise LIST "seq2";
   646 
   647 (*combine two lists forming a list of pairs:
   648   [x1, ..., xn] ~~ [y1, ..., yn]  ===>  [(x1, y1), ..., (xn, yn)]*)
   649 fun [] ~~ [] = []
   650   | (x :: xs) ~~ (y :: ys) = (x, y) :: (xs ~~ ys)
   651   | _ ~~ _ = raise LIST "~~";
   652 
   653 (*inverse of ~~; the old 'split':
   654   [(x1, y1), ..., (xn, yn)]  ===>  ([x1, ..., xn], [y1, ..., yn])*)
   655 fun split_list (l: ('a * 'b) list) = (map #1 l, map #2 l);
   656 
   657 fun equal_lists eq (xs, ys) = length xs = length ys andalso forall2 eq (xs, ys);
   658 
   659 
   660 (* prefixes, suffixes *)
   661 
   662 fun [] prefix _ = true
   663   | (x :: xs) prefix (y :: ys) = x = y andalso (xs prefix ys)
   664   | _ prefix _ = false;
   665 
   666 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., x(i-1)], [xi, ..., xn])
   667    where xi is the first element that does not satisfy the predicate*)
   668 fun take_prefix (pred : 'a -> bool)  (xs: 'a list) : 'a list * 'a list =
   669   let fun take (rxs, []) = (rev rxs, [])
   670         | take (rxs, x :: xs) =
   671             if  pred x  then  take(x :: rxs, xs)  else  (rev rxs, x :: xs)
   672   in  take([], xs)  end;
   673 
   674 (* [x1, ..., xi, ..., xn]  --->  ([x1, ..., xi], [x(i+1), ..., xn])
   675    where xi is the last element that does not satisfy the predicate*)
   676 fun take_suffix _ [] = ([], [])
   677   | take_suffix pred (x :: xs) =
   678       (case take_suffix pred xs of
   679         ([], sffx) => if pred x then ([], x :: sffx) else ([x], sffx)
   680       | (prfx, sffx) => (x :: prfx, sffx));
   681 
   682 fun prefixes1 [] = []
   683   | prefixes1 (x :: xs) = map (cons x) ([] :: prefixes1 xs);
   684 
   685 fun suffixes1 xs = map rev (prefixes1 (rev xs));
   686 
   687 
   688 
   689 (** integers **)
   690 
   691 fun gcd(x,y) =
   692   let fun gxd x y =
   693     if y = 0 then x else gxd y (x mod y)
   694   in if x < y then gxd y x else gxd x y end;
   695 
   696 fun lcm(x,y) = (x * y) div gcd(x,y);
   697 
   698 fun inc i = (i := ! i + 1; ! i);
   699 fun dec i = (i := ! i - 1; ! i);
   700 
   701 
   702 (* lists of integers *)
   703 
   704 (*make the list [from, from + 1, ..., to]*)
   705 fun (from upto to) =
   706   if from > to then [] else from :: ((from + 1) upto to);
   707 
   708 (*make the list [from, from - 1, ..., to]*)
   709 fun (from downto to) =
   710   if from < to then [] else from :: ((from - 1) downto to);
   711 
   712 (*predicate: downto0 (is, n) <=> is = [n, n - 1, ..., 0]*)
   713 fun downto0 (i :: is, n) = i = n andalso downto0 (is, n - 1)
   714   | downto0 ([], n) = n = ~1;
   715 
   716 
   717 (* convert integers to strings *)
   718 
   719 (*expand the number in the given base;
   720   example: radixpand (2, 8) gives [1, 0, 0, 0]*)
   721 fun radixpand (base, num) : int list =
   722   let
   723     fun radix (n, tail) =
   724       if n < base then n :: tail
   725       else radix (n div base, (n mod base) :: tail)
   726   in radix (num, []) end;
   727 
   728 (*expands a number into a string of characters starting from "zerochar";
   729   example: radixstring (2, "0", 8) gives "1000"*)
   730 fun radixstring (base, zerochar, num) =
   731   let val offset = ord zerochar;
   732       fun chrof n = chr (offset + n)
   733   in implode (map chrof (radixpand (base, num))) end;
   734 
   735 
   736 val string_of_int = Int.toString;
   737 
   738 fun string_of_indexname (a,0) = a
   739   | string_of_indexname (a,i) = a ^ "_" ^ Int.toString i;
   740 
   741 
   742 (* read integers *)
   743 
   744 fun read_radixint (radix: int, cs) : int * string list =
   745   let val zero = ord"0"
   746       val limit = zero+radix
   747       fun scan (num,[]) = (num,[])
   748         | scan (num, c::cs) =
   749               if  zero <= ord c  andalso  ord c < limit
   750               then scan(radix*num + ord c - zero, cs)
   751               else (num, c::cs)
   752   in  scan(0,cs)  end;
   753 
   754 fun read_int cs = read_radixint (10, cs);
   755 
   756 fun oct_char s = chr (#1 (read_radixint (8, explode s)));
   757 
   758 
   759 
   760 (** strings **)
   761 
   762 (*functions tuned for strings, avoiding explode*)
   763 
   764 fun nth_elem_string (i, str) =
   765   (case try String.substring (str, i, 1) of
   766     Some s => s
   767   | None => raise LIST "nth_elem_string");
   768 
   769 fun foldl_string f (x0, str) =
   770   let
   771     val n = size str;
   772     fun fold (x, i) =
   773       if i < n then fold (f (x, String.substring (str, i, 1)), i + 1) else x;
   774   in fold (x0, 0) end;
   775 
   776 fun exists_string pred str =
   777   let
   778     val n = size str;
   779     fun ex i = i < n andalso (pred (String.substring (str, i, 1)) orelse ex (i + 1));
   780   in ex 0 end;
   781 
   782 (*enclose in brackets*)
   783 fun enclose lpar rpar str = lpar ^ str ^ rpar;
   784 fun unenclose str = String.substring (str, 1, size str - 2);
   785 
   786 (*simple quoting (does not escape special chars)*)
   787 val quote = enclose "\"" "\"";
   788 
   789 (*space_implode "..." (explode "hello") = "h...e...l...l...o"*)
   790 fun space_implode a bs = implode (separate a bs);
   791 
   792 val commas = space_implode ", ";
   793 val commas_quote = commas o map quote;
   794 
   795 (*concatenate messages, one per line, into a string*)
   796 val cat_lines = space_implode "\n";
   797 
   798 (*space_explode "." "h.e..l.lo" = ["h", "e", "", "l", "lo"]*)
   799 fun space_explode _ "" = []
   800   | space_explode sep str =
   801       let
   802         fun expl chs =
   803           (case take_prefix (not_equal sep) chs of
   804             (cs, []) => [implode cs]
   805           | (cs, _ :: cs') => implode cs :: expl cs');
   806       in expl (explode str) end;
   807 
   808 val split_lines = space_explode "\n";
   809 
   810 fun prefix_lines "" txt = txt
   811   | prefix_lines prfx txt = txt |> split_lines |> map (fn s => prfx ^ s) |> cat_lines;
   812 
   813 (*untabify*)
   814 fun untabify chs =
   815   let
   816     val tab_width = 8;
   817 
   818     fun untab (_, "\n") = (0, ["\n"])
   819       | untab (pos, "\t") =
   820           let val d = tab_width - (pos mod tab_width) in (pos + d, replicate d " ") end
   821       | untab (pos, c) = (pos + 1, [c]);
   822   in
   823     if not (exists (equal "\t") chs) then chs
   824     else flat (#2 (foldl_map untab (0, chs)))
   825   end;
   826 
   827 (*append suffix*)
   828 fun suffix sfx s = s ^ sfx;
   829 
   830 (*remove suffix*)
   831 fun unsuffix sfx s =
   832   let
   833     val cs = explode s;
   834     val prfx_len = size s - size sfx;
   835   in
   836     if prfx_len >= 0 andalso implode (drop (prfx_len, cs)) = sfx then
   837       implode (take (prfx_len, cs))
   838     else raise LIST "unsuffix"
   839   end;
   840 
   841 fun replicate_string 0 _ = ""
   842   | replicate_string 1 a = a
   843   | replicate_string k a =
   844       if k mod 2 = 0 then replicate_string (k div 2) (a ^ a)
   845       else replicate_string (k div 2) (a ^ a) ^ a;
   846 
   847 
   848 
   849 (** lists as sets **)
   850 
   851 (*membership in a list*)
   852 fun x mem [] = false
   853   | x mem (y :: ys) = x = y orelse x mem ys;
   854 
   855 (*membership in a list, optimized version for ints*)
   856 fun (x:int) mem_int [] = false
   857   | x mem_int (y :: ys) = x = y orelse x mem_int ys;
   858 
   859 (*membership in a list, optimized version for strings*)
   860 fun (x:string) mem_string [] = false
   861   | x mem_string (y :: ys) = x = y orelse x mem_string ys;
   862 
   863 (*generalized membership test*)
   864 fun gen_mem eq (x, []) = false
   865   | gen_mem eq (x, y :: ys) = eq (x, y) orelse gen_mem eq (x, ys);
   866 
   867 
   868 (*insertion into list if not already there*)
   869 fun (x ins xs) = if x mem xs then xs else x :: xs;
   870 
   871 (*insertion into list, optimized version for ints*)
   872 fun (x ins_int xs) = if x mem_int xs then xs else x :: xs;
   873 
   874 (*insertion into list, optimized version for strings*)
   875 fun (x ins_string xs) = if x mem_string xs then xs else x :: xs;
   876 
   877 (*generalized insertion*)
   878 fun gen_ins eq (x, xs) = if gen_mem eq (x, xs) then xs else x :: xs;
   879 
   880 
   881 (*union of sets represented as lists: no repetitions*)
   882 fun xs union [] = xs
   883   | [] union ys = ys
   884   | (x :: xs) union ys = xs union (x ins ys);
   885 
   886 (*union of sets, optimized version for ints*)
   887 fun (xs:int list) union_int [] = xs
   888   | [] union_int ys = ys
   889   | (x :: xs) union_int ys = xs union_int (x ins_int ys);
   890 
   891 (*union of sets, optimized version for strings*)
   892 fun (xs:string list) union_string [] = xs
   893   | [] union_string ys = ys
   894   | (x :: xs) union_string ys = xs union_string (x ins_string ys);
   895 
   896 (*generalized union*)
   897 fun gen_union eq (xs, []) = xs
   898   | gen_union eq ([], ys) = ys
   899   | gen_union eq (x :: xs, ys) = gen_union eq (xs, gen_ins eq (x, ys));
   900 
   901 
   902 (*intersection*)
   903 fun [] inter ys = []
   904   | (x :: xs) inter ys =
   905       if x mem ys then x :: (xs inter ys) else xs inter ys;
   906 
   907 (*intersection, optimized version for ints*)
   908 fun ([]:int list) inter_int ys = []
   909   | (x :: xs) inter_int ys =
   910       if x mem_int ys then x :: (xs inter_int ys) else xs inter_int ys;
   911 
   912 (*intersection, optimized version for strings *)
   913 fun ([]:string list) inter_string ys = []
   914   | (x :: xs) inter_string ys =
   915       if x mem_string ys then x :: (xs inter_string ys) else xs inter_string ys;
   916 
   917 (*generalized intersection*)
   918 fun gen_inter eq ([], ys) = []
   919   | gen_inter eq (x::xs, ys) =
   920       if gen_mem eq (x,ys) then x :: gen_inter eq (xs, ys)
   921                            else      gen_inter eq (xs, ys);
   922 
   923 
   924 (*subset*)
   925 fun [] subset ys = true
   926   | (x :: xs) subset ys = x mem ys andalso xs subset ys;
   927 
   928 (*subset, optimized version for ints*)
   929 fun ([]:int list) subset_int ys = true
   930   | (x :: xs) subset_int ys = x mem_int ys andalso xs subset_int ys;
   931 
   932 (*subset, optimized version for strings*)
   933 fun ([]:string list) subset_string ys = true
   934   | (x :: xs) subset_string ys = x mem_string ys andalso xs subset_string ys;
   935 
   936 (*set equality*)
   937 fun eq_set (xs, ys) =
   938   xs = ys orelse (xs subset ys andalso ys subset xs);
   939 
   940 (*set equality for strings*)
   941 fun eq_set_string ((xs:string list), ys) =
   942   xs = ys orelse (xs subset_string ys andalso ys subset_string xs);
   943 
   944 fun gen_subset eq (xs, ys) = forall (fn x => gen_mem eq (x, ys)) xs;
   945 
   946 
   947 (*removing an element from a list WITHOUT duplicates*)
   948 fun (y :: ys) \ x = if x = y then ys else y :: (ys \ x)
   949   | [] \ x = [];
   950 
   951 fun ys \\ xs = foldl (op \) (ys,xs);
   952 
   953 (*removing an element from a list -- possibly WITH duplicates*)
   954 fun gen_rem eq (xs, y) = filter_out (fn x => eq (x, y)) xs;
   955 fun gen_rems eq (xs, ys) = filter_out (fn x => gen_mem eq (x, ys)) xs;
   956 
   957 
   958 (*makes a list of the distinct members of the input; preserves order, takes
   959   first of equal elements*)
   960 fun gen_distinct eq lst =
   961   let
   962     val memb = gen_mem eq;
   963 
   964     fun dist (rev_seen, []) = rev rev_seen
   965       | dist (rev_seen, x :: xs) =
   966           if memb (x, rev_seen) then dist (rev_seen, xs)
   967           else dist (x :: rev_seen, xs);
   968   in
   969     dist ([], lst)
   970   end;
   971 
   972 fun distinct l = gen_distinct (op =) l;
   973 
   974 
   975 (*returns the tail beginning with the first repeated element, or []*)
   976 fun findrep [] = []
   977   | findrep (x :: xs) = if x mem xs then x :: xs else findrep xs;
   978 
   979 
   980 (*returns a list containing all repeated elements exactly once; preserves
   981   order, takes first of equal elements*)
   982 fun gen_duplicates eq lst =
   983   let
   984     val memb = gen_mem eq;
   985 
   986     fun dups (rev_dups, []) = rev rev_dups
   987       | dups (rev_dups, x :: xs) =
   988           if memb (x, rev_dups) orelse not (memb (x, xs)) then
   989             dups (rev_dups, xs)
   990           else dups (x :: rev_dups, xs);
   991   in
   992     dups ([], lst)
   993   end;
   994 
   995 fun duplicates l = gen_duplicates (op =) l;
   996 
   997 
   998 
   999 (** association lists **)
  1000 
  1001 (*association list lookup*)
  1002 fun assoc ([], key) = None
  1003   | assoc ((keyi, xi) :: pairs, key) =
  1004       if key = keyi then Some xi else assoc (pairs, key);
  1005 
  1006 (*association list lookup, optimized version for ints*)
  1007 fun assoc_int ([], (key:int)) = None
  1008   | assoc_int ((keyi, xi) :: pairs, key) =
  1009       if key = keyi then Some xi else assoc_int (pairs, key);
  1010 
  1011 (*association list lookup, optimized version for strings*)
  1012 fun assoc_string ([], (key:string)) = None
  1013   | assoc_string ((keyi, xi) :: pairs, key) =
  1014       if key = keyi then Some xi else assoc_string (pairs, key);
  1015 
  1016 (*association list lookup, optimized version for string*ints*)
  1017 fun assoc_string_int ([], (key:string*int)) = None
  1018   | assoc_string_int ((keyi, xi) :: pairs, key) =
  1019       if key = keyi then Some xi else assoc_string_int (pairs, key);
  1020 
  1021 fun assocs ps x =
  1022   (case assoc (ps, x) of
  1023     None => []
  1024   | Some ys => ys);
  1025 
  1026 (*two-fold association list lookup*)
  1027 fun assoc2 (aal, (key1, key2)) =
  1028   (case assoc (aal, key1) of
  1029     Some al => assoc (al, key2)
  1030   | None => None);
  1031 
  1032 (*generalized association list lookup*)
  1033 fun gen_assoc eq ([], key) = None
  1034   | gen_assoc eq ((keyi, xi) :: pairs, key) =
  1035       if eq (key, keyi) then Some xi else gen_assoc eq (pairs, key);
  1036 
  1037 (*association list update*)
  1038 fun overwrite (al, p as (key, _)) =
  1039   let fun over ((q as (keyi, _)) :: pairs) =
  1040             if keyi = key then p :: pairs else q :: (over pairs)
  1041         | over [] = [p]
  1042   in over al end;
  1043 
  1044 fun gen_overwrite eq (al, p as (key, _)) =
  1045   let fun over ((q as (keyi, _)) :: pairs) =
  1046             if eq (keyi, key) then p :: pairs else q :: (over pairs)
  1047         | over [] = [p]
  1048   in over al end;
  1049 
  1050 
  1051 (* lists as tables *)
  1052 
  1053 fun gen_merge_lists _ xs [] = xs
  1054   | gen_merge_lists _ [] ys = ys
  1055   | gen_merge_lists eq xs ys = xs @ gen_rems eq (ys, xs);
  1056 
  1057 fun gen_merge_lists' _ xs [] = xs
  1058   | gen_merge_lists' _ [] ys = ys
  1059   | gen_merge_lists' eq xs ys = gen_rems eq (ys, xs) @ xs;
  1060 
  1061 fun merge_lists xs ys = gen_merge_lists (op =) xs ys;
  1062 fun merge_lists' xs ys = gen_merge_lists' (op =) xs ys;
  1063 fun merge_alists al = gen_merge_lists eq_fst al;
  1064 
  1065 
  1066 
  1067 (** balanced trees **)
  1068 
  1069 exception Balance;      (*indicates non-positive argument to balancing fun*)
  1070 
  1071 (*balanced folding; avoids deep nesting*)
  1072 fun fold_bal f [x] = x
  1073   | fold_bal f [] = raise Balance
  1074   | fold_bal f xs =
  1075       let val (ps,qs) = splitAt(length xs div 2, xs)
  1076       in  f (fold_bal f ps, fold_bal f qs)  end;
  1077 
  1078 (*construct something of the form f(...g(...(x)...)) for balanced access*)
  1079 fun access_bal (f, g, x) n i =
  1080   let fun acc n i =     (*1<=i<=n*)
  1081           if n=1 then x else
  1082           let val n2 = n div 2
  1083           in  if i<=n2 then f (acc n2 i)
  1084                        else g (acc (n-n2) (i-n2))
  1085           end
  1086   in  if 1<=i andalso i<=n then acc n i else raise Balance  end;
  1087 
  1088 (*construct ALL such accesses; could try harder to share recursive calls!*)
  1089 fun accesses_bal (f, g, x) n =
  1090   let fun acc n =
  1091           if n=1 then [x] else
  1092           let val n2 = n div 2
  1093               val acc2 = acc n2
  1094           in  if n-n2=n2 then map f acc2 @ map g acc2
  1095                          else map f acc2 @ map g (acc (n-n2)) end
  1096   in  if 1<=n then acc n else raise Balance  end;
  1097 
  1098 
  1099 
  1100 (** orders **)
  1101 
  1102 fun rev_order LESS = GREATER
  1103   | rev_order EQUAL = EQUAL
  1104   | rev_order GREATER = LESS;
  1105 
  1106 (*assume rel is a linear strict order*)
  1107 fun make_ord rel (x, y) =
  1108   if rel (x, y) then LESS
  1109   else if rel (y, x) then GREATER
  1110   else EQUAL;
  1111 
  1112 (*Better to use Int.compare*)
  1113 fun int_ord (i, j: int) =
  1114   if i < j then LESS
  1115   else if i = j then EQUAL
  1116   else GREATER;
  1117 
  1118 (*Better to use String.compare*)
  1119 fun string_ord (a, b: string) =
  1120   if a < b then LESS
  1121   else if a = b then EQUAL
  1122   else GREATER;
  1123 
  1124 (*lexicographic product*)
  1125 fun prod_ord a_ord b_ord ((x, y), (x', y')) =
  1126   (case a_ord (x, x') of EQUAL => b_ord (y, y') | ord => ord);
  1127 
  1128 (*dictionary order -- in general NOT well-founded!*)
  1129 fun dict_ord _ ([], []) = EQUAL
  1130   | dict_ord _ ([], _ :: _) = LESS
  1131   | dict_ord _ (_ :: _, []) = GREATER
  1132   | dict_ord elem_ord (x :: xs, y :: ys) =
  1133       (case elem_ord (x, y) of EQUAL => dict_ord elem_ord (xs, ys) | ord => ord);
  1134 
  1135 (*lexicographic product of lists*)
  1136 fun list_ord elem_ord (xs, ys) =
  1137   prod_ord int_ord (dict_ord elem_ord) ((length xs, xs), (length ys, ys));
  1138 
  1139 
  1140 (* sorting *)
  1141 
  1142 (*quicksort (stable, i.e. does not reorder equal elements)*)
  1143 fun sort ord =
  1144   let
  1145     fun qsort xs =
  1146       let val len = length xs in
  1147         if len <= 1 then xs
  1148         else
  1149           let val (lts, eqs, gts) = part (nth_elem (len div 2, xs)) xs in
  1150             qsort lts @ eqs @ qsort gts
  1151           end
  1152       end
  1153     and part _ [] = ([], [], [])
  1154       | part pivot (x :: xs) = add (ord (x, pivot)) x (part pivot xs)
  1155     and add LESS x (lts, eqs, gts) = (x :: lts, eqs, gts)
  1156       | add EQUAL x (lts, eqs, gts) = (lts, x :: eqs, gts)
  1157       | add GREATER x (lts, eqs, gts) = (lts, eqs, x :: gts);
  1158   in qsort end;
  1159 
  1160 (*sort strings*)
  1161 val sort_strings = sort string_ord;
  1162 fun sort_wrt sel xs = sort (string_ord o pairself sel) xs;
  1163 
  1164 fun unique_strings ([]: string list) = []
  1165   | unique_strings [x] = [x]
  1166   | unique_strings (x :: y :: ys) =
  1167       if x = y then unique_strings (y :: ys)
  1168       else x :: unique_strings (y :: ys);
  1169 
  1170 
  1171 (** random numbers **)
  1172 
  1173 exception RANDOM;
  1174 
  1175 fun rmod x y = x - y * Real.realFloor (x / y);
  1176 
  1177 local
  1178   val a = 16807.0;
  1179   val m = 2147483647.0;
  1180   val random_seed = ref 1.0;
  1181 in
  1182 
  1183 fun random () =
  1184   let val r = rmod (a * !random_seed) m
  1185   in (random_seed := r; r) end;
  1186 
  1187 end;
  1188 
  1189 fun random_range l h =
  1190   if h < l orelse l < 0 then raise RANDOM
  1191   else l + Real.floor (rmod (random ()) (real (h - l + 1)));
  1192 
  1193 fun one_of xs = nth_elem (random_range 0 (length xs - 1), xs);
  1194 
  1195 fun frequency xs =
  1196   let
  1197     val sum = foldl op + (0, map fst xs);
  1198     fun pick n ((k, x) :: xs) =
  1199       if n <= k then x else pick (n - k) xs
  1200   in pick (random_range 1 sum) xs end;
  1201 
  1202 
  1203 (** current directory **)
  1204 
  1205 val cd = OS.FileSys.chDir;
  1206 val pwd = OS.FileSys.getDir;
  1207 
  1208 
  1209 
  1210 (** rational numbers **)
  1211 
  1212 datatype rat = Rat of bool * int * int
  1213 
  1214 exception RAT of string;
  1215 
  1216 fun rep_rat(Rat(a,p,q)) = (if a then p else ~p,q)
  1217 
  1218 fun ratnorm(a,p,q) = if p=0 then Rat(a,0,1) else
  1219   let val absp = abs p
  1220       val m = gcd(absp,q)
  1221   in Rat(a = (0 <= p), absp div m, q div m) end;
  1222 
  1223 fun ratadd(Rat(a,p,q),Rat(b,r,s)) =
  1224   let val den = lcm(q,s)
  1225       val p = p*(den div q) and r = r*(den div s)
  1226       val num = (if a then p else ~p) + (if b then r else ~r)
  1227   in ratnorm(true,num,den) end;
  1228 
  1229 fun ratmul(Rat(a,p,q),Rat(b,r,s)) = ratnorm(a=b,p*r,q*s)
  1230 
  1231 fun ratinv(Rat(a,p,q)) = if p=0 then raise RAT "ratinv" else Rat(a,q,p)
  1232 
  1233 fun int_ratdiv(p,q) =
  1234   if q=0 then raise RAT "int_ratdiv" else ratnorm(0<=q, p, abs q)
  1235 
  1236 fun ratneg(Rat(b,p,q)) = Rat(not b,p,q);
  1237 
  1238 fun rat_of_int i = if i < 0 then Rat(false,abs i,1) else Rat(true,i,1);
  1239 
  1240 
  1241 (** misc **)
  1242 
  1243 (*use the keyfun to make a list of (x, key) pairs*)
  1244 fun make_keylist (keyfun: 'a->'b) : 'a list -> ('a * 'b) list =
  1245   let fun keypair x = (x, keyfun x)
  1246   in map keypair end;
  1247 
  1248 (*given a list of (x, key) pairs and a searchkey
  1249   return the list of xs from each pair whose key equals searchkey*)
  1250 fun keyfilter [] searchkey = []
  1251   | keyfilter ((x, key) :: pairs) searchkey =
  1252       if key = searchkey then x :: keyfilter pairs searchkey
  1253       else keyfilter pairs searchkey;
  1254 
  1255 
  1256 (*Partition list into elements that satisfy predicate and those that don't.
  1257   Preserves order of elements in both lists.*)
  1258 fun partition (pred: 'a->bool) (ys: 'a list) : ('a list * 'a list) =
  1259     let fun part ([], answer) = answer
  1260           | part (x::xs, (ys, ns)) = if pred(x)
  1261             then  part (xs, (x::ys, ns))
  1262             else  part (xs, (ys, x::ns))
  1263     in  part (rev ys, ([], []))  end;
  1264 
  1265 
  1266 fun partition_eq (eq:'a * 'a -> bool) =
  1267     let fun part [] = []
  1268           | part (x::ys) = let val (xs, xs') = partition (apl(x, eq)) ys
  1269                            in (x::xs)::(part xs') end
  1270     in part end;
  1271 
  1272 
  1273 (*Partition a list into buckets  [ bi, b(i+1), ..., bj ]
  1274    putting x in bk if p(k)(x) holds.  Preserve order of elements if possible.*)
  1275 fun partition_list p i j =
  1276   let fun part k xs =
  1277             if k>j then
  1278               (case xs of [] => []
  1279                          | _ => raise LIST "partition_list")
  1280             else
  1281             let val (ns, rest) = partition (p k) xs;
  1282             in  ns :: part(k+1)rest  end
  1283   in  part i end;
  1284 
  1285 
  1286 (* generating identifiers *)
  1287 
  1288 (** Freshly generated identifiers; supplied prefix MUST start with a letter **)
  1289 local
  1290 (*Maps 0-63 to A-Z, a-z, 0-9 or _ or ' for generating random identifiers*)
  1291 fun char i =      if i<26 then chr (ord "A" + i)
  1292              else if i<52 then chr (ord "a" + i - 26)
  1293              else if i<62 then chr (ord"0" + i - 52)
  1294              else if i=62 then "_"
  1295              else  (*i=63*)    "'";
  1296 
  1297 val charVec = Vector.tabulate (64, char);
  1298 
  1299 fun newid n =
  1300   let
  1301   in  implode (map (fn i => Vector.sub(charVec,i)) (radixpand (64,n)))  end;
  1302 
  1303 val seedr = ref 0;
  1304 
  1305 in
  1306 
  1307 fun gensym pre = pre ^ (#1(newid (!seedr), inc seedr));
  1308 
  1309 end;
  1310 
  1311 
  1312 (* lexical scanning *)
  1313 
  1314 (*scan a list of characters into "words" composed of "letters" (recognized by
  1315   is_let) and separated by any number of non-"letters"*)
  1316 fun scanwords is_let cs =
  1317   let fun scan1 [] = []
  1318         | scan1 cs =
  1319             let val (lets, rest) = take_prefix is_let cs
  1320             in implode lets :: scanwords is_let rest end;
  1321   in scan1 (#2 (take_prefix (not o is_let) cs)) end;
  1322 
  1323 
  1324 end;
  1325 
  1326 open Library;