在下面的代码第4行中,我有一个表达式夹在do块中的两个IO动作之间:
1 doubleX :: (Show x, Num x) => x -> IO ()
2 doubleX x = do
3 putStrLn ("I will now double " ++ (show x))
4 let double = x * 2
5 putStrLn ("The result is " ++ (show double))
我理解使用>> =或>>链接monadic操作的符号。但是当你在两者之间有表达式时,它是如何工作的?你不能只使用>>。
将第3-5行粘在一起答案 0 :(得分:6)
我要从我非常相似的答案中here(尽管可能不重复,因为该问题并未明确处理let
)。
Report提供了从do语法到内核Haskell的完整翻译;与您的问题相关的部分是:
do {e} = e do {e;stmts} = e >> do {stmts} do {let decls; stmts} = let decls in do {stmts}
所以你的代码就像这样去了:
doubleX x = do
putStrLn ("I will now double " ++ (show x))
let double = x * 2
putStrLn ("The result is " ++ (show double))
==> do {e;stmts} rule
doubleX x =
putStrLn ("I will now double " ++ (show x)) >> do
let double = x * 2
putStrLn ("The result is " ++ (show double))
==> do {let decls; stmts} rule
doubleX x =
putStrLn ("I will now double " ++ (show x)) >>
let double = x * 2 in do
putStrLn ("The result is " ++ (show double))
==> do {e} rule
doubleX x =
putStrLn ("I will now double " ++ (show x)) >>
let double = x * 2 in
putStrLn ("The result is " ++ (show double))