gpt4 book ai didi

haskell - Haskell do block 中如何允许表达式

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

在以下代码的第 4 行中,我在 do block 中的两个 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))

我将 do 表示法理解为使用 >>= 或 >> 将单子(monad)操作链接在一起。但是当你在两者之间有一个表达式时,它是如何工作的呢?您不能只使用 >> 将第 3-5 行粘合在一起。

最佳答案

我将从我非常相似的答案中抄袭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))

关于haskell - Haskell do block 中如何允许表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45404126/

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