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