Build in haskell

I am trying to learn Haskell and want to write a small program that prints the contents of a file on the screen. When I load it into GHCi, I get the following error:

The last statement in the 'do' construct must be an expression

I know this question has already been asked here: Haskell - "The last statement in the" do "construct must be an expression . "

Even though my code is very similar, I still cannot understand the problem. If anyone could point out a problem, I would be very grateful.

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
0
source share
3 answers

Your indentation is broken. This is 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

if , end <- hIsEof handle, , do. , putStrLn line , line <- hGetLine handle, , do ( else) .

+4

. -, if - , end <- ... do. Unindent...

. , 18. 19 20 ( do). ( , )... . , , .

test.hs:9:22:
    Couldn't match expected type `([a] -> a) -> [String] -> FilePath'
           against inferred type `IOMode'
    In the second argument of `($)', namely `ReadMode head args'
    In a stmt of a 'do' expression:
        inh <- openFile $ ReadMode head args
    In the expression:
        do { args <- getArgs;
             inh <- openFile $ ReadMode head args;
             printFile inh;
             hClose inh }

inh <- openFile (head args) ReadMode. , / , , .

+4

You wrote this:

main :: IO()
main = do
    args <- getArgs
    inh <- openFile $ ReadMode head args
    printFile inh
    hClose inh

But this is probably nicer:

main :: IO()
main = do
    args <- getArgs
    withFile (head args) ReadMode printFile
+1
source

All Articles