diff --git a/src/core/CCList.ml b/src/core/CCList.ml index 92c2747d..17a29a04 100644 --- a/src/core/CCList.ml +++ b/src/core/CCList.ml @@ -569,6 +569,24 @@ let last n l = let len = List.length l in if len < n then l else drop (len-n) l +let head_opt = function + | [] -> None + | x::_ -> Some x + +let rec last_opt = function + | [] -> None + | [x] -> Some x + | _ :: tail -> last_opt tail + +(*$= & ~printer:Q.Print.(option int) + (Some 1) (head_opt [1;2;3]) + (Some 1) (head_opt [1]) + None (head_opt []) + (Some 3) (last_opt [1;2;3]) + (Some 1) (last_opt [1]) + None (last_opt []) +*) + let rec find_pred p l = match l with | [] -> None | x :: _ when p x -> Some x diff --git a/src/core/CCList.mli b/src/core/CCList.mli index a3a35b26..3331b9a7 100644 --- a/src/core/CCList.mli +++ b/src/core/CCList.mli @@ -134,6 +134,14 @@ 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 head_opt : 'a t -> 'a option +(** First element. + @since NEXT_RELEASE *) + +val last_opt : 'a t -> 'a option +(** Last element. + @since NEXT_RELEASE *) + 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]