Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell function returning Just pair of values if both arguments are Just, Nothing otherwise

Define a function

   pairMaybe :: Maybe a -> Maybe b -> Maybe (a,b)

that produces a Just result only if both arguments are Just, and a Nothing if either argument is Nothing.

I’ve come up with:

pairMaybe (Just a) (Just b) = Just (a,b)
pairMaybe (Just a) Nothing = Nothing
pairMaybe Nothing (Just b) = Nothing

I’m not sure if this is the right way of writing it. Is there something wrong with this or is this the way to define this function?

Also I think I’d probably like a better explanation of what this function can actually do, so if I called pairMaybe with two arguments, what arguments can they be? Of course they have to be of type Maybe, but what’s a good example?

like image 402
Suzan Aydın Avatar asked Nov 27 '22 17:11

Suzan Aydın


1 Answers

Doing this via pattern matching is fine; you could simplify your code though by using

pairMaybe :: Maybe a -> Maybe b -> Maybe (a,b)
pairMaybe (Just a) (Just b) = Just (a,b)
pairMaybe _        _        = Nothing

That being said, your function actually just lifts the (,) function (which creates 2-tuples) into the Maybe monad, so you could also write

pairMaybe :: Maybe a -> Maybe b -> Maybe (a,b)
pairMaybe = liftM2 (,)
like image 85
Frerich Raabe Avatar answered Dec 04 '22 10:12

Frerich Raabe