Haskell(也许,x,也许 y,也许 z)->也许(x,y,z)

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

我有一组 Haskell IO 绑定调用 return Maybe Z,Maybe Y,Maybe Z,其中 X /= Y /= Z。

我想要一个函数 returns Just (X,Y,Z) where ALL are Just n, or else Nothing.

一个天真的实现是

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

但我想知道是否有更优雅的解决方案?也许是某种映射?

据我所知,比较普通

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

不会工作,因为 fn1-3 是 IO 绑定的?

谢谢。

您不需要指定输出类型。您可以使用:

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)

但在这里您可以使用:

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

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