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