0

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!

user3104760
  • 143
  • 6

1 Answers1

1

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
nobody
  • 414
  • 2
  • 8
  • 18
  • So do we use the same logic when we try to find any characters? Are there any shortcut methods for that too?? – user3104760 Dec 16 '15 at 12:58
  • I tried a code like this but gave an error for the letter "s". What is the reason for the error? readFile "/tmp/foo.txt">>= print . length . filter s ; – user3104760 Dec 16 '15 at 15:22
  • Are you looking for total number of a specific character? You may use `readFile "/tmp/foo.txt" >>= print . length . filter (== 's')`. – nobody Dec 17 '15 at 11:16