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