'做'在Haskell构建 [英] 'do' construct in Haskell
问题描述
我正在尝试学习Haskell,并希望编写一个小程序,将文件内容打印到屏幕上。当我将其加载到GHCi时,我收到以下错误:
I'm trying to learn Haskell and want to write a small program which prints the content of a file to the screen. When I load it into GHCi I get the following error:
'do'结构中的最后一个语句必须是表达式
The last statement in a 'do' construct must be an expression
我知道这个问题已在这里提出: Haskell - 'do'结构中的最后一个语句必须是表达式。
I know this question has be asked already here: Haskell — "The last statement in a 'do' construct must be an expression".
即使我的代码非常相似,我仍然无法弄清楚问题。如果有人能指出我的问题,我会非常感激。
Even though my code is very similar I still can't figure out the problem. If anyone could point out the problem to me I'd be very thankful.
module Main (main) where
import System.IO
import System(getArgs)
main :: IO()
main = do
args <- getArgs
inh <- openFile $ ReadMode head args
printFile inh
hClose inh
printFile :: Handle -> IO ()
printFile handle = do
end <- hIsEOF handle
if end
then return ()
else do line <- hGetLine handle
putStrLn line
printFile handle
推荐答案
你的缩进被打破。这些更好:
Your indentation is broken. These are better:
printFile :: Handle -> IO ()
printFile handle = do
end <- hIsEOF handle
if end
then return ()
else do line <- hGetLine handle
putStrLn line
printFile handle
printFile :: Handle -> IO ()
printFile handle = do
end <- hIsEOF handle
if end
then return ()
else do
line <- hGetLine handle
putStrLn line
printFile handle
通过如果
进一步缩进而不是 end< - hIsEof handle
,它实际上是一个行继续,而不是中的后续操作做
。类似地,你有 putStrLn行
少于行< -hGetLine句柄
的事实意味着做
(在 else
里面)在那里结束。
By having if
further indented than end <- hIsEof handle
, it was actually a line continuation, not a subsequent action in the do
. Similarly, the fact that you had putStrLn line
less indented than line <- hGetLine handle
means that the do
(inside the else
) ended there.
这篇关于'做'在Haskell构建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!