'做'在Haskell构建 [英] 'do' construct in Haskell

查看:150
本文介绍了'做'在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆