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