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