Skip to content

Commit 17ddb52

Browse files
authored
Merge pull request #50 from LiamGoodacre/master
Add `findMap`
2 parents 3db300e + d33623c commit 17ddb52

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

src/Data/Foldable.purs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ module Data.Foldable
1616
, elem
1717
, notElem
1818
, find
19+
, findMap
1920
, maximum
2021
, maximumBy
2122
, minimum
@@ -269,6 +270,13 @@ find p = foldl go Nothing
269270
go Nothing x | p x = Just x
270271
go r _ = r
271272

273+
-- | Try to find an element in a data structure which satisfies a predicate mapping.
274+
findMap :: forall a b f. Foldable f => (a -> Maybe b) -> f a -> Maybe b
275+
findMap p = foldl go Nothing
276+
where
277+
go Nothing x = p x
278+
go r _ = r
279+
272280
-- | Find the largest element of a structure, according to its `Ord` instance.
273281
maximum :: forall a f. (Ord a, Foldable f) => f a -> Maybe a
274282
maximum = maximumBy compare

test/Main.purs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import Control.Monad.Eff.Console (CONSOLE, log)
88
import Data.Bifoldable (class Bifoldable, bifoldl, bifoldr, bifoldMap, bifoldrDefault, bifoldlDefault, bifoldMapDefaultR, bifoldMapDefaultL)
99
import Data.Bifunctor (class Bifunctor, bimap)
1010
import Data.Bitraversable (class Bitraversable, bisequenceDefault, bitraverse, bisequence, bitraverseDefault)
11-
import Data.Foldable (class Foldable, foldl, foldr, foldMap, foldrDefault, foldlDefault, foldMapDefaultR, foldMapDefaultL, minimumBy, minimum, maximumBy, maximum, find)
11+
import Data.Foldable (class Foldable, foldl, foldr, foldMap, foldrDefault, foldlDefault, foldMapDefaultR, foldMapDefaultL, minimumBy, minimum, maximumBy, maximum, find, findMap)
1212
import Data.Function (on)
1313
import Data.Int (toNumber)
1414
import Data.Maybe (Maybe(..))
@@ -81,6 +81,10 @@ main = do
8181
assert $ find (_ == 10) [1, 5, 10] == Just 10
8282
assert $ find (\x -> x `mod` 2 == 0) [1, 4, 10] == Just 4
8383

84+
log "Test findMap" *> do
85+
let pred x = if x > 5 then Just (x * 100) else Nothing
86+
assert $ findMap pred [1, 5, 10, 20] == Just 1000
87+
8488
log "Test maximum"
8589
assert $ maximum (arrayFrom1UpTo 10) == Just 10
8690

0 commit comments

Comments
 (0)