From 5a4d25b93934bfca5ca5f4ccfddec1ab90a4ef2a Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Mon, 31 Aug 2015 13:42:13 +0200 Subject: [PATCH] add `CCKList.{of_array,to_array}` --- src/iter/CCKList.ml | 27 +++++++++++++++++++++++++++ src/iter/CCKList.mli | 8 ++++++++ 2 files changed, 35 insertions(+) diff --git a/src/iter/CCKList.ml b/src/iter/CCKList.ml index 042dba39..0b7de890 100644 --- a/src/iter/CCKList.ml +++ b/src/iter/CCKList.ml @@ -334,6 +334,33 @@ let of_list l = | x::l' -> `Cons (x, aux l') in aux l +let of_array a = + let rec aux a i () = + if i=Array.length a then `Nil + else `Cons (a.(i), aux a (i+1)) + in + aux a 0 + +let to_array l = + match l() with + | `Nil -> [| |] + | `Cons (x, _) -> + let n = length l in + let a = Array.make n x in (* need first elem to create [a] *) + iteri + (fun i x -> a.(i) <- x) + l; + a + +(*$Q + Q.(array int) (fun a -> of_array a |> to_array = a) +*) + +(*$T + of_array [| 1; 2; 3 |] |> to_list = [1;2;3] + of_list [1;2;3] |> to_array = [| 1; 2; 3; |] +*) + let rec to_seq res k = match res () with | `Nil -> () | `Cons (s, f) -> k s; to_seq f k diff --git a/src/iter/CCKList.mli b/src/iter/CCKList.mli index 564bdb79..76c94bdc 100644 --- a/src/iter/CCKList.mli +++ b/src/iter/CCKList.mli @@ -212,6 +212,14 @@ val of_list : 'a list -> 'a t val to_list : 'a t -> 'a list (** Gather all values into a list *) +val of_array : 'a array -> 'a t +(** Iterate on the array + @since NEXT_RELEASE *) + +val to_array : 'a t -> 'a array +(** Convert into array. Iterates twice. + @since NEXT_RELEASE *) + val to_rev_list : 'a t -> 'a list (** Convert to a list, in reverse order. More efficient than {!to_list} *)