Skip to content

Commit e9b8b5c

Browse files
authored
Merge pull request #101 from purescript/with-index-result
Let findWithIndex also return index of found value
2 parents 849891c + feaeff7 commit e9b8b5c

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

src/Data/FoldableWithIndex.purs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -268,11 +268,16 @@ findWithIndex
268268
. FoldableWithIndex i f
269269
=> (i -> a -> Boolean)
270270
-> f a
271-
-> Maybe a
271+
-> Maybe { index :: i, value :: a }
272272
findWithIndex p = foldlWithIndex go Nothing
273273
where
274-
go i Nothing x | p i x = Just x
275-
go i r _ = r
274+
go
275+
:: i
276+
-> Maybe { index :: i, value :: a }
277+
-> a
278+
-> Maybe { index :: i, value :: a }
279+
go i Nothing x | p i x = Just { index: i, value: x }
280+
go _ r _ = r
276281

277282
-- | A default implementation of `foldr` using `foldrWithIndex`
278283
foldrDefault

test/Main.purs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,10 @@ main = do
120120
assert $ find (\x -> x `mod` 2 == 0) [1, 4, 10] == Just 4
121121

122122
log "Test findWithIndex"
123-
assert $ findWithIndex (\i x -> i == 2 && x `mod` 2 == 0) [1, 2, 4, 6] == Just 4
123+
assert $
124+
case findWithIndex (\i x -> i `mod` 2 == 0 && x `mod` 2 == 0) [1, 2, 4, 6] of
125+
Nothing -> false
126+
Just { index, value } -> index == 2 && value == 4
124127

125128
log "Test findMap" *> do
126129
let pred x = if x > 5 then Just (x * 100) else Nothing

0 commit comments

Comments
 (0)