From e2bb0e93cbfad0b2b216603c932fd770fc8e037e Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Sat, 14 Jun 2014 14:30:15 +0200 Subject: [PATCH] CCArray.find --- core/CCArray.ml | 8 ++++++++ core/CCArray.mli | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/core/CCArray.ml b/core/CCArray.ml index 2838c7cc..7d2d6dfa 100644 --- a/core/CCArray.ml +++ b/core/CCArray.ml @@ -57,6 +57,14 @@ let reverse_in_place a = a = [| 6;5;4;3;2;1 |] *) +let find f a = + let rec find i = + if i = Array.length a then None + else match f a.(i) with + | Some _ as res -> res + | None -> find (i+1) + in find 0 + let filter_map f a = let rec aux acc i = if i = Array.length a diff --git a/core/CCArray.mli b/core/CCArray.mli index e31ce665..5ed08de1 100644 --- a/core/CCArray.mli +++ b/core/CCArray.mli @@ -41,6 +41,10 @@ val filter : ('a -> bool) -> 'a t -> 'a t val reverse_in_place : 'a t -> unit (** Reverse the array in place *) +val find : ('a -> 'b option) -> 'a t -> 'b option +(** [find f a] returns [Some y] if there is an element [x] such + that [f x = Some y], else it returns [None] *) + val filter_map : ('a -> 'b option) -> 'a t -> 'b t (** Map each element into another value, or discard it *)