You can execute the specification using the statements from Control.Applicative .
myMin :: Ord x => Maybe x -> Maybe x -> Maybe x myMin ab = min <$> a <*> b <|> a <|> b
where <|> for Maybe implements "preference"
Nothing <|> b = b a <|> _ = a
Thing
min <$> Just a <*> Just b = Just (min ab)
but
min <$> Just a <*> Nothing = Nothing
which led to some incorrect answers to this question. Using <|> allows you to use the calculated value of min when it is available, but restore with any of them, if only one is Just .
But you should ask if Maybe used this way. With the inglorious exception of its instance, Monoid Maybe set up to model fault-tolerant computing. You have an extension of an existing Ord with a "top" element.
data Topped x = Val x | Top deriving (Show, Eq, Ord)
and you will find that min for Topped x is exactly what you need. It's good to think about types, not data representations, but about data equipment with structure. Nothing usually some kind of failure, so it might be better to use a different type for your purpose.
source share