Suzan Aydın
Suzan Aydın

Reputation: 363

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?

Upvotes: 4

Views: 2497

Answers (3)

Frerich Raabe
Frerich Raabe

Reputation: 94409

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

Upvotes: 19

Tarrasch
Tarrasch

Reputation: 10557

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.

Upvotes: 2

Simeon Visser
Simeon Visser

Reputation: 122456

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.

Upvotes: 6

Related Questions