Search code examples
ubuntuhaskellfunctional-programminghugs

Word count of a file with haskell


I have a problem with Haskell when i am trying to count the words of a file. I am just a beginner and this is my first program so i am pretty sure that it is a very simple mistake. I am using hugs to run my code. Until now i learnt how to read from a file but i failed to count the words in it. My code is something like this

main = do {
contents <- readFile "/tmp/foo.txt";
let contents2 = replace"."""contents;
let contents3 = replace"!"""contents2;
let lower = map toLower contents3;
let chop = words(lower);
let count = show(length chop)++"\n";
putStrln $"This file has"++count++"words";
}

Any help would be very appreciated. Thanks!


Solution

  • You may use either one of the following:

    main = readFile "/tmp/foo.txt" >>= print . length . words
    

    or

    main = do
        contents <- readFile "/tmp/foo.txt"
        print . length . words $ contents