Appendix C. Word statistics example with monad transformers
We considered several examples and discussed many aspects of the monads and monad transformers. Let's now try it one more time. The next example shows you a set of monad mechanisms. The code it demonstrates is much closer to real code that you might see in Haskell projects. It's highly combinatorial and functional, as it uses the point-free style, higher-order functions, and general monadic combinators. It might be challenging to go through, so you might want to learn more functional programming in Haskell while studying this example. Just tell yourself, "To be, or not to be: that is the question" when you’re struggling with some difficult concept. By the way, Shakespeare's famous statement will be our data. The task is to get the following word statistics:
be: 2 is: 1 not: 1 or: 1 question: 1 that: 1 the: 1 to: 2
We'll take a text, normalize it by throwing out any characters except letters, then break the text into words; then we'll collect word statistics. In this data transformation, we'll use three monads: the IO monad to print results, the Reader monad to keep the text-normalizing configuration, and the State monad to collect statistics. We'll solve this task twice. In the first solution, we just nest all monadic functions without mixing effects. In the second solution, we'll compose a monad stack. Listing C.1 shows the first solution.