gpt4 book ai didi

haskell - 如何处理一个 IO (Maybe (IO (Maybe t))) 类型?

转载 作者:行者123 更新时间:2023-12-04 22:10:31 34 4
gpt4 key购买 nike

我正在处理一个库( ghcjs-dom ),其中每个函数都返回一个 IO (Maybe T) .

我有一个函数a with 返回 IO (Maybe x)和功能 b需要x作为参数并返回 IO (Maybe y) .

是一个让我做a ??? b的运算符(operator)并获得 IO (Maybe y) .我的 Hoogle 搜索一无所获。

我看起来像 join适用于 IO (Maybe (IO (Maybe t)))而不是 IO (IO t)Maybe (Maybe t) .

最佳答案

据我了解,您有:

a :: IO (Maybe X)
b :: X -> IO (Maybe Y)
IO (Maybe a)之间有密切关系和 MaybeT IO a ,即 MaybeT将一个转换为另一个:
MaybeT :: IO (Maybe a) -> MaybeT IO a

而逆运算只是 runMaybeT :
runMaybeT :: MaybeT IO a -> IO (MaybeT a)

在 MaybeT monad 中,您想要执行的组合只是
绑定(bind)操作:
MaybeT a >>= (\x -> MaybeT (b x)) :: MaybeT IO Y

这会产生 MaybeT IO Y 类型的值。 .将其转换回 IO (Maybe Y)只需使用 runMaybeT .

更新

这是一个“组合” a 和 b 的运算符:
andThen :: IO (Maybe a) -> (a -> IO (Maybe b)) -> IO (Maybe b)
andThen a b = runMaybeT $ MaybeT a >>= (\x -> MaybeT (b x) )

但是,如果您发现自己经常使用此运算符,也许您
应该重做你的函数,以便你主要在 MaybeT IO 中工作
monad,然后你可以使用 >>=与单个 runMaybeT在外面。

关于haskell - 如何处理一个 IO (Maybe (IO (Maybe t))) 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38727850/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com