gpt4 book ai didi

haskell - 使用防护装置正确的缩进规则

转载 作者:行者123 更新时间:2023-12-02 09:07:59 28 4
gpt4 key购买 nike

我查看了有关缩进的问题,但没有任何帮助。我的缩进看起来也正确,但根据编译器的说法,它不是。正确的缩进是什么以及规则是什么?

readFile filename = do 
inputFile <- openFile filename ReadMode
readLines inputFile
hClose inputFile

readLines inputFile =
do endof <- hIsEOF inputFile
| endof = return()
| otherwise = do
inpStr <- hGetLine inputFile
print inpStr
readLines inputFile

全部使用空格,不使用制表符。错误:“输入‘|’时出现解析错误|结束=返回()“

最佳答案

您可以为此重组代码,例如

readLines :: Handle -> IO ()
readLines inputFile = g =<< hIsEOF inputFile
where -- hIsEOF :: Handle -> IO Bool
g endof
| endof = return ()
| otherwise = do
inpStr <- hGetLine inputFile
print inpStr
readLines inputFile

守卫,| ... , 属于函数定义或 case 表达式。它们不能出现在do中自己阻止。

g =<< hIsEOF inputFile是一种更短的书写方式

readLines inputFile  =  do {  endof <- hIsEOF inputFile
; g endof
}
where
g endof
| endof = .....

但更简单的选择是使用 if ... then ... else ...do首先阻止:

readLines inputFile = 
do { endof <- hIsEOF inputFile
; if endof
then return()
else do { inpStr <- hGetLine inputFile
; print inpStr
; readLines inputFile
}}

还有一个正在使用 LambdaCase内联 g定义:

readLines :: Handle -> IO ()
readLines inputFile = hIsEOF inputFile >>=
(\ case { True -> return ()
; _ -> do
inpStr <- hGetLine inputFile
print inpStr
readLines inputFile })

case 子句可以有防护(尽管这里我们不需要它们)。

关于haskell - 使用防护装置正确的缩进规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55688093/

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