[Haskell-beginners] count function

Alexander Dunlap alexander.dunlap at gmail.com
Sun Oct 18 11:01:53 EDT 2009


On Sun, Oct 18, 2009 at 7:52 AM, John Moore <john.moore54 at gmail.com> wrote:
> Hi,
>  Trying to get aprogram to count all the lines or words from a file. Not
> sure about the syntax. Probably missing some.
> Here's what I have so far any help in the right direction would be great.
>
> import System.IO
> main :: IO ()
> main = do
>        incom <- openFile "file.txt" ReadMode
>        otcom <- openFile "prob.txt" WriteMode
>        fCount incom otcom
>        hClose incom
>        hClose otcom
>        fCount incomh otcomh =
>          do eof <- hIsEof incomh
>              if eof
>               then return()
>               else do c <- hGetCount incom
>
> it tells me parse error on =
>
> John

Add a "where" before fCount - this lets you introduce auxiliary
functions. Alternatively, you could define fCount at the top level.

The way I would count all of the lines in a file is (untested)

fCountLines :: String -> IO Int
fCountLines = length . lines . readFile

Hope that helps.

Alex


More information about the Beginners mailing list