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