added repeatedly, rand_int, of_array and to_array to Gen

This commit is contained in:
Simon Cruanes 2013-03-21 18:06:00 +01:00
parent 6ba411d7f5
commit 0af36e124e
2 changed files with 47 additions and 0 deletions

34
gen.ml
View file

@ -109,6 +109,11 @@ let repeat x =
let f () = x in
fun () -> f
let repeatedly f =
fun () ->
fun () ->
f ()
(** [iterate x f] is [[x; f x; f (f x); f (f (f x)); ...]] *)
let iterate x f =
fun () ->
@ -168,6 +173,14 @@ let scan f acc e =
let iter f enum =
Gen.iter f (enum ())
(** Iterate on elements with their index in the enum, from 0 *)
let iteri f enum =
let r = ref 0 in
let gen = enum () in
try
while true do f !r (gen ()); incr r; done
with EOG -> ()
let iter2 f e1 e2 =
let gen1 = e1 () and gen2 = e2 () in
try
@ -776,6 +789,27 @@ let of_list l =
let to_rev_list enum =
Gen.to_rev_list (enum ())
let to_array enum =
let n = length enum in
let a = Array.make n (Obj.magic 0) in
iteri (fun i x -> a.(i) <- x) enum;
a
let of_array ?(start=0) ?len a =
let len = match len with
| None -> Array.length a
| Some n -> assert (n <= Array.length a); n in
fun () ->
let i = ref start in
fun () ->
if !i >= len
then raise EOG
else (let x = a.(!i) in incr i; x)
let rand_int i =
repeatedly (fun () -> Random.int i)
let int_range i j =
fun () -> Gen.int_range i j

13
gen.mli
View file

@ -82,6 +82,10 @@ val singleton : 'a -> 'a t
val repeat : 'a -> 'a t
(** Repeat same element endlessly *)
val repeatedly : (unit -> 'a) -> 'a t
(** Call the same function an infinite number of times (useful
if the function is a random generator) *)
val iterate : 'a -> ('a -> 'a) -> 'a t
(** [iterate x f] is [[x; f x; f (f x); f (f (f x)); ...]] *)
@ -109,6 +113,9 @@ val scan : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b t
val iter : ('a -> unit) -> 'a t -> unit
(** Iterate on the enum *)
val iteri : (int -> 'a -> unit) -> 'a t -> unit
(** Iterate on elements with their index in the enum, from 0 *)
val iter2 : ('a -> 'b -> unit) -> 'a t -> 'b t -> unit
(** Iterate on the two sequences. Stops once one of them is exhausted.*)
@ -272,6 +279,12 @@ val to_list : 'a t -> 'a list
val to_rev_list : 'a t -> 'a list
(** Tail call conversion to list, in reverse order *)
val to_array : 'a t -> 'a array
val of_array : ?start:int -> ?len:int -> 'a array -> 'a t
val rand_int : int -> int t
val int_range : int -> int -> int t
val pp : ?start:string -> ?stop:string -> ?sep:string -> ?horizontal:bool ->