From ef06d117cb5986c8043123a7f7cb245232417d98 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Fri, 20 Jun 2014 14:28:41 +0200 Subject: [PATCH] api change in CClist: find is now find_idx, and find:('a->'b option) -> 'a list -> 'b option added --- core/CCList.ml | 14 +++++++++++++- core/CCList.mli | 9 +++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/core/CCList.ml b/core/CCList.ml index 34d04392..6a748d52 100644 --- a/core/CCList.ml +++ b/core/CCList.ml @@ -219,13 +219,25 @@ let last n l = let len = List.length l in if len < n then l else drop (len-n) l -let find p l = +let find_idx p l = let rec search i l = match l with | [] -> None | x::_ when p x -> Some (i, x) | _::xs -> search (i+1) xs in search 0 l +let rec find f l = match l with + | [] -> None + | x::l' -> + match f x with + | Some _ as res -> res + | None -> find f l' + +(*$T + find (fun x -> if x=3 then Some "a" else None) [1;2;3;4] = Some "a" + find (fun x -> if x=3 then Some "a" else None) [1;2;4;5] = None +*) + let filter_map f l = let rec recurse acc l = match l with | [] -> List.rev acc diff --git a/core/CCList.mli b/core/CCList.mli index 54338a68..eafd9656 100644 --- a/core/CCList.mli +++ b/core/CCList.mli @@ -86,10 +86,15 @@ 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 : ('a -> bool) -> 'a t -> (int * 'a) option +val find_idx : ('a -> bool) -> 'a t -> (int * 'a) option (** [find p x] returns [Some (i,x)] where [x] is the [i]-th element of [l], and [p x] holds. Otherwise returns [None] *) +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 + the call returns [None] *) + val filter_map : ('a -> 'b option) -> 'a t -> 'b t (** Map and remove elements at the same time *) @@ -115,7 +120,7 @@ module Idx : sig val set : 'a t -> int -> 'a -> 'a t (** set i-th element (removes the old one), or does nothing if index too high *) - + val insert : 'a t -> int -> 'a -> 'a t (** insert at i-th position, between the two existing elements. If the index is too high, append at the end of the list *)