@@ -16,6 +16,10 @@ module Data.Foldable
1616 , elem
1717 , notElem
1818 , find
19+ , maximum
20+ , maximumBy
21+ , minimum
22+ , minimumBy
1923 ) where
2024
2125import Prelude
@@ -228,3 +232,33 @@ notElem x = not <<< elem x
228232-- | Try to find an element in a data structure which satisfies a predicate.
229233find :: forall a f . (Foldable f ) => (a -> Boolean ) -> f a -> Maybe a
230234find p = foldl (\r x -> if p x then Just x else r) Nothing
235+
236+ -- | Find the largest element of a structure, according to its `Ord` instance.
237+ maximum :: forall a f . (Ord a , Foldable f ) => f a -> Maybe a
238+ maximum = maximumBy compare
239+
240+ -- | Find the largest element of a structure, according to a given comparison
241+ -- | function. The comparison function should represent a total ordering (see
242+ -- | the `Ord` type class laws); if it does not, the behaviour is undefined.
243+ maximumBy :: forall a f . (Foldable f ) => (a -> a -> Ordering ) -> f a -> Maybe a
244+ maximumBy cmp = foldl max' Nothing
245+ where
246+ max' Nothing x = Just x
247+ max' (Just x) y = Just (case cmp x y of
248+ GT -> x
249+ _ -> y)
250+
251+ -- | Find the smallest element of a structure, according to its `Ord` instance.
252+ minimum :: forall a f . (Ord a , Foldable f ) => f a -> Maybe a
253+ minimum = minimumBy compare
254+
255+ -- | Find the smallest element of a structure, according to a given comparison
256+ -- | function. The comparison function should represent a total ordering (see
257+ -- | the `Ord` type class laws); if it does not, the behaviour is undefined.
258+ minimumBy :: forall a f . (Foldable f ) => (a -> a -> Ordering ) -> f a -> Maybe a
259+ minimumBy cmp = foldl min' Nothing
260+ where
261+ min' Nothing x = Just x
262+ min' (Just x) y = Just (case cmp x y of
263+ LT -> x
264+ _ -> y)
0 commit comments