diff --git a/core/CCVector.ml b/core/CCVector.ml index b236ee2b..143a5a55 100644 --- a/core/CCVector.ml +++ b/core/CCVector.ml @@ -215,6 +215,19 @@ let pop v = try Some (pop_exn v) with Failure _ -> None +let top v = + if v.size = 0 then None else Some v.vec.(v.size-1) + +let top_exn v = + if v.size = 0 then failwith "Vector.top"; + v.vec.(v.size-1) + +(*$T + 1 -- 10 |> top = Some 10 + create () |> top = None + 1 -- 10 |> top_exn = 10 + *) + let copy v = { size = v.size; vec = Array.sub v.vec 0 v.size; diff --git a/core/CCVector.mli b/core/CCVector.mli index a032eb88..94a312fb 100644 --- a/core/CCVector.mli +++ b/core/CCVector.mli @@ -99,6 +99,15 @@ val pop_exn : ('a, rw) t -> 'a (** remove last element, or raise a Failure if empty @raise Failure on an empty vector *) +val top : ('a, _) t -> 'a option +(** Top element, if present + @since NEXT_RELEASE *) + +val top_exn : ('a, _) t -> 'a +(** Top element, if present + @raise Failure on an empty vector + @since NEXT_RELEASE *) + val copy : ('a,_) t -> ('a,'mut) t (** Shallow copy (may give an immutable or mutable vector) *)