Before we took a detour to learn about do notation, we had just finished adding support for collecting metadata about the files that we are going to view, and writing a function to display that information in a status bar. Now that we know about do notation we’ll be able to take on a small bit of refactoring work to make integrating this feature into our application easier.

The first thing that we need to do is to update our paginate function to add the status bar to the end of each page of text that we generate. Let’s take a look at the refactored version of paginate and then we can briefly walk through what it’s doing:

​  paginate :: ​ ScreenDimensions ​ -> ​ FileInfo ​ -> ​ Text ​.​ Text ​ -> [​ Text ​.​ Text ​]
​  paginate (​ ScreenDimensions ​ rows cols) finfo text =
​  ​ let ​
​  rows' = rows - 1
​  wrappedLines = concatMap (wordWrap cols) (​ Text ​.lines text)
​  pages = map (​ Text ​.unlines . padTo rows') $ groupsOf rows' wrappedLines
​  pageCount = length pages
​  statusLines = map (formatFileInfo finfo cols pageCount) [1..pageCount]
​  ​ in ​ zipWith (<>) pages statusLines
​  ​ where ​
​  padTo :: ​ Int ​ -> [​ Text ​.​ Text ​] -> [​ Text ​.​ Text ​]
​  padTo lineCount rowsToPad =
​  take lineCount $ rowsToPad <> repeat ​ "" ​

Our underlying pagination function remains the same as before, but we’ve made a couple of changes. First, we’re taking the input text and generating pages that are each a single line shorter than the size of our screen, using rows’ . This gives us room for the status bar at the bottom.

The next change is that we’re adding padding to the bottom of each page, using padTo . In this example, we’re simply adding as many empty lines as necessary to ensure that we have enough rows to fill the available vertical space. Once we’ve padded out the list of rows, we use Text.unlines to transform the collections of rows into a single page of text with newlines.

After generating the individual pages, we count the total number of pages and use that count to generate a unique status line for each page. The line zipWith (<>) pages statusLines will go through the list of pages and status lines and append each status line to its corresponding page.

So far, so good; we can generate pages using file metadata now, but we need to actually get the metadata and pass it into paginate . Right now we’re calling paginate from runHCat , and runHCat has gotten a little hard to work with.

Recall from earlier in this chapter that our current version of runHCat is:

​  runHCat :: ​ IO ​ ()
​  runHCat =
​  handleArgs
​  >>= eitherToErr
​  >>= flip openFile ​ ReadMode ​
​  >>= ​ Text ​.hGetContents
​  >>= ​ \ ​contents ->
​  getTerminalSize >>= ​ \ ​termSize ->
​  ​ let ​ pages = paginate termSize contents
​  ​ in ​ showPages pages

We could continue with our current implementation and add a call to fileInfo so that we can pass it along to paginate :

​  runHCat :: ​ IO ​ ()
​  runHCat =
​  handleArgs
​  >>= eitherToErr
​  >>= ​ \ ​targetFilePath ->
​  openFile targetFilePath ​ ReadMode ​
​  
​  >>= ​ TextIO ​.hGetContents
​  >>= ​ \ ​contents ->
​  getTerminalSize >>= ​ \ ​termSize ->
​  fileInfo targetFilePath >>= ​ \ ​finfo ->
​  ​ let ​ pages = paginate termSize finfo contents
​  ​ in ​ showPages pages

If you run this, you might notice a bug: the status line in our program should be displaying, but on most systems it will actually be invisible until you try to exit the program, at which point it will appear. The problem here is terminal buffering. By default, our terminal will be using line-buffered output, which means that each line of text will be printed when the terminal encounters a newline. Our status line doesn’t end with a newline. If it did, we’d end up losing an extra line in our terminal to displaying an empty line for the cursor. Unfortunately, this means that the terminal won’t render our status line until we exit the program. When our program exits, the shell takes back control over standard output and flushes the output buffer of our program.

This is an easy fix. We can use hSetBuffering on stdout just like we did for stdin when we wanted to read keypresses without forcing the user to press enter. The problem is that our function is already quite unwieldy and we’re just adding more layers to it. Without a refactor, the fixed version of runHCat will have yet another layer of nesting:

​  runHCat :: ​ IO ​ ()
​  runHCat =
​  handleArgs
​  >>= eitherToErr
​  >>= ​ \ ​targetFilePath ->
​  openFile targetFilePath ​ ReadMode ​
​  >>= ​ TextIO ​.hGetContents
​  >>= ​ \ ​contents ->
​  getTerminalSize
​  >>= ​ \ ​termSize ->
​  hSetBuffering stdout ​ NoBuffering ​
​  >> fileInfo targetFilePath
​  >>= ​ \ ​finfo ->
​  ​ let ​ pages = paginate termSize finfo contents
​  ​ in ​ showPages pages

It’s clear that this is starting to get unmanageable, so use what we’ve learned about do notation to refactor our function. We’ll start with a completely mechanical translation, replacing >>= \var -> with var <- and otherwise not changing the structure of the code. That leaves us with this version which is already looking quite a bit more readable:

​  runHCat :: ​ IO ​ ()
​  runHCat = ​ do ​
​  args <- handleArgs
​  targetFilePath <- eitherToErr args
​  fileHandle <- openFile targetFilePath ​ ReadMode ​
​  contents <- ​ TextIO ​.hGetContents fileHandle
​  termSize <- getTerminalSize
​  hSetBuffering stdout ​ NoBuffering ​
​  finfo <- fileInfo targetFilePath
​  ​ let ​ pages = paginate termSize finfo contents
​  showPages pages

We’ve eliminated a lot of the nesting and it’s easier to focus on the calls that are being made. There are still some small improvements that we can make though. For one thing, we’ve completely eliminated all uses of >>= in this version of the function, but we can combine do notation with >>= to make code that’s easier to read than using either style alone.

For example, let’s consider the process of opening our file and reading the contents. We are creating fileHandle as an intermediate variable, and then using it immediately to pass as an argument to TextIO.hGetContents . We could use TextIO. readFile here and eliminate the need for a file handle, but for the sake of the example, let’s say we want to keep each step of this explicit.

In this case, the intermediate variable isn’t adding any value, but it does add visual noise that can make it harder for us to see what’s going on. In an ideal world, each binding in our do block would correspond to a meaningful IO action that we want to do. We can often make that happen by combining related IO actions using >>= and then binding the output.

The big drawback to using >>= in a do block is that we can naturally read do bindings right to left, from the IO action to the variable being bound to its output. On the other hand, we’ll typically read >>= from left to right. Switching the direction that we need to read the code in the middle of a line introduces some mental overhead.

To make this easier, we can use \=<< . As you might expect from looking at it, \=<< behaves exactly like >>= but with the arguments reversed. This lets us write a do binding that can entirely be read from right to left.

Let’s refactor our program again using this approach to see how it works in practice:

​  runHCat :: ​ IO ​ ()
​  runHCat = ​ do ​
​  targetFilePath <- eitherToErr =<< handleArgs
​  contents <- ​ TextIO ​.hGetContents =<< openFile targetFilePath ​ ReadMode ​
​  termSize <- getTerminalSize
​  hSetBuffering stdout ​ NoBuffering ​
​  finfo <- fileInfo targetFilePath
​  ​ let ​ pages = paginate termSize finfo contents
​  showPages pages

In cases where you have several IO actions that you want to chain together, using \=<< can also be difficult to use while keeping your code readable. In cases like this, it can be convenient to use nested do blocks:

​  runHCat :: ​ IO ​ ()
​  runHCat = ​ do ​
​  targetFilePath <- ​ do ​
​  args <- handleArgs
​  eitherToErr args
​  
​  contents <- ​ do ​
​  handle <- openFile targetFilePath ​ ReadMode ​
​  ​ TextIO ​.hGetContents handle
​  
​  termSize <- getTerminalSize
​  hSetBuffering stdout ​ NoBuffering ​
​  finfo <- fileInfo targetFilePath
​  ​ let ​ pages = paginate termSize finfo contents
​  showPages pages

Nesting do blocks is an effective way to keep all relevant code in a single function, but avoid having too many bindings in scope at the top level of your function.