gpt4 book ai didi

haskell - 如何在 Maybe 和 IO 中使用 Do 表示法

转载 作者:行者123 更新时间:2023-12-02 07:57:53 24 4
gpt4 key购买 nike

我正在努力掌握 Haskell 中的 do notation

我可以将它与 Maybe 一起使用,然后打印结果。像这样:

maybeAdd :: Maybe Integer
maybeAdd = do one <- maybe1
two <- maybe2
three <- maybe3
return (one + two + three)

main :: IO ()
main = putStr (show $ fromMaybe 0 maybeAdd)

但我没有使用单独的函数,而是尝试在 main 函数中使用带有 Maybe 的 do 表示法。但我没有任何运气。我尝试的各种尝试包括:

main :: IO ()
main = do one <- maybe1
two <- maybe2
three <- maybe3
putStr (show $ fromMaybe 0 $ return (one + two + three))
main :: IO ()
main = do one <- maybe1
two <- maybe2
three <- maybe3
putStr (show $ fromMaybe 0 $ Just (one + two + three))
main :: IO ()
main = do one <- maybe1
two <- maybe2
three <- maybe3
putStr (show $ (one + two + three))

所有这些都会导致各种类型的编译错误,遗憾的是我未能破译以找到正确的方法。

我如何实现上述目标?也许也可以解释为什么我尝试的方法是错误的?

最佳答案

每个 do block 必须在单个 monad 中工作。如果你想使用多个 monad,你可以使用多个 do block 。尝试调整您的代码:

main :: IO ()
main = do -- IO block
let x = do -- Maybe block
one <- maybe1
two <- maybe2
three <- maybe3
return (one + two + three)
putStr (show $ fromMaybe 0 x)

你甚至可以使用

main = do -- IO block
putStr $ show $ fromMaybe 0 $ do -- Maybe block
one <- maybe1
two <- maybe2
three <- maybe3
return (one + two + three)
-- other IO actions here

但在某些情况下可能不太可读。

关于haskell - 如何在 Maybe 和 IO 中使用 Do 表示法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61153956/

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