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

StackOverflow https://stackoverflow.com/questions/20294098

  •  06-08-2022
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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 (,)

OTHER TIPS

You missed the pattern where both values are Nothing (that won't match to any of your patterns):

pairMaybe Nothing Nothing = Nothing

Other than that pattern matching is a great way of getting things done in Haskell.

Looks great! Though you can shorten it a bit.

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

This also fixes the bug Simeon pointed out. The reason you can simplify it like that is that all the right hand sides with Nothing are the same, so those cases can be merged into one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top