Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe `maximum` in Haskell Standard Library?

Tags:

haskell

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.

like image 525
Kevin Meredith Avatar asked May 16 '17 12:05

Kevin Meredith


People also ask

What are the 2010 libraries in Haskell?

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.

What is the Rio library for Haskell?

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.

Is there a tutorial on Haskell standard library in Relude?

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.

What is a module in Haskell?

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.


2 Answers

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
like image 163
duplode Avatar answered Oct 14 '22 05:10

duplode


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 foldMapping 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
like image 42
Benjamin Hodgson Avatar answered Oct 14 '22 05:10

Benjamin Hodgson