From 81ed6139cad6dfcd3c3a4c7ba33c338238be3766 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Mon, 24 Apr 2017 20:20:37 +0200 Subject: [PATCH] add `CCList.take_drop_while` (close #120) --- src/core/CCList.ml | 23 +++++++++++++++++++++++ src/core/CCList.mli | 4 ++++ 2 files changed, 27 insertions(+) diff --git a/src/core/CCList.ml b/src/core/CCList.ml index 1a0ab160..6861d538 100644 --- a/src/core/CCList.ml +++ b/src/core/CCList.ml @@ -700,6 +700,29 @@ let rec drop_while p l = match l with take_while f l @ drop_while f l = l) *) +let take_drop_while p l = + let rec direct i p l = match l with + | [] -> [], [] + | _ when i=0 -> safe p [] l + | x :: tail -> + if p x + then + let l1, l2 = direct (i-1) p tail in + x :: l1, l2 + else [], l + and safe p acc l = match l with + | [] -> List.rev acc, [] + | x :: tail -> + if p x then safe p (x::acc) tail else List.rev acc, l + in + direct direct_depth_default_ p l + +(*$Q + Q.(pair (fun1 small_int bool) (list small_int)) (fun (f,l) -> \ + let l1,l2 = take_drop_while f l in \ + (l1 = take_while f l) && (l2 = drop_while f l)) +*) + let last n l = let len = List.length l in if len < n then l else drop (len-n) l diff --git a/src/core/CCList.mli b/src/core/CCList.mli index 46fbeff4..f90ddef8 100644 --- a/src/core/CCList.mli +++ b/src/core/CCList.mli @@ -197,6 +197,10 @@ val take_while : ('a -> bool) -> 'a t -> 'a t val drop_while : ('a -> bool) -> 'a t -> 'a t (** @since 0.13 *) +val take_drop_while : ('a -> bool) -> 'a t -> 'a t * 'a t +(** [take_drop_while p l = take_while p l, drop_while p l] + @since NEXT_RELEASE *) + 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 *)