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