From 262a2baacccc44c0cf21618ed9c1edb02948e350 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Sun, 24 May 2015 21:28:07 +0200 Subject: [PATCH] add `CCList.{remove,is_empty}` --- src/core/CCList.ml | 17 +++++++++++++++++ src/core/CCList.mli | 9 +++++++++ 2 files changed, 26 insertions(+) diff --git a/src/core/CCList.ml b/src/core/CCList.ml index c43904cc..f8a82c3b 100644 --- a/src/core/CCList.ml +++ b/src/core/CCList.ml @@ -30,6 +30,10 @@ type 'a t = 'a list let empty = [] +let is_empty = function + | [] -> true + | _::_ -> false + (* max depth for direct recursion *) let direct_depth_default_ = 1000 @@ -422,6 +426,19 @@ let find_idx p l = find_mapi (fun i x -> if p x then Some (i, x) else None) l find (fun x -> if x=3 then Some "a" else None) [1;2;4;5] = None *) +let remove ?(eq=(=)) ~x l = + let rec remove' eq x acc l = match l with + | [] -> List.rev acc + | y :: tail when eq x y -> remove' eq x acc tail + | y :: tail -> remove' eq x (y::acc) tail + in + remove' eq x [] l + +(*$T + remove ~x:1 [2;1;3;3;2;1] = [2;3;3;2] + remove ~x:10 [1;2;3] = [1;2;3] +*) + let filter_map f l = let rec recurse acc l = match l with | [] -> List.rev acc diff --git a/src/core/CCList.mli b/src/core/CCList.mli index bc4531be..c1e68ba0 100644 --- a/src/core/CCList.mli +++ b/src/core/CCList.mli @@ -30,6 +30,10 @@ type 'a t = 'a list val empty : 'a t +val is_empty : _ t -> bool +(** [is_empty l] returns [true] iff [l = []] + @since NEXT_RELEASE *) + val map : ('a -> 'b) -> 'a t -> 'b t (** Safe version of map *) @@ -140,6 +144,11 @@ 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 remove : ?eq:('a -> 'a -> bool) -> x:'a -> 'a t -> 'a t +(** [remove ~x l] removes every instance of [x] from [l]. Tailrec. + @param eq equality function + @since NEXT_RELEASE *) + val filter_map : ('a -> 'b option) -> 'a t -> 'b t (** Map and remove elements at the same time *)