Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Haskell (Maybe, x, Maybe y, Maybe z) -> Maybe (x,y,z)

I have a set of Haskell IO bound calls that return Maybe Z, Maybe Y, Maybe Z, where X /= Y /= Z.

I would like a function that returns Just (X,Y,Z) where ALL are Just n, or else Nothing.

A naive implementation would be

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

fn :: (Maybe x, Maybe y, Maybe z) -> Maybe (x,y,z)
fn (Just x, Just y, Just z) = Just (x,y,z)
fn _ = Nothing

but I’m wondering is there a more elegant solution? Perhaps some kind of mapping?

As far as I can see, the more usual

let x = do x <- fn1
           y <- fn2
           z <- fn3
           return (x,y,z) :: Maybe (X,Y,Z)

isn’t going to work because fn1-3 are IO bound?

thanks.

>Solution :

You do not need to specify the output type. You can work with:

f :: Monad m => m a -> m b -> m c -> m (a, b, c)
f mx my mz = do
    x <- mx
    y <- my
    z <- mz
    return (x, y, z)

But here you can work with:

f :: Applicative f => f a -> f b -> f c -> f (a, b, c)
f fa fb fc = (,,) <$> fa <*> fb <*> fc

or as @RobinZigmond says, with liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d:

import Control.Applicative(liftA3)

f :: Applicative f => f a -> f b -> f c -> f (a, b, c)
f = liftA3 (,,)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading