Skip to content

Commit 7ba6690

Browse files
author
Martin Bidlingmaier
committed
Let findWithIndex also return index of found value
Because Data.Tuple depends on this package, `findWithIndex` can't return an actual `Tuple`. `ValueWithIndex` exists as a workaround. Also tweaks the test slightly, and adds a type signature for a local function.
1 parent c4875cc commit 7ba6690

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
@@ -10,6 +10,7 @@ module Data.FoldableWithIndex
1010
, surroundMapWithIndex
1111
, allWithIndex
1212
, anyWithIndex
13+
, ValueWithIndex
1314
, findWithIndex
1415
) where
1516

@@ -259,15 +260,19 @@ anyWithIndex
259260
-> b
260261
anyWithIndex t = unwrap <<< foldMapWithIndex (\i -> Disj <<< t i)
261262

263+
-- | Isomorphic to `Tuple i a`.
264+
type ValueWithIndex i a = { index :: i, value :: a }
265+
262266
-- | Try to find an element in a data structure which satisfies a predicate
263267
-- | with access to the index.
264268
findWithIndex
265269
:: forall i a f
266270
. FoldableWithIndex i f
267271
=> (i -> a -> Boolean)
268272
-> f a
269-
-> Maybe a
273+
-> Maybe (ValueWithIndex i a)
270274
findWithIndex p = foldlWithIndex go Nothing
271275
where
272-
go i Nothing x | p i x = Just x
273-
go i r _ = r
276+
go :: i -> Maybe (ValueWithIndex i a) -> a -> Maybe (ValueWithIndex i a)
277+
go i Nothing x | p i x = Just { index: i, value: x}
278+
go _ r _ = r

test/Main.purs

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

102102
log "Test findWithIndex"
103-
assert $ findWithIndex (\i x -> i == 2 && x `mod` 2 == 0) [1, 2, 4, 6] == Just 4
103+
assert $
104+
case findWithIndex (\i x -> i `mod` 2 == 0 && x `mod` 2 == 0) [1, 2, 4, 6] of
105+
Nothing -> false
106+
Just { index, value } -> index == 2 && value == 4
104107

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

0 commit comments

Comments
 (0)