Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/Data/Semigroup/Foldable.purs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ module Data.Semigroup.Foldable
, intercalate
, intercalateMap
, maximum
, maximumBy
, minimum
, minimumBy
) where

import Prelude
Expand Down Expand Up @@ -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)

Expand Down
13 changes: 13 additions & 0 deletions test/Main.purs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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!"


Expand Down