From dab92250d3070c120d76ad0afdd523ea8a5353d4 Mon Sep 17 00:00:00 2001 From: Ignat Insarov Date: Thu, 25 Jan 2024 16:58:21 +0300 Subject: [PATCH 1/2] Add `vectorToMaybe`. --- vector/src/Data/Vector/Generic.hs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/vector/src/Data/Vector/Generic.hs b/vector/src/Data/Vector/Generic.hs index ec847c20..d146aa76 100644 --- a/vector/src/Data/Vector/Generic.hs +++ b/vector/src/Data/Vector/Generic.hs @@ -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 #-} From b7d2f4d97e219c56db122c6e316dfdb9c0843e8a Mon Sep 17 00:00:00 2001 From: Ignat Insarov Date: Thu, 25 Jan 2024 17:21:28 +0300 Subject: [PATCH 2/2] Add property check for `vectorToMaybe`. --- vector/src/Data/Vector/Generic.hs | 2 +- vector/tests/Tests/Vector/Property.hs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/vector/src/Data/Vector/Generic.hs b/vector/src/Data/Vector/Generic.hs index d146aa76..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 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) ==>