From 55ff51f2cbde21bf7b1fce9c6284291b77fe81bf Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Fri, 15 Feb 2013 17:35:00 +0100 Subject: [PATCH] more combinators (iterate and forever); some sequences of random elements --- sequence.ml | 30 ++++++++++++++++++++++++++++++ sequence.mli | 19 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/sequence.ml b/sequence.ml index 869fe24..632fab9 100644 --- a/sequence.ml +++ b/sequence.ml @@ -36,6 +36,16 @@ let singleton x = fun k -> k x (** Infinite sequence of the same element *) let repeat x = fun k -> while true do k x done +(** [iterate f x] is the infinite sequence (x, f(x), f(f(x)), ...) *) +let iterate f x = + let rec iterate k x = k x; iterate k (f x) in + from_iter (fun k -> iterate k x) + +(** Sequence that calls the given function to produce elements *) +let forever f = + let rec forever k = k (f ()); forever k in + from_iter forever + (** Cycle forever through the given sequence. O(n). *) let cycle s = fun k -> while true do s k; done @@ -320,6 +330,26 @@ module Map = struct end end +(** {2 Infinite sequences of random values} *) + +let random_int bound = forever (fun () -> Random.int bound) + +let random_bool = forever Random.bool + +let random_float bound = forever (fun () -> Random.float bound) + +(** Sequence of choices of an element in the array *) +let random_array a = + assert (Array.length a > 0); + let seq k = + while true do + let i = Random.int (Array.length a) in + k a.(i); + done in + from_iter seq + +let random_list l = random_array (Array.of_list l) + (** {2 Pretty printing of sequences} *) (** Pretty print a sequence of ['a], using the given pretty printer diff --git a/sequence.mli b/sequence.mli index bc7267f..ed1a640 100644 --- a/sequence.mli +++ b/sequence.mli @@ -42,6 +42,12 @@ val singleton : 'a -> 'a t val repeat : 'a -> 'a t (** Infinite sequence of the same element *) +val iterate : ('a -> 'a) -> 'a -> 'a t + (** [iterate f x] is the infinite sequence (x, f(x), f(f(x)), ...) *) + +val forever : (unit -> 'b) -> 'b t + (** Sequence that calls the given function to produce elements *) + val cycle : 'a t -> 'a t (** Cycle forever through the given sequence. Assume the given sequence can be traversed any amount of times (not transient). *) @@ -204,6 +210,19 @@ module Map : sig module Make(V : Map.OrderedType) : S with type key = V.t end +(** {2 Infinite sequences of random values} *) + +val random_int : int -> int t + +val random_bool : bool t + +val random_float : float -> float t + +val random_array : 'a array -> 'a t + (** Sequence of choices of an element in the array *) + +val random_list : 'a list -> 'a t + (** {2 Pretty printing of sequences} *) val pp_seq : ?sep:string -> (Format.formatter -> 'a -> unit) ->