From 8413e6d8a09c13b60819e03cf56525c33f7acbb3 Mon Sep 17 00:00:00 2001 From: Cyril Date: Tue, 8 Dec 2020 04:25:51 +0100 Subject: [PATCH] Add maximumBy and minimumBy to Data.Semigroup.Foldable (#123) --- src/Data/Semigroup/Foldable.purs | 8 ++++++++ test/Main.purs | 13 +++++++++++++ 2 files changed, 21 insertions(+) diff --git a/src/Data/Semigroup/Foldable.purs b/src/Data/Semigroup/Foldable.purs index 2a06b62..e16006d 100644 --- a/src/Data/Semigroup/Foldable.purs +++ b/src/Data/Semigroup/Foldable.purs @@ -16,7 +16,9 @@ module Data.Semigroup.Foldable , intercalate , intercalateMap , maximum + , maximumBy , minimum + , minimumBy ) where import Prelude @@ -118,9 +120,15 @@ sequence1_ = traverse1_ identity maximum :: forall f a. Ord a => Foldable1 f => f a -> a maximum = ala Max foldMap1 +maximumBy :: forall f a. Foldable1 f => (a -> a -> Ordering) -> f a -> a +maximumBy cmp = foldl1 \x y -> if cmp x y == GT then x else y + minimum :: forall f a. Ord a => Foldable1 f => f a -> a minimum = ala Min foldMap1 +minimumBy :: forall f a. Foldable1 f => (a -> a -> Ordering) -> f a -> a +minimumBy cmp = foldl1 \x y -> if cmp x y == LT then x else y + -- | Internal. Used by intercalation functions. newtype JoinWith a = JoinWith (a -> a) diff --git a/test/Main.purs b/test/Main.purs index 5f7da7b..9f86a01 100644 --- a/test/Main.purs +++ b/test/Main.purs @@ -14,6 +14,7 @@ import Data.Maybe (Maybe(..)) import Data.Monoid.Additive (Additive(..)) import Data.Newtype (unwrap) import Data.Semigroup.Foldable (class Foldable1, foldr1, foldl1, fold1Default, foldr1Default, foldl1Default) +import Data.Semigroup.Foldable as Foldable1 import Data.Traversable (class Traversable, sequenceDefault, traverse, sequence, traverseDefault) import Data.TraversableWithIndex (class TraversableWithIndex, traverseWithIndex) import Effect (Effect, foreachE) @@ -200,6 +201,18 @@ main = do assert $ "(a(b(cd)))" == foldMap (foldr1 (\x y -> "(" <> x <> y <> ")")) (maybeMkNEArray ["a", "b", "c", "d"]) assert $ "(((ab)c)d)" == foldMap (foldl1 (\x y -> "(" <> x <> y <> ")")) (maybeMkNEArray ["a", "b", "c", "d"]) + log "Test maximumBy" + assert $ + (Foldable1.maximumBy (compare `on` abs) <$> + (maybeMkNEArray (negate <<< toNumber <$> arrayFrom1UpTo 10))) + == Just (-10.0) + + log "Test minimumBy" + assert $ + (Foldable1.minimumBy (compare `on` abs) <$> + (maybeMkNEArray (negate <<< toNumber <$> arrayFrom1UpTo 10))) + == Just (-1.0) + log "All done!"