Skip to content

Commit

Permalink
A version of findIndex for the last matching element.
Browse files Browse the repository at this point in the history
Discussed in

haskell#172
  • Loading branch information
leftaroundabout committed Sep 26, 2017
1 parent 3c51c33 commit be4961b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
8 changes: 7 additions & 1 deletion Data/Vector/Generic.hs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ module Data.Vector.Generic (
partition, partitionWith, unstablePartition, span, break,

-- ** Searching
elem, notElem, find, findIndex, findIndices, elemIndex, elemIndices,
elem, notElem, find, findIndex, findIndexR, findIndices, elemIndex, elemIndices,

-- * Folding
foldl, foldl1, foldl', foldl1', foldr, foldr1, foldr', foldr1',
Expand Down Expand Up @@ -1468,6 +1468,12 @@ findIndex :: Vector v a => (a -> Bool) -> v a -> Maybe Int
{-# INLINE findIndex #-}
findIndex f = Bundle.findIndex f . stream

-- | /O(n)/ Yield 'Just' the index of the /last/ element matching the predicate
-- or 'Nothing' if no such element exists.
findIndexR :: Vector v a => (a -> Bool) -> v a -> Maybe Int
{-# INLINE findIndexR #-}
findIndexR f v = fmap (length v - 1 -) . Bundle.findIndex f $ streamR v

-- | /O(n)/ Yield the indices of elements satisfying the predicate in ascending
-- order.
findIndices :: (Vector v a, Vector v Int) => (a -> Bool) -> v a -> v Int
Expand Down
6 changes: 5 additions & 1 deletion tests/Tests/Vector.hs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ testPolymorphicFunctions _ = $(testProperties [

-- Searching
'prop_elem, 'prop_notElem,
'prop_find, 'prop_findIndex, 'prop_findIndices,
'prop_find, 'prop_findIndex, 'prop_findIndexR, 'prop_findIndices,
'prop_elemIndex, 'prop_elemIndices,

-- Folding
Expand Down Expand Up @@ -330,6 +330,10 @@ testPolymorphicFunctions _ = $(testProperties [
prop_find :: P ((a -> Bool) -> v a -> Maybe a) = V.find `eq` find
prop_findIndex :: P ((a -> Bool) -> v a -> Maybe Int)
= V.findIndex `eq` findIndex
prop_findIndexR :: P ((a -> Bool) -> v a -> Maybe Int)
= V.findIndexR `eq` (\p l -> case filter (p . snd) . reverse $ zip [0..] l of
(i,_):_ -> Just i
[] -> Nothing )
prop_findIndices :: P ((a -> Bool) -> v a -> v Int)
= V.findIndices `eq` findIndices
prop_elemIndex :: P (a -> v a -> Maybe Int) = V.elemIndex `eq` elemIndex
Expand Down

0 comments on commit be4961b

Please sign in to comment.