At least two maybes

I want to get at least two possible values, either if someone gets nothing without nothing, or returns nothing if both inputs are nothing. I can write a simple function for this, but I suspect there is a way to do this without writing a custom function. Sorry if this is a minor question, but is there an easier way than using this custom function?

minMaybe :: Ord a => Maybe a -> Maybe a -> Maybe a minMaybe Nothing b = b minMaybe a Nothing = a minMaybe (Just a) (Just b) = Just $ min ab 
+6
source share
3 answers

You cannot use an Applicative or Monad instance for this, since any Nothing in these contexts will have your final Nothing result. Moreover, the term "simpler" is very stubborn, and your function is beautiful, as it is.

+3
source

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.

+17
source

You can write it with an instance of Alternative Maybe :

 minMaybe ab = liftA2 min ab <|> a <|> b 

Alternatively, you can use maxBound by default, so it always selects another:

 minMaybe ab = liftA2 min (da) (db) where dx = x <|> Just maxBound 

But I do not recommend this.

+3
source

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


All Articles