Safe `maximum` in the Haskell standard library?

Is there a safe equivalent maximumin the Haskell standard library?

*Main Control.Monad.State Data.List> maximum []
*** Exception: Prelude.maximum: empty list

I tried to find one, (Ord a, Foldable t) => t a -> Maybe awith hoogle , but did not find it.

+4
source share
3 answers

For completeness: easing the requirement of the "standard library" for "some commonly used library", the secure package provides a Safe.Foldablemodule that includes a function maximumMay:

maximumMay :: (Foldable t, Ord a) => t a -> Maybe a
+5
source

You can create your own:

maximumMaybe :: (Ord a, Foldable f) => f a -> Maybe a
maximumMaybe xs
  | null xs   = Nothing
  | otherwise = Just $ maximum xs

Previous answer (does not add up):

maximumMaybe :: Ord a => [a] -> Maybe a
maximumMaybe xs = listToMaybe xs *> Just (maximum xs)

Or if you like the dots-less style:

maximumMaybe :: Ord a => [a] -> Maybe a
maximumMaybe = (<*) . Just . maximum <*> listToMaybe

Another, simpler solution is:

maximumMaybe :: Ord a => [a] -> Maybe a
maximumMaybe [] = Nothing
maximumMaybe xs = Just $ maximum xs
+3

Foldable, foldMap Monoid.

Option Semigroup Monoid, (Option Nothing), foldMap, Foldable . Max newtype Ord Semigroup, <> .

, foldMap ping Foldable Option Max, .

safeMaximum :: (Foldable t, Ord a) => t a -> Maybe a
safeMaximum = fmap getMax . getOption . foldMap (Option . Just . Max)

ghci> safeMaximum "wowzers"
Just 'z'
ghci> safeMaximum ""
Nothing
+3

Source: https://habr.com/ru/post/1677255/


All Articles