add CCList.{head_opt,last_opt}

This commit is contained in:
Simon Cruanes 2016-09-25 19:34:05 +02:00
parent 7a823b16d8
commit 3e50420ce8
2 changed files with 26 additions and 0 deletions

View file

@ -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

View file

@ -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]