Skip to content

Commit 8413e6d

Browse files
authored
Add maximumBy and minimumBy to Data.Semigroup.Foldable (#123)
1 parent 26d7c0c commit 8413e6d

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/Data/Semigroup/Foldable.purs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@ module Data.Semigroup.Foldable
1616
, intercalate
1717
, intercalateMap
1818
, maximum
19+
, maximumBy
1920
, minimum
21+
, minimumBy
2022
) where
2123

2224
import Prelude
@@ -118,9 +120,15 @@ sequence1_ = traverse1_ identity
118120
maximum :: forall f a. Ord a => Foldable1 f => f a -> a
119121
maximum = ala Max foldMap1
120122

123+
maximumBy :: forall f a. Foldable1 f => (a -> a -> Ordering) -> f a -> a
124+
maximumBy cmp = foldl1 \x y -> if cmp x y == GT then x else y
125+
121126
minimum :: forall f a. Ord a => Foldable1 f => f a -> a
122127
minimum = ala Min foldMap1
123128

129+
minimumBy :: forall f a. Foldable1 f => (a -> a -> Ordering) -> f a -> a
130+
minimumBy cmp = foldl1 \x y -> if cmp x y == LT then x else y
131+
124132
-- | Internal. Used by intercalation functions.
125133
newtype JoinWith a = JoinWith (a -> a)
126134

test/Main.purs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import Data.Maybe (Maybe(..))
1414
import Data.Monoid.Additive (Additive(..))
1515
import Data.Newtype (unwrap)
1616
import Data.Semigroup.Foldable (class Foldable1, foldr1, foldl1, fold1Default, foldr1Default, foldl1Default)
17+
import Data.Semigroup.Foldable as Foldable1
1718
import Data.Traversable (class Traversable, sequenceDefault, traverse, sequence, traverseDefault)
1819
import Data.TraversableWithIndex (class TraversableWithIndex, traverseWithIndex)
1920
import Effect (Effect, foreachE)
@@ -200,6 +201,18 @@ main = do
200201
assert $ "(a(b(cd)))" == foldMap (foldr1 (\x y -> "(" <> x <> y <> ")")) (maybeMkNEArray ["a", "b", "c", "d"])
201202
assert $ "(((ab)c)d)" == foldMap (foldl1 (\x y -> "(" <> x <> y <> ")")) (maybeMkNEArray ["a", "b", "c", "d"])
202203

204+
log "Test maximumBy"
205+
assert $
206+
(Foldable1.maximumBy (compare `on` abs) <$>
207+
(maybeMkNEArray (negate <<< toNumber <$> arrayFrom1UpTo 10)))
208+
== Just (-10.0)
209+
210+
log "Test minimumBy"
211+
assert $
212+
(Foldable1.minimumBy (compare `on` abs) <$>
213+
(maybeMkNEArray (negate <<< toNumber <$> arrayFrom1UpTo 10)))
214+
== Just (-1.0)
215+
203216
log "All done!"
204217

205218

0 commit comments

Comments
 (0)