From 4118f87ae41d9b3c2e6e9cb599b158fc18c08569 Mon Sep 17 00:00:00 2001 From: John Hester Date: Thu, 12 Dec 2024 15:30:49 -0600 Subject: [PATCH] feat: add CCVector.findi --- src/core/CCVector.ml | 16 ++++++++++++++++ src/core/CCVector.mli | 3 +++ 2 files changed, 19 insertions(+) diff --git a/src/core/CCVector.ml b/src/core/CCVector.ml index 572c3598b..a31d76216 100644 --- a/src/core/CCVector.ml +++ b/src/core/CCVector.ml @@ -490,8 +490,24 @@ let find_internal_ p v = in check 0 +let find_internal_i_ p v = + let n = v.size in + let rec check i = + if i = n then + raise_notrace Not_found + else ( + let x = v.vec.(i) in + if p x then + i,x + else + check (i + 1) + ) + in + check 0 + let find_exn p v = try find_internal_ p v with Not_found -> raise Not_found let find p v = try Some (find_internal_ p v) with Not_found -> None +let findi p v = try Some (find_internal_i_ p v) with Not_found -> None let find_map f v = let n = v.size in diff --git a/src/core/CCVector.mli b/src/core/CCVector.mli index a874e5c19..aed8e0c78 100644 --- a/src/core/CCVector.mli +++ b/src/core/CCVector.mli @@ -220,6 +220,9 @@ val for_all : ('a -> bool) -> ('a, _) t -> bool val find : ('a -> bool) -> ('a, _) t -> 'a option (** Find an element that satisfies the predicate. *) +val findi : ('a -> bool) -> ('a, _) t -> (int * 'a) option +(** Find an element and its index that satisfies the predicate. *) + val find_exn : ('a -> bool) -> ('a, _) t -> 'a (** Find an element that satisfies the predicate, or @raise Not_found if no element does. *)