Search code examples
haskelloption-type

Another Maybe for "find minimum" functions


Maybe is useful when we are searching "maximum" value and unconvinient for finding minimum

-- update maximum could be used as "lambda"
updateMaximum :: (Ord a) => Maybe a -> Maybe a -> Maybe a
updateMaximum saved new = max new saved
    
-- update minimum could't be used as "lambda"
updateMinimum Nothing new = new
updateMinimum saved Nothing = saved
updateMininum saved new = min new saved

The ideal solution would be the standard monad with another constructors order, but i didn't find it:

data Maybe' a = Just' a | Notheing'
-- all standard functions implementations:
safeHaad' :: [a] -> Maybe' a
...

So the issue is: what is the standart way in haskell for writing "updateMinimum" function?

P.S. Two possible solutions are available, but each with its own disadvantage:

  • change problem wording: find minimum of function "f()" -> find maximum of funciton "0-f()"
  • Use "MyMaybe" with swapped constructors order: data MyMaybe a = Value a | None

Solution

  • The monoid-extras package provides the Inf data type, with variants PosInf and NegInf, for exactly this purpose. Your two functions look like this:

    updateMaximum :: Ord a => NegInf a -> NegInf a -> NegInf a
    updateMaximum = max
    
    updateMinimum :: Ord a => PosInf a -> PosInf a -> PosInf a
    updateMinimum = min
    

    I wouldn't even bother naming them.