Define a function
pairMaybe :: Maybe a -> Maybe b -> Maybe (a,b)
that produces a
Just
result only if both arguments areJust
, and aNothing
if either argument isNothing
.
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 (,)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With