haskell do 和 let ..in 语句的缩进问题

haskell indentation issue with do and let ..in statements

我尝试了各种组合来修复以下代码的缩进但失败了。我该如何解决以下问题

fold' list = do
    let result = foldl (+) list
    in putStrLn $ "Reduced " ++ show(result)
    return $ result

 parse error on input `in'
Failed, modules loaded: none.

do子句中,不应使用in关键字.

所以你可以通过写作来修复它:

fold' list = do
    let result = foldl (+) list
    putStrLn $ "Reduced " ++ show(result)   -- no "in" keyword
    return $ result

let 语句的范围是其余子句。

翻译如section 3.14 of the Haskell report [link]中指定:

do {e}                =   e
do {e;stmts}          =   e >> do {stmts}
do {p <- e; stmts}    = let ok p = do {stmts}
                            ok _ = fail "..."
                        in e >>= ok
do {let decls; stmts} =   let decls in do {stmts}

因此,如果我们定义两个同名的 let 语句( 推荐),第一个移动到顶部的语句将被计算在内。

因此:

foo = do
    let x = "4"
    putStrLn x
    let x = "2"
    putStrLn x

它将转化为:

foo = let x = "4" in (putStrLn x >> (let x = "2" in putStrLn x))

因此第一个 putStrLn 将使用 let x = "4" 定义的 x 而最后一个将使用 let x = "2" 定义的 x