Skip to content

Commit d9b8f61

Browse files
author
Serhii Khoma
committed
feat: findMapWithIndex -> implement
1 parent 926fbd0 commit d9b8f61

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/Data/FoldableWithIndex.purs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ module Data.FoldableWithIndex
1111
, allWithIndex
1212
, anyWithIndex
1313
, findWithIndex
14+
, findMapWithIndex
1415
, foldrDefault
1516
, foldlDefault
1617
, foldMapDefault
@@ -279,6 +280,24 @@ findWithIndex p = foldlWithIndex go Nothing
279280
go i Nothing x | p i x = Just { index: i, value: x }
280281
go _ r _ = r
281282

283+
-- | Try to find an element in a data structure which satisfies a predicate mapping
284+
-- | with access to the index.
285+
findMapWithIndex
286+
:: forall i a b f
287+
. FoldableWithIndex i f
288+
=> (i -> a -> Maybe b)
289+
-> f a
290+
-> Maybe b
291+
findMapWithIndex f = foldlWithIndex go Nothing
292+
where
293+
go
294+
:: i
295+
-> Maybe b
296+
-> a
297+
-> Maybe b
298+
go i Nothing x = f i x
299+
go _ r _ = r
300+
282301
-- | A default implementation of `foldr` using `foldrWithIndex`
283302
foldrDefault
284303
:: forall i f a b

test/Main.purs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import Data.Bifoldable (class Bifoldable, bifoldl, bifoldr, bifoldMap, bifoldrDe
66
import Data.Bifunctor (class Bifunctor, bimap)
77
import Data.Bitraversable (class Bitraversable, bisequenceDefault, bitraverse, bisequence, bitraverseDefault)
88
import Data.Foldable (class Foldable, find, findMap, fold, indexl, indexr, foldMap, foldMapDefaultL, foldMapDefaultR, foldl, foldlDefault, foldr, foldrDefault, length, maximum, maximumBy, minimum, minimumBy, null, surroundMap)
9-
import Data.FoldableWithIndex (class FoldableWithIndex, findWithIndex, foldMapWithIndex, foldMapWithIndexDefaultL, foldMapWithIndexDefaultR, foldlWithIndex, foldlWithIndexDefault, foldrWithIndex, foldrWithIndexDefault, surroundMapWithIndex)
9+
import Data.FoldableWithIndex (class FoldableWithIndex, findWithIndex, findMapWithIndex, foldMapWithIndex, foldMapWithIndexDefaultL, foldMapWithIndexDefaultR, foldlWithIndex, foldlWithIndexDefault, foldrWithIndex, foldrWithIndexDefault, surroundMapWithIndex)
1010
import Data.Function (on)
1111
import Data.FunctorWithIndex (class FunctorWithIndex, mapWithIndex)
1212
import Data.Int (toNumber, pow)
@@ -129,6 +129,10 @@ main = do
129129
let pred x = if x > 5 then Just (x * 100) else Nothing
130130
assert $ findMap pred [1, 5, 10, 20] == Just 1000
131131

132+
log "Test findMapWithIndex" *> do
133+
let pred i x = if x >= 5 && i >= 3 then Just { i, x } else Nothing
134+
assert $ findMapWithIndex pred [1, 5, 10, 20] == Just { i: 3, x: 20 }
135+
132136
log "Test maximum"
133137
assert $ maximum (arrayFrom1UpTo 10) == Just 10
134138

0 commit comments

Comments
 (0)