0

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

zootechdrum
  • 111
  • 1
  • 8
  • 4
    The percentage sign is not related to Haskell, it's coming from the shell: [Getting a weird percent sign in printf output in terminal with C](https://stackoverflow.com/q/27238564/770830). – bereal Nov 27 '21 at 07:39
  • I think it would help you to quote the exercise's problem statement in its entirety, along with the original source file it's asking you to modify. – amalloy Nov 27 '21 at 08:01
  • This is similar question: https://stackoverflow.com/questions/7867723/haskell-file-reading – David Lukas Nov 27 '21 at 19:59

1 Answers1

1
  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"
advait
  • 6,355
  • 4
  • 29
  • 39