CCVector: Add function foldi

This commit is contained in:
Master Builder 2024-01-11 16:24:50 +00:00
parent 9de8f1fb2e
commit a70d6ef273
3 changed files with 31 additions and 0 deletions

View file

@ -412,6 +412,18 @@ let fold f acc v =
in in
fold acc 0 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 exists p v =
let n = v.size in let n = v.size in
let rec check i = let rec check i =

View file

@ -206,6 +206,11 @@ val filter_in_place : ('a -> bool) -> ('a, rw) t -> unit
val fold : ('b -> 'a -> 'b) -> 'b -> ('a, _) t -> 'b val fold : ('b -> 'a -> 'b) -> 'b -> ('a, _) t -> 'b
(** Fold on elements of the vector *) (** 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 val exists : ('a -> bool) -> ('a, _) t -> bool
(** Existential test (is there an element that satisfies the predicate?). *) (** Existential test (is there an element that satisfies the predicate?). *)

View file

@ -737,3 +737,17 @@ t @@ fun () -> of_list CCList.(1 -- 300_000) |> to_list = CCList.(1 -- 300_000)
t @@ fun () -> t @@ fun () ->
let v = 1 -- 10 in let v = 1 -- 10 in
to_list v = Gen.to_list (to_gen v) 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