diff --git a/vector/src/Data/Vector/Generic.hs b/vector/src/Data/Vector/Generic.hs index ec847c20..ebdffe0f 100644 --- a/vector/src/Data/Vector/Generic.hs +++ b/vector/src/Data/Vector/Generic.hs @@ -29,7 +29,7 @@ module Data.Vector.Generic ( length, null, -- ** Indexing - (!), (!?), head, last, + (!), (!?), head, vectorToMaybe, last, unsafeIndex, unsafeHead, unsafeLast, -- ** Monadic indexing @@ -244,10 +244,21 @@ v !? i | i `inRange` length v = case basicUnsafeIndexM v i of Box a -> Just a -- | /O(1)/ First element. +-- +-- Partial. +-- Undefined at @fromList [ ]@. +-- Completion is 'vectorToMaybe' head :: Vector v a => v a -> a {-# INLINE_FUSED head #-} head v = v ! 0 +-- | /O(1)/ Just the first element — or nothing when there are none. +-- +-- Completes 'head'. +vectorToMaybe :: Vector v a => v a -> Maybe a +{-# INLINE_FUSED vectorToMaybe #-} +vectorToMaybe v = v !? 0 + -- | /O(1)/ Last element. last :: Vector v a => v a -> a {-# INLINE_FUSED last #-} diff --git a/vector/tests/Tests/Vector/Property.hs b/vector/tests/Tests/Vector/Property.hs index dc8f0b63..c033ece9 100644 --- a/vector/tests/Tests/Vector/Property.hs +++ b/vector/tests/Tests/Vector/Property.hs @@ -98,7 +98,7 @@ testPolymorphicFunctions _ = $(testProperties [ 'prop_length, 'prop_null, -- Indexing - 'prop_index, 'prop_safeIndex, 'prop_head, 'prop_last, + 'prop_index, 'prop_safeIndex, 'prop_head, 'prop_vectorToMaybe, 'prop_last, 'prop_unsafeIndex, 'prop_unsafeHead, 'prop_unsafeLast, -- Monadic indexing (FIXME) @@ -241,6 +241,7 @@ testPolymorphicFunctions _ = $(testProperties [ prop_createT = (\v -> V.createT (T.mapM V.thaw v)) `eq` id prop_head :: P (v a -> a) = not . V.null ===> V.head `eq` head + prop_vectorToMaybe :: P (v a -> Maybe a) = not . V.null ===> V.vectorToMaybe `eq` (Just . head) prop_last :: P (v a -> a) = not . V.null ===> V.last `eq` last prop_index = \xs -> not (V.null xs) ==>