简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM