In the last section, you finished the second version of your file viewing application. This version added the ability to scroll through a document a page at a time, and would allow you to exit the program at any time. In this section, we’re going to expand on our example program by including some additional information in a status bar. There are a lot of pieces of information that we could potentially add to a status bar, and you can choose to add some extra information if you’d like while you are working through this section, but we’ll focus our example on adding these:

  1. The name of the file
  2. The size of the file, in bytes
  3. The last time the file was modified
  4. The read, write, and execute permissions on the file
  5. The current page that we’re viewing
  6. The total number of pages in the document

To get some of this information we’ll need to add a dependency on couple of common packages. The directory package will give us some cross-platform tools for getting information about files and directories. We’ll use this package to get information like the modification time and permissions. The time package will give us the ability to format a timestamp to make it human readable.

​  ​ import ​ ​ qualified ​ ​ Data.ByteString ​ ​ as ​ BS
​  ​ import ​ ​ qualified ​ ​ Data.Time.Clock ​ ​ as ​ Clock
​  ​ import ​ ​ qualified ​ ​ Data.Time.Format ​ ​ as ​ TimeFormat
​  ​ import ​ ​ qualified ​ ​ Data.Time.Clock.POSIX ​ ​ as ​ PosixClock
​  ​ import ​ ​ qualified ​ ​ System.Directory ​ ​ as ​ Directory

Collecting Information

The first thing that we need to do is to create a record to hold all of the data about our file that we want to show in the status line. In this example, we’ll call our record FileInfo :

​  ​ data ​ ​ FileInfo ​ = ​ FileInfo ​
​  { filePath :: ​ FilePath ​
​  , fileSize :: ​ Int ​
​  , fileMTime :: ​ Clock ​.​ UTCTime ​
​  , fileReadable :: ​ Bool ​
​  , fileWriteable :: ​ Bool ​
​  , fileExecutable :: ​ Bool ​
​  } ​ deriving ​ ​ Show ​

This record will hold all of the basic information about our file that we want to display in the status bar. You’ll notice that we’re not including the current or total page count. By omitting those fields, we can calculate a single FileInfo for each file that we’re looking at, without having to regenerate a new value for each page.

Next, let’s write a function to create a new FileInfo value. We’ll call the function fileInfo . Let’s look at the implementation and then step through what it’s doing:

​  fileInfo :: ​ FilePath ​ -> ​ IO ​ ​ FileInfo ​
​  fileInfo filePath =
​  ​ Directory ​.getPermissions filePath >>= ​ \ ​perms ->
​  ​ Directory ​.getModificationTime filePath >>= ​ \ ​mtime ->
​  ​ BS ​.readFile filePath >>= ​ \ ​contents ->
​  ​ let ​ size = ​ BS ​.length contents
​  ​ in ​ return ​ FileInfo ​
​  { filePath = filePath
​  , fileSize = size
​  , fileMTime = mtime
​  , fileReadable = ​ Directory ​.readable perms
​  , fileWriteable = ​ Directory ​.writable perms
​  , fileExecutable = ​ Directory ​.executable perms
​  }

You’ll notice our function returns an IO action with a FileInfo , since all the things we’re doing to get information about the file are themselves IO actions. Most of the work we’re doing in this function is calling some IO actions and packing their results into a FileInfo record. We use getPermissions to get the permissions of the file, and getModificationTime to get the time the file was last changed. There isn’t an easy cross-platform way to look up the size of a file without reading it, but we can read the contents into a ByteString and then look at the length of the ByteString to get the size of the file. We’re using ByteString here instead of Text because we are specifically interested in the number of bytes in the file. If we used Text here we’d get the number of characters , which could be a lot smaller than the number of bytes, especially if we were dealing with text in a language that typically requires more than a single byte to represent a character. The last thing we do is to use the helper functions readable , writable , and executable to get the specific capabilities out of the Permissions type that is returned from getPermissions .

We can start manually testing our code now by calling fileInfo on different paths. Let’s run through a couple of examples:

​  λ fileInfo "HCat.hs"
​  FileInfo { filePath = "HCat.hs"
​  , fileSize = 17033
​  , fileMTime = 2022-01-24 05:09:57.532796141 UTC
​  , fileReadable = True
​  , fileWriteable = True
​  , fileExecutable = False
​  }
​  λ fileInfo "../hcat.cabal"
​  FileInfo { filePath = "../hcat.cabal"
​  , fileSize = 731
​  , fileMTime = 2022-01-24 04:20:48.234890708 UTC
​  , fileReadable = True
​  , fileWriteable = True
​  , fileExecutable = False
​  }

This function is serving its purpose of getting information about the contents of a file, but the way it’s being displayed in ghci isn’t going to work for us if we want to show a status line. For one thing, the formatting is all wrong to fit onto a single line. For another, we are missing the current page that we’re viewing and the overall page count, both key pieces of information we’ll want to display on the status line.

Formatting the Status Line

For each page of our file output, we’d like to create a status line at the bottom of the screen that shows some information from our FileInfo record, plus the current and total page count. The status line also needs to be formatted to take up only the amount of space available in a single row of text no matter how wide or small the user’s terminal is.

To handle this, let’s add a new function that will take a FileInfo along with a terminal width, total page count, and the current page. We’ll return a new Text value that contains all the status information. Let’s call our function formatFileInfo :

​  formatFileInfo :: ​ FileInfo ​ -> ​ Int ​ -> ​ Int ​ -> ​ Int ​ -> ​ Text ​.​ Text ​

Since we need to access all of the fields in our FileInfo record, we’ll use the RecordWildCards extension to create bindings for all of them automatically:

​  formatFileInfo ​ FileInfo ​{..} maxWidth totalPages currentPage =

We’ll use the printf function from the Text.Printf module in base to format our actual status line string. Let’s start there and define all the fields we want to show, and then work backwards and define them one at a time:

​  statusLine = ​ Text ​.pack $
​  printf
​  ​ "%s | permissions: %s | %d bytes | modified: %s | page: %d of %d" ​
​  filePath
​  permissionString
​  fileSize
​  timestamp
​  currentPage
​  totalPages

If you’ve used printf style functions in other languages, the syntax here might look familiar to you. The printf function takes a format string that uses special formatting symbols to represent values in a formatted string. You can find a comprehensive list of the format specifiers in the Haddock documentation. [16] In our status line we’re using %s , which is a placeholder for a String , and %d , which is a placeholder for an Integral value, in our case Int . After the format string we provide a list of values that will be used to fill in the format specifiers in the order that they appear.

Several of these fields are freebies. The filePath and fileSize fields are taken directly from our FileInfo record, and both currentPage and totalPages are being passed into the function. That means we need to work backwards to define both permissionString and timestamp .

Getting a value for permissionString is just a matter of a few if expressions:

​  permissionString =
​  [ ​ if ​ fileReadable ​ then ​ ​ 'r' ​ ​ else ​ ​ '-' ​
​  , ​ if ​ fileWriteable ​ then ​ ​ 'w' ​ ​ else ​ ​ '-' ​
​  , ​ if ​ fileExecutable ​ then ​ ​ 'x' ​ ​ else ​ ​ '-' ​ ]

If you find this confusing, remember that a String is just a list of Char values.

The next field we need to prepare is timestamp . This is going to be a human-readable timestamp based on the modification time that’s stored in our FileInfo . We’d like to show the timestamp in YYYY-MM-DD HH:MM:SS format. To do that we’ll use the formatTime function from the Data.Time.Format module in the time package. The formatTime takes a format string, a locale, and a UTCTime value and returns a human-readable timestamp. Like printf , the format string we pass to formatTime uses percent signs to indicate different kinds of values. You can look at the full list in the Haddock documentation. [17] We’ll use %F %T as our format string. This will give us our desired YYYY-MM-DD HH:MM:SS formatted timestamp:

​  timestamp =
​  ​ TimeFormat ​.formatTime ​ TimeFormat ​.defaultTimeLocale ​ "%F %T" ​ fileMTime

With these two values, we can generate a status line. Let’s take a look in ghci to see how our status line will look:

​  ​ λ ​ info <- fileInfo ​ "./ex" ​
​  ​ λ ​ ​ TextIO ​.putStrLn $ formatFileInfo info 100 5 2
​  ./ex|permissions: r-x|5 bytes|modified: 1970-01-01 00:00:01|page: 2 ​ of ​ 5

This isn’t too bad, it gives us a lot of information in a pretty readable format. There are a couple of changes we still should make: first, the status line could potentially be wider than the size of the terminal that we are writing to. In this case, we should truncate the status line so that we don’t accidentally cause word wrapping. Second, we should do something to make the status line more visually distinctive so that it’s easy for the user to tell the difference between the status bar and the rest of the text.

Let’s start by truncating the text in the status bar if it’s too long. Here’s the algorithm that we’ll use:

  • If the terminal is three or fewer characters wide, don’t display a status line at all.

  • If the length of the status line text is not longer than the width of the display, show the text unmodified.

  • If the length of the status line is longer than the display, replace the last three characters in the status line with ellipses.

This algorithm translates pretty naturally to code:

​  truncateStatus statusLine
​  | maxWidth <= 3 = ​ "" ​
​  | ​ Text ​.length statusLine > maxWidth =
​  ​ Text ​.take (maxWidth - 3) statusLine <> ​ "..." ​
​  | otherwise = statusLine

Finally, we can decorate our text to make the status line more visually distinctive. One way we can do that is to once again use ANSI terminal escape sequences to invert the colors of the text. As before, feel free to copy the literal escape codes from the example:

​  invertText inputStr =
​  ​ let ​
​  reverseVideo = ​ " ​​ \^[ ​​ [7m" ​
​  resetVideo = ​ " ​​ \^[ ​​ [0m" ​
​  ​ in ​ reverseVideo <> inputStr <> resetVideo

Now that we can truncate and highlight the status bar, we just need to call those functions on our printf formatted string. The final version of formatFileInfo is:

​  formatFileInfo :: ​ FileInfo ​ -> ​ Int ​ -> ​ Int ​ -> ​ Int ​ -> ​ Text ​.​ Text ​
​  formatFileInfo ​ FileInfo ​{..} maxWidth totalPages currentPage =
​  ​ let ​
​  timestamp =
​  ​ TimeFormat ​.formatTime ​ TimeFormat ​.defaultTimeLocale ​ "%F %T" ​ fileMTime
​  permissionString =
​  [ ​ if ​ fileReadable ​ then ​ ​ 'r' ​ ​ else ​ ​ '-' ​
​  , ​ if ​ fileWriteable ​ then ​ ​ 'w' ​ ​ else ​ ​ '-' ​
​  , ​ if ​ fileExecutable ​ then ​ ​ 'x' ​ ​ else ​ ​ '-' ​ ]
​  statusLine = ​ Text ​.pack $
​  printf
​  ​ "%s | permissions: %s | %d bytes | modified: %s | page: %d of %d" ​
​  filePath
​  permissionString
​  fileSize
​  timestamp
​  currentPage
​  totalPages
​  ​ in ​ invertText (truncateStatus statusLine)
​  ​ where ​
​  invertText inputStr =
​  ​ let ​
​  reverseVideo = ​ " ​​ \^[ ​​ [7m" ​
​  resetVideo = ​ " ​​ \^[ ​​ [0m" ​
​  ​ in ​ reverseVideo <> inputStr <> resetVideo
​  truncateStatus statusLine
​  | maxWidth <= 3 = ​ "" ​
​  | ​ Text ​.length statusLine > maxWidth =
​  ​ Text ​.take (maxWidth - 3) statusLine <> ​ "..." ​
​  | otherwise = statusLine

Improving Readability with Do Blocks

Now that we have a way to get information about a file and format it nicely, the next step in building our application will be to integrate our new fileInfo function into our pagination code. Before we move on to this next step though, we’re going to take a slight detour and look at some ways that we can refactor our code to be easier to read and write using a common Haskell feature called do notation.

So far in this chapter we’ve built up IO actions using functions like >>= and fmap that we learned about in the previous chapter. As our programs have gotten longer and more sophisticated, you might have thought that our applications have also grown less readable. If we look back at fileInfo as an example, you’ll notice that each time you add a new field to the overall collection of information, you are following the same pattern of adding a new function so that you can bind the result of an IO action:

​  fileInfo :: ​ FilePath ​ -> ​ IO ​ ​ FileInfo ​
​  fileInfo filePath =
​  ​ Directory ​.getPermissions filePath >>= ​ \ ​perms ->
​  ​ Directory ​.getModificationTime filePath >>= ​ \ ​mtime ->
​  ​ BS ​.readFile filePath >>= ​ \ ​contents ->
​  ​ let ​ size = ​ BS ​.length contents
​  ​ in ​ return ​ FileInfo ​
​  { filePath = filePath
​  , fileSize = size
​  , fileMTime = mtime
​  , fileReadable = ​ Directory ​.readable perms
​  , fileWriteable = ​ Directory ​.writable perms
​  , fileExecutable = ​ Directory ​.executable perms
​  }

For three values that works well enough, but you can easily imagine how adding a few more items to the file info would start to make the code completely unreadable. As the procedural shells of our application start to do more, we need a better way to write the code. In fact, you might find yourself writing procedural style IO-heavy code and wishing that Haskell was a more procedural language, or at least supported the syntax of common imperative programming languages.

Haskell gives us the ability to do just that with do notation . do notation allows us to use the do keyword to write imperative style blocks called “do blocks”. The do notation is syntactic sugar . It doesn’t add new capabilities to the language, but it gives you a nicer and more convenient way to write some types of code. In fact, the Haskell compiler will automatically translate imperative style code inside of do blocks into code that uses (>>=) . There’s nothing that you can write with do notation that you can’t write by calling >>= , but the syntax of do blocks can be quite a bit nicer in some cases.

The quickest way to understand what a do block is doing is with a short example. Let’s write a small function that uses do notation, and then we’ll desugar it into the >>= style that you’ve been using throughout this chapter. We’ll create a small function that will read the contents of two files, and then write the lines back out to a third file, interleaving the lines from the first two:

​  interleaveLines :: ​ String ​ -> ​ String ​ -> ​ String ​
​  interleaveLines a b =
​  unlines . concat . ​ Data ​.​ List ​.transpose $ [lines a, lines b]
​  
​  interleaveFiles :: ​ FilePath ​ -> ​ FilePath ​ -> ​ FilePath ​ -> ​ IO ​ ​ String ​
​  interleaveFiles file1 file2 outFile = ​ do ​
​  content1 <- readFile file1
​  content2 <- readFile file2
​  putStrLn ​ "I've read two files" ​
​  ​ let ​ content3 = interleaveLines content1 content2
​  writeFile outFile content3
​  return content3

Even without digging into the details of do notation, you should be able to follow what’s going on in the interleaveFiles function. The most obvious difference in this code from code that we’ve been writing is the use of <- for variable assignment. You might also have noticed that we have statements like putStrLn and writeFile that just appear like they would in a procedural program. Finally, you might notice the use of let without a corresponding in when we say let content3 = interleaveLines content1 content2 .

So why the new type of assignment, and why two different styles of assignment? Before we dig into that, let’s look at a desugared version of the same function:

​  bindInterleave :: ​ FilePath ​ -> ​ FilePath ​ -> ​ FilePath ​ -> ​ IO ​ ​ String ​
​  bindInterleave file1 file2 outFile =
​  readFile file1
​  >>= ​ \ ​content1 ->
​  readFile file2
​  >>= ​ \ ​content2 -> putStrLn ​ "I've read two files" ​
​  >>= ​ \ ​​ _ ​ ->
​  ​ let ​ content3 = interleaveLines content1 content2
​  ​ in ​ writeFile outFile content3
​  >> return content3

Comparing these two versions of the function, we can see the syntactic sugar of the do notation is just wrapping the pattern of using bind with anonymous functions. In do blocks we use <- style assignment to bind a variable. Saying foo <- bar inside of a do block is the same as saying bar >>= \foo -> ... in normal Haskell notation.

In simple cases like this, do blocks can slightly improve the readability of our program by removing the >>= \var -> from each line of our code, allowing us to focus on the important parts of our application.

do blocks can also be nested, allowing us to create more complex applications where using bind notation would quickly get unwieldy.

Refactoring fileInfo

Now that we know about do blocks, we can clean up some of our code. Let’s start by looking at how we can refactor our fileInfo function to use do notation. We will start by mechanically replacing the anonymous functions with do bindings:

​  fileInfo :: ​ FilePath ​ -> ​ IO ​ ​ FileInfo ​
​  fileInfo filePath = ​ do ​
​  perms <- ​ Directory ​.getPermissions filePath
​  mtime <- ​ Directory ​.getModificationTime filePath
​  contents <- ​ BS ​.readFile filePath
​  ​ let ​ size = ​ BS ​.length contents
​  return ​ FileInfo ​
​  { filePath = filePath
​  , fileSize = size
​  , fileMTime = mtime
​  , fileReadable = ​ Directory ​.readable perms
​  , fileWriteable = ​ Directory ​.writable perms
​  , fileExecutable = ​ Directory ​.executable perms
​  }

This version of the code is much more readable. We’ve removed a large amount of indentation, and it’s easier to follow the important parts of the program since we’ve removed some extra syntax that made it a little harder to follow along with the important parts of the program.

One additional small change we can make is to combine reading the contents of the file and calculating its size, turning that into a single expression:

​  size <- ​ BS ​.length <$> ​ BS ​.readFile filePath

Using (<$>) this way is a common pattern that you’ll see frequently throughout this book and in production Haskell code.

This style of do notation that we’ve just used follows the usual Haskell convention of using significant whitespace to manage the structure of our program. All of the code inside of the do block is indented by a consistent number of spaces to group the expressions together. If we are writing several let bindings inside of a do block, we need to add an additional level of indentation to differentiate the let bindings from the do expressions:

​  letBindingDo :: ​ IO ​ (​ Int ​,​ Int ​,​ Int ​)
​  letBindingDo = ​ do ​
​  ​ let ​
​  a = 1
​  b = 2
​  c = 3
​  return (a,b,c)

Uncommonly, you might also see code that uses an alternative form of do notation that makes use of braces and semicolons instead of significant whitespace. This style of code is equivalent to the more usual style with significant whitespace, but it more closely resembles imperative code in a C-family language. As an example:

​  fileInfo :: ​ FilePath ​ -> ​ IO ​ ​ FileInfo ​
​  fileInfo filePath = ​ do ​
​  { perms <- ​ Directory ​.getPermissions filePath;
​  mtime <- ​ Directory ​.getModificationTime filePath;
​  size <- ​ BS ​.length <$> ​ BS ​.readFile filePath;
​  return ​ FileInfo ​
​  { filePath = filePath
​  , fileSize = size
​  , fileMTime = mtime
​  , fileReadable = ​ Directory ​.readable perms
​  , fileWriteable = ​ Directory ​.writable perms
​  , fileExecutable = ​ Directory ​.executable perms
​  };
​  }

In this style of notation, each expression is terminated with a trailing semicolon, and the entire do block is wrapped in braces.

Let expressions are also wrapped in braces:

​  letBindingBrackets :: ​ IO ​ (​ Int ​,​ Int ​,​ Int ​)
​  letBindingBrackets = ​ do ​
​  {
​  ​ let ​ {
​  a = 1;
​  b = 2;
​  c = 3;
​  };
​  return (a,b,c);
​  }

The use of braces and semicolons here eliminates the need for significant whitespace, although whitespace for the sake of formatting and making the code more readable is still recommended.

This style of do notation is rarely used, and throughout the rest of the book we’ll use the much more common significant whitespace style of code. This bracket-and-semicolon style is mentioned here because you may run across it in some popular papers and other pieces of documentation, and it does occasionally show up in some open source projects.

In the next section, we’ll finish up our application by putting all of our new functions together and using do notation to refactor runHCat . As you’re working through that last section, keep an eye out for other refactoring opportunities.