Convert (maybe a, b) to Maybe (a, b)

Is there a simple (no wheel reuse) to convert from (Maybe a, b)

to Maybe (a,b)

. I have looked at Traversable

but cannot get it to work.

+3


source to share


4 answers


You can also use Bitraversable

:

bitraverse id pure :: (Bitraversable t, Applicative f) => t (f c) d -> f (t c d)

      



which specializes in

bitraverse id pure :: (Maybe a, b) -> Maybe (a, b)

      

+7


source


Yes. Functors.

solution :: (Maybe a, b) -> Maybe (a, b)
solution (a, b) = fmap (\q -> (q, b)) a

      

Or, in a style without spaces:

solution = uncurry $ flip $ fmap . flip (,)

      



Also, as @Bakuriu said, if you include TupleSections

and Control.Applicative

, it becomes very simple:

solution (a, b) = (, b) <$> a

      

More details here .

+5


source


The following works with lens

:

> import Control.Lens
> _1 id (Just 1, 2)
Just (1, 2)

      

+3


source


What do you mean by "without inventing the wheel"? The easiest way to create such a function is as follows:

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

g :: (Maybe a, b) -> Maybe (a, b)
g = uncurry f

      

Hope it helps.

+1


source







All Articles