From 2d30b2ae143ec3de3cdeb338d6cd87e7183fa60c Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Thu, 27 Jan 2022 13:48:49 -0500 Subject: [PATCH] add `CCSeq.{zip_i,of_string}` --- src/core/CCSeq.ml | 18 ++++++++++++++++++ src/core/CCSeq.mli | 9 +++++++++ 2 files changed, 27 insertions(+) diff --git a/src/core/CCSeq.ml b/src/core/CCSeq.ml index 55a32593..5cf9d55b 100644 --- a/src/core/CCSeq.ml +++ b/src/core/CCSeq.ml @@ -356,6 +356,17 @@ let unzip l = let l = of_list l in let a, b = unzip l in equal (=) l (zip a b)) *) +let zip_i seq = + let rec loop i seq () = match seq() with + | Nil -> Nil + | Cons (x,tl) -> Cons ((i,x), loop (i+1) tl) + in + loop 0 seq + +(*$= + [0,'a'; 1, 'b'; 2, 'c'] (of_string "abcde" |> zip_i |> take 3 |> to_list) +*) + (** {2 Implementations} *) let return x () = Cons (x, nil) @@ -394,6 +405,13 @@ let of_array a = in aux a 0 +let of_string s = + let rec aux s i () = + if i=String.length s then Nil + else Cons (String.get s i, aux s (i+1)) + in + aux s 0 + let to_array l = (* We contruct the length and list of seq elements (in reverse) in one pass *) let len, ls = fold_left (fun (i, acc) x -> (i + 1, x :: acc)) (0, []) l in diff --git a/src/core/CCSeq.mli b/src/core/CCSeq.mli index c5991f70..5a51f39c 100644 --- a/src/core/CCSeq.mli +++ b/src/core/CCSeq.mli @@ -166,6 +166,11 @@ val zip : 'a t -> 'b t -> ('a * 'b) t val unzip : ('a * 'b) t -> 'a t * 'b t (** Split each tuple in the list. *) +val zip_i : 'a t -> (int * 'a) t +(** [zip_i seq] zips the index of each element with the element itself. + @since NEXT +*) + (** {2 Misc} *) val sort : cmp:'a ord -> 'a t -> 'a t @@ -254,6 +259,10 @@ val to_gen : 'a t -> 'a gen val of_gen : 'a gen -> 'a t (** [of_gen g] consumes the generator and caches intermediate results. *) +val of_string : string -> char t +(** Iterate on characters. + @since NEXT_RELEASE *) + (** {2 IO} *) val pp : ?pp_start:unit printer -> ?pp_stop:unit printer -> ?pp_sep:unit printer ->