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