作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在努力掌握 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/
我是一名优秀的程序员,十分优秀!