Is there a safe equivalent of maximum
in Haskell's 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 a
with hoogle, but found none.
2010 Libraries in Haskell: This library also provides us various packages which all the Haskell libraries should support; this library provides us with the basic functionality which can be used with the monad, data list, io, and many more.
The goal of the rio library is to make it easier to adopt Haskell for writing production software. It is intended as a cross between: This repository contains the rio library and other related libraries, such as rio-orphans. There is a tutorial on how to use rio available on FP Complete's Haskell site.
This is neither a tutorial on Haskell Standard Library nor a tutorial on each function contained in relude. For latter see the detailed documentation of every data type, type class and function together with examples and usages in the Haddock documentation for relude.
These modules are nothing but contain the required library, which is very much needed to write a basic program in Haskell or in any other programming language. Here we will see what the functions that are available inside this module are.
For the sake of completeness: loosening your "Standard Library" requirement to "some very commonly used library", the safe package provides the Safe.Foldable
module, which includes a maximumMay
function:
maximumMay :: (Foldable t, Ord a) => t a -> Maybe a
You can code one up yourself for any Foldable
, by applying foldMap
to a suitable choice of Monoid
.
The Option
monoid takes an existing Semigroup
and lifts it into a Monoid
by adjoining an empty element (Option Nothing
), which'll be returned by foldMap
if the input Foldable
is empty. The Max
newtype lifts any instance of Ord
into a Semigroup
by making <>
pick the larger of its arguments.
So by foldMap
ping the input Foldable
through the composition of Option
and Max
, we get your desired behaviour.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With