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
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.
CodePudding user response:
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