Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions Data/Vector/Generic.hs
Original file line numberDiff line numberDiff line change
Expand Up@@ -241,8 +241,13 @@ infixl 9 !?
-- | O(1) Safe indexing
(!?) :: Vector v a => v a -> Int -> Maybe a
{-# INLINE_FUSED (!?) #-}
v !? i | i < 0 || i >= length v = Nothing
| otherwise = Just $ unsafeIndex v i
-- Lengths are never negative, so we can check 0 <= i < length v
-- using one unsigned comparison.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand this comment and logic. Is the idea that

fromIntegral (minBound :: Int) :: Word
9223372036854775808

is always bigger than any realistic length Vector could be?

I think that should explained more clearly, this is "too clever" otherwise.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@phadej, right; a vector of length over maxBound :: Int will break assumptions all over the place. I can add a comment to that effect.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Existing definition has a benefit of short-circuiting in compile time when i is a statically known negative number. But I do not think that this is an important scenario.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's probably worth adding note that fromIntegral (i :: Int) :: Word > fromIntegral (maxBound :: Int) :: Word for all negative Ints. Such optimization is not entirely obvious

v !? i | (fromIntegral i :: Word) >= fromIntegral (length v)
= Nothing
| otherwise
-- Use basicUnsafeIndexM @Maybe to perform the indexing eagerly.
= basicUnsafeIndexM v i

-- | /O(1)/ First element
head :: Vector v a => v a -> a
Expand Down