From 882214f577ec843f3e76f63b86850689a1209c3e Mon Sep 17 00:00:00 2001 From: Olivia Brode-Roger Date: Fri, 14 Jul 2023 09:16:41 -0700 Subject: [PATCH] add reverseFilter (#177) --- src/List/Extra.elm | 25 +++++++++++++++++++++++-- tests/Tests.elm | 5 +++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/List/Extra.elm b/src/List/Extra.elm index cdf8ba3..3d95253 100644 --- a/src/List/Extra.elm +++ b/src/List/Extra.elm @@ -1,5 +1,5 @@ module List.Extra exposing - ( last, init, getAt, uncons, unconsLast, maximumBy, maximumWith, minimumBy, minimumWith, andMap, andThen, reverseMap, takeWhile, dropWhile, unique, uniqueBy, allDifferent, allDifferentBy, setIf, setAt, remove, updateIf, updateAt, updateIfIndex, removeAt, removeIfIndex, filterNot, swapAt, stableSortWith + ( last, init, getAt, uncons, unconsLast, maximumBy, maximumWith, minimumBy, minimumWith, andMap, andThen, reverseMap, reverseFilter, takeWhile, dropWhile, unique, uniqueBy, allDifferent, allDifferentBy, setIf, setAt, remove, updateIf, updateAt, updateIfIndex, removeAt, removeIfIndex, filterNot, swapAt, stableSortWith , intercalate, transpose, subsequences, permutations, interweave, cartesianProduct, uniquePairs , foldl1, foldr1, indexedFoldl, indexedFoldr, Step(..), stoppableFoldl , scanl, scanl1, scanr, scanr1, mapAccuml, mapAccumr, unfoldr, iterate, initialize, cycle, reverseRange @@ -17,7 +17,7 @@ module List.Extra exposing # Basics -@docs last, init, getAt, uncons, unconsLast, maximumBy, maximumWith, minimumBy, minimumWith, andMap, andThen, reverseMap, takeWhile, dropWhile, unique, uniqueBy, allDifferent, allDifferentBy, setIf, setAt, remove, updateIf, updateAt, updateIfIndex, removeAt, removeIfIndex, filterNot, swapAt, stableSortWith +@docs last, init, getAt, uncons, unconsLast, maximumBy, maximumWith, minimumBy, minimumWith, andMap, andThen, reverseMap, reverseFilter, takeWhile, dropWhile, unique, uniqueBy, allDifferent, allDifferentBy, setIf, setAt, remove, updateIf, updateAt, updateIfIndex, removeAt, removeIfIndex, filterNot, swapAt, stableSortWith # List transformations @@ -569,6 +569,27 @@ reverseMap f xs = foldl (\x acc -> f x :: acc) [] xs +{-| `reverseMap f xs` gives the same result as `List.reverse (List.map f xs)`, +but is tail-recursive and slightly more efficient. + + reverseFilter (\x -> x > 5) [ 1, 4, 9, 16] + --> [ 16, 9 ] + +-} +reverseFilter : (a -> Bool) -> List a -> List a +reverseFilter isGood xs = + foldl + (\x acc -> + if isGood x then + x :: acc + + else + acc + ) + [] + xs + + {-| Negation of `member`. notMember 1 [ 1, 2, 3 ] diff --git a/tests/Tests.elm b/tests/Tests.elm index a362ef7..080a94e 100644 --- a/tests/Tests.elm +++ b/tests/Tests.elm @@ -40,6 +40,11 @@ all = \() -> Expect.equal (reverseMap sqrt [ 1, 4, 9 ]) [ 3, 2, 1 ] ] + , describe "reverseFilter" <| + [ test "filters and reverses" <| + \() -> + Expect.equal (reverseFilter (\x -> x > 5) [ 1, 4, 9, 16 ]) [ 16, 9 ] + ] , describe "notMember" <| [ test "disconfirms member" <| \() ->