From 153cababb3024e0ba10d5e45f9e24e0c59a40b2b Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Sun, 17 May 2015 19:18:40 +0200 Subject: [PATCH] add `CCList.{find_pred,find_pred_exn}` --- src/core/CCList.ml | 16 ++++++++++++++++ src/core/CCList.mli | 10 ++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/core/CCList.ml b/src/core/CCList.ml index 77ea0b1d..57b5189a 100644 --- a/src/core/CCList.ml +++ b/src/core/CCList.ml @@ -385,6 +385,22 @@ let last n l = let len = List.length l in if len < n then l else drop (len-n) l +let rec find_pred p l = match l with + | [] -> None + | x :: _ when p x -> Some x + | _ :: tl -> find_pred p tl + +let find_pred_exn p l = match find_pred p l with + | None -> raise Not_found + | Some x -> x + +(*$T + find_pred ((=) 4) [1;2;5;4;3;0] = Some 4 + find_pred (fun _ -> true) [] = None + find_pred (fun _ -> false) (1 -- 10) = None + find_pred (fun x -> x < 10) (1 -- 9) = Some 1 +*) + let findi f l = let rec aux f i = function | [] -> None diff --git a/src/core/CCList.mli b/src/core/CCList.mli index bc134612..4bc71c5e 100644 --- a/src/core/CCList.mli +++ b/src/core/CCList.mli @@ -109,6 +109,16 @@ val last : int -> 'a t -> 'a t (** [last n l] takes the last [n] elements of [l] (or less if [l] doesn't have that many elements *) +val find_pred : ('a -> bool) -> 'a t -> 'a option +(** [find_pred p l] finds the first element of [l] that satisfies [p], + or returns [None] if no element satisfies [p] + @since NEXT_RELEASE *) + +val find_pred_exn : ('a -> bool) -> 'a t -> 'a +(** Unsafe version of {!find_pred} + @raise Not_found if no such element is found + @since NEXT_RELEASE *) + val find : ('a -> 'b option) -> 'a t -> 'b option (** [find f l] traverses [l], applying [f] to each element. If for some element [x], [f x = Some y], then [Some y] is returned. Otherwise