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