Home > Back-end >  How t to count the number of words in a file in Haskell?
How t to count the number of words in a file in Haskell?

Time:12-03

I am following this book. http://book.realworldhaskell.org/read/getting-started.html

I am completly stuck on how to count the number of words in a file. On my way of trying to solve this I also notices something interesting.

main = interact wordCount
    where wordCount input = show (length (input))    "\n"

I noticed that without the "\n" character I instead get a percentage sign appended at the end of the number.

main = interact wordCount
    where wordCount input = show (length (input))

So I have 2 questions why do I get the percentage sign if I don't append the "\n" character and how do I count all the words in a file? This is so much more complicated than any interpreted language I have learned. But I am loving the challenge.

In my text file I deleted all city's except for one. Below is the contents of my txt file

Teignmouth, England

CodePudding user response:

  1. Your shell is actually appending a % because the output of your program doesn't end with a newline (see here). The POSIX standard defines a "line" as something that ends with a \n (see here).

  2. The function words is what you're looking for:

main = interact wordCount
    where wordCount input = (show $ length $ words input)    "\n"

Note that the $ operator allows for reduction of parentheses. This code is equivalent:

main = interact wordCount
    where wordCount input = (show (length (words input)))    "\n"
  • Related