From 17eab9c3f441c297f904fe6c474c687c7f77d97d Mon Sep 17 00:00:00 2001 From: Master Builder Date: Thu, 11 Jan 2024 16:24:50 +0000 Subject: [PATCH] CCVector: Add function foldi --- src/core/CCVector.ml | 12 ++++++++++++ src/core/CCVector.mli | 5 +++++ tests/core/t_vector.ml | 14 ++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/src/core/CCVector.ml b/src/core/CCVector.ml index 8771e74b..f1d9d240 100644 --- a/src/core/CCVector.ml +++ b/src/core/CCVector.ml @@ -412,6 +412,18 @@ let fold f acc v = in fold acc 0 +let foldi f acc v = + let { vec; size } = v in + let rec fold acc i = + if i = size then + acc + else ( + let x = Array.unsafe_get vec i in + fold (f i acc x) (i + 1) + ) + in + fold acc 0 + let exists p v = let n = v.size in let rec check i = diff --git a/src/core/CCVector.mli b/src/core/CCVector.mli index 7e858453..c8fddf6e 100644 --- a/src/core/CCVector.mli +++ b/src/core/CCVector.mli @@ -206,6 +206,11 @@ val filter_in_place : ('a -> bool) -> ('a, rw) t -> unit val fold : ('b -> 'a -> 'b) -> 'b -> ('a, _) t -> 'b (** Fold on elements of the vector *) +val foldi : (int -> 'b -> 'a -> 'b) -> 'b -> ('a, _) t -> 'b +(** [foldi f init v] is just like {!fold}, but it also passes in the index + of each element as the first argument to the function [f]. + @since NEXT_RELEASE *) + val exists : ('a -> bool) -> ('a, _) t -> bool (** Existential test (is there an element that satisfies the predicate?). *) diff --git a/tests/core/t_vector.ml b/tests/core/t_vector.ml index 75fed217..a3f6236c 100644 --- a/tests/core/t_vector.ml +++ b/tests/core/t_vector.ml @@ -737,3 +737,17 @@ t @@ fun () -> of_list CCList.(1 -- 300_000) |> to_list = CCList.(1 -- 300_000) t @@ fun () -> let v = 1 -- 10 in to_list v = Gen.to_list (to_gen v) +;; + +t @@ fun () -> +let v = create () in +0 = foldi (fun i acc _ -> acc + i) 0 v +;; + +t @@ fun () -> +let v = create () in +push v 0; +push v 0; +push v 0; +push v 0; +6 = foldi (fun i acc _ -> acc + i) 0 v