When we see the behavior of our program, our first instinct might be to look at how we’re recording the time spent in the histogram code—perhaps we’ve accidentally introduced a bug that causes us to not record times correctly? The fact that we have more reasonable values for our other calls is evidence against this though.

The problem we’ve run into is writeIORef handles the value it’s writing into the reference lazily. Although we’re always writing something into the reference immediately each time we’re calling writeIORef , the value we’re writing isn’t our newly updated histogram. Instead, we’re writing a thunk that contains the computation that will give us an updated histogram when we need it. Creating a thunk is fast enough that at the millisecond-resolution we’re rounding down to zero each time we call the function. It’s only once we try to actually look at the values in the map that we finally have to compute them.

One way that we could work around this is by adding a new timer around the code that we’re using to actually print out the histogram:

​  timeFunction metrics ​ "print histogram" ​ $ ​ do ​
​  histogram <- readIORef histogramRef
​  putStrLn ​ "Histogram Data:" ​
​  for_ (​ Map ​.toList histogram) $ ​ \ ​(letter, count) ->
​  putStrLn $ printf ​ " %c: %d" ​ letter count

Now when we run our program, we’ll see that while our histogram construction continues to not take any time, we can track the amount of time it takes to evaluate the histogram so that we can print it out:

​  successes: 20611
​  failures: 43
​  Time spent in "TextIO.readFile": 25
​  Time spent in "histogram": 0
​  Time spent in "print histogram": 5788
​  Time spent in "traverseSubdirectory": 3850
​  Time spent in "wordcount": 0

Unfortunately, the problem here goes deeper than just not having a correct accounting of the time that we spent computing the histogram. We’ve also introduced a type of problem known as a space leak .

Understanding Space Leaks

Space leaks are a type of error we can run into in Haskell when laziness starts to work against us, and we start to see a large number of thunks accumulated that are not evaluated. This can manifest in several different ways, including causing our programs to use too much memory, to have poor or unpredictable performance patterns, or more rarely, to crash at runtime with a stack overflow. What we’ve seen so far when trying to run our directory traversal program is an example of how space leaks can make themselves known when the performance isn’t what we expect. Specifically, we would expect generating the character histogram to take a lot of time, but in fact it takes almost no time at all.

The idea that a space leak can show up as a problem with unexpected performance characteristics can be counterintuitive, but as we look into what happened with our program in this case it will start to be clear just why the unusual performance was an indicator of a space leak.

Before we dive into the code and start working on a fix, let’s get some hard data. When we suspect that we have a space leak, it can be helpful to look at information about the amount of memory we’re allocating, and what the garbage collector is doing. Even if the data doesn’t initially tell us where to look for the error, it gives us a baseline to measure against, so we can see if the changes we’re making are actually having a positive impact on the runtime characteristics of the application.

We can’t get the kind of information that we need from ghci , so let’s create a new file and make sure that we have main defined so that we can compile the application as a stand-alone program:

​  ​ import ​ ​ System.Environment ​ (​ getArgs ​)
​  
​  main :: ​ IO ​ ()
​  main = getArgs >>= directorySummaryWithMetrics . head

If you haven’t already created a new cabal project for this program, you can take a minute to do so now, or you can compile the program directly with ghc . In either case, make sure that you’ve enabled -O2 level optimizations. GHC is able to do a number of optimizations, and we want to avoid spending too much time chasing down optimizations that the compile will take care of for us anyway.

​  $ ghc -O2 DirectorySummary.hs -o DirectorySummary

Once you’ve built the program, we want to run it, but instead of running the program like normal, we’re going to pass in some extra flags to the Haskell runtime so that we can ask it to collect some information about memory usage as our program is running. Flags like this that we use to control the way the Haskell runtime works, or to ask it for some extra information about our program, are called RTS flags . RTS flags are normal command line flags, but we need to differentiate between options we want to pass to the Haskell runtime and the options that we want to pass to our program. To do so, we start by passing in the special +RTS argument. This argument will cause the runtime to interpret all the arguments that it sees as arguments to the runtime system, until it sees the -RTS argument. This lets us pass in as many arguments as we want to the runtime system without our application having to know about or handle them.

In our particular case, we only want to pass a single RTS flag, -s . This flag will ask the runtime to generate summary statistics about the memory utilization of our application:

​  $ ./DirectorySummary +RTS -s -RTS ./example-dir/

When you run the program with this RTS flag you’ll get all of the normal output you’d expect, and then at the end before your program exits you’ll see some output like this:

​  1,911,494,744 bytes allocated in the heap
​  44,005,608 bytes copied during GC
​  12,816,336 bytes maximum residency (10 sample(s))
​  6,051,224 bytes maximum slop
​  39 MiB total memory in use (3 MB lost due to fragmentation)
​  
​  Tot time (elapsed) Avg pause Max pause
​  Gen 0 1764 colls, 0 par 0.026s 0.026s 0.0000s 0.0004s
​  Gen 1 10 colls, 0 par 0.007s 0.007s 0.0007s 0.0012s
​  
​  INIT time 0.000s ( 0.000s elapsed)
​  MUT time 0.363s ( 0.363s elapsed)
​  GC time 0.033s ( 0.033s elapsed)
​  EXIT time 0.000s ( 0.000s elapsed)
​  Total time 0.396s ( 0.396s elapsed)
​  
​  %GC time 0.0% (0.0% elapsed)
​  
​  Alloc rate 5,262,713,737 bytes per MUT second
​  
​  Productivity 91.7% of total user, 91.6% of total elapsed

There’s a lot of information here that we won’t cover in this book, but you can refer to the GHC User Guide [18] for comprehensive documentation on the meaning of all these fields. For the moment we’re going to focus on the maximum residency field, which tells us the amount of memory that our program was actually using at its peak.

If you look at the total size, in bytes, of all of the data in your example directory, you’ll notice that it is fairly similar to the total residency of our application. For example, if we look at the total number of bytes in all of the files in example-dir , we’ll see that they total about 12.3 megabytes, which is a little bit less than the total residency of our application, but suspiciously close:

​  $ du -s -B 1 ./example-dir/
​  12365824 ./example-dir/

The fact that our maximum residency is so similar to the size of all of the files in our directory can start to give us a hint about what has happened. When we read the contents of a file in so that we can calculate the character histogram, we’re not freeing that data right away. Instead, we’re keeping all of the files in memory. The fact that we see observable delay before the histogram is printed out on the screen gives us a bit more information: we’re reading all of the files, but not actually calculating the histogram until we’re ready to print it out. It seems like, in this case, laziness might be causing trouble. Let’s take a look at what’s going on, and in the next section, we’ll look at a few ways to address this particular type of problem.

Laziness, Strictness, and IO

The root cause of the problem we’ve run into is that we’re mixing lazy and strict values, and it’s causing our program to act unexpectedly. Let’s take a look at our histogram calculation code again for reference:

​  traverseDirectory metrics root $ ​ \ ​file -> ​ do ​
​  contents <- timeFunction metrics ​ "TextIO.readFile" ​ $
​  ​ TextIO ​.readFile file
​  
​  ​ -- Omitting some things here ​
​  
​  timeFunction metrics ​ "histogram" ​ $ ​ do ​
​  oldHistogram <- readIORef histogramRef
​  ​ let ​
​  addCharToHistogram histogram letter =
​  ​ Map ​.insertWith (+) letter 1 histogram
​  newHistogram = ​ Text ​.foldl' addCharToHistogram oldHistogram contents
​  writeIORef histogramRef newHistogram

The first thing that we need to keep in mind here is that TextIO.readFile is a strict function. Whenever we call it, we’re going to get the entire contents of the file brought into memory. Similarly, combining IO actions using (>>=) or in a do block is always strict. As we’re traversing the directories, we’re always going to read the contents of the file before we write an update to histogramRef or before we move on and read the contents of the next file.

The second thing that we have to keep in mind is that Haskell is lazy by default, so all of the things that don’t have to be strict are going to generate thunks instead of strictly evaluated values. That means that whenever we create a new histogram, we’re not really computing the value of a brand new histogram, we’re just creating a new thunk that can compute a histogram when a histogram is needed:

​  newHistogram = ​ Text ​.foldl' addCharToHistogram oldHistogram contents

Perhaps unintuitively, a value to an IORef is not strict. When we call writeIORef , we’re not forcing the value newHistogram to be computed, instead we just write the thunk into the reference.

The last thing to keep in mind is a thunk keeps around references to everything that is needed to compute a value. In this case, each thunk we’re writing into the reference is keeping a reference to the previous thunk that was stored in the IORef and a reference to the contents of the text file we’ve just read. Since we have a reference to the contents of the text file, that data can’t be garbage collected. Since we have a reference to the previous thunk, which in turn has a reference to the contents of its text file, that text file can’t be garbage collected either. By the time we’ve finished traversing the directory, we have a chain of thunks that are keeping open references to all the data from all the files we’ve opened—plus a bit of overhead for the other calculations we need to do.

The solution to this problem is to reduce the amount of laziness in our program. If we can compute the value of the histogram thunk immediately, then we will no longer need to keep references to the contents of the file or the previous thunk, and the garbage collector can clean everything up for us. This is a common enough problem in Haskell programs that we have not just one, but several different approaches we can use to solve the problem. Before we dive into reviewing the options though, let’s take a slight detour to understand exactly what we mean when we’re talking about strictness, laziness, and what it means to evaluate an expression. This will give us the tools to better understand when and how to introduce strictness, and also make sure we’re better prepared to avoid this type of space leak in the future.

Thunks and Evaluation in Haskell Programs

Much earlier in this book you learned about how thunks can enable us to do creative things like creating infinitely linked lists , and more recently, you saw an example of how a thunk being created unexpectedly created a space leak that caused us to use far more memory than necessary when we were counting the frequency of characters in a directory full of files. Most of the time as we are writing Haskell, we don’t have to think too much about the details of what thunks are being created and when, and thankfully, most of the time if we do think about them it’s because they are helping us write things that might be harder to express in a strict language. Sometimes though, laziness causes problems, and when that happens we need to understand a little bit more about how our programs are actually being run. In this case, that means we need to know a bit more about what thunks are and how they work so that we can fix our space leak and ensure we don’t have similar problems in the future.

So, what is a thunk? Up until now, we’ve used a pretty simple mental model of a thunk as a value that hasn’t yet been computed. This is right, but there’s a little bit more to it than is apparent from that explanation. To better explore what thunks are and how they impact the way our programs are run, let’s work through an example. Our example will recreate the same space leak caused by writing into an IORef that we encountered when we were working with our timer function, but in a much smaller and simpler program so that we can avoid too many extraneous details.

Our example program will have two functions. Our first function, characterCounter , will read the contents of a file and return an IO action that will give us a way to count the number of occurrences of some character or substring inside of the contents of the file:

​  characterCounter :: ​ FilePath ​ -> ​ IO ​ (​ Text ​.​ Text ​ -> ​ Int ​)
​  characterCounter filePath = ​ do ​
​  haystack <- ​ TextIO ​.readFile filePath
​  pure $ ​ \ ​needle ->
​  ​ Text ​.count needle haystack
​  + ​ Text ​.count needle (​ Text ​.pack filePath)

Next, we’d like to call characterCounter . Our second function, someExample , is going to do some work to figure out what path we should open, and then count the number of spaces in the file at that path and write the count into an IORef :

​  someExample :: ​ FilePath ​ -> ​ IO ​ (​ IORef ​ ​ Int ​)
​  someExample path = ​ do ​
​  countRef <- newIORef 0
​  ​ let ​
​  somePath = complicatedPathFinding path
​  counter <- characterCounter somePath
​  writeIORef countRef (counter ​ " " ​)
​  pure countRef
​  ​ where ​
​  ​ -- You can use any function you'd like here ​
​  complicatedPathFinding = id

The first thing to think about when we’re dealing with performance problems like space leaks or unexpected slowness in a Haskell program should be memory allocation. Allocations and freeing up memory are core to the way that Haskell programs are run. Space leaks, unexpectedly slow programs, stack overflows, and bugs like exhausting the number of file descriptors are all examples of problems that are closely tied to the way things are allocated.

Most of the things we’re dealing with when we write programs end up existing at runtime as heap objects . Heap objects are how the Haskell runtime allocates memory for everything from literal values like numbers, to values we’ve created using value constructors, to functions and thunks. Understanding how heap objects work is the first step to understanding more about how thunks and laziness works in Haskell.

At a high level, all of the heap objects that we create in our program have the same structure: a header that contains some metadata about what kind of heap object we’re dealing with, followed by some additional information that varies depending on the type of heap object, and finally, a payload that contains data, or references to data, that is needed by the heap object.

Some of the most common types of heap objects we deal with in most Haskell programs are called thunks . The GHC runtime keeps track of several different kinds of thunks internally, but for our purposes we don’t need to differentiate between them, and for the sake of simplicity we’ll collectively refer to all of them as “a thunk.”

When a thunk is first created, it’s going to have three different sets of data. First, the header will tell the GHC runtime what kind of thunk it’s dealing with, and will have all of the other housekeeping information that all heap objects need. The next section contains the code that needs to run so that the thunk can be evaluated when and if the result of the thunk is needed. Finally, the payload section keeps around a table of references to the values that that the code section needs to refer to in order to calculate a value.

To help make this a bit more concrete, let’s look at our example code and think about what happens when we define somePath . When we define somePath in our let binding, the runtime is going to manage that by creating a new thunk:

​  ​ let ​
​  somePath = complicatedPathFinding path

images/somePathThunk.png

The header data for our new heap object will have a type that tells the runtime we’re dealing with a thunk, and the code section will tell us we need to call a function named complicatedPathFinding , applying a value to it named path . A reference to the actual complicatedPathFinding function and a reference to the string we’re applying are stored in the payload so that we can reference them if we need to run the code to get a value for the thunk.

This thunk by itself isn’t doing much, so let’s move on to the next thing we’re defining: our character counter function, named counter . We’re getting the function we’re binding counter to by running an IO action. IO actions can be stored in thunks just like everything else, but since the implementation details of IO can be a little tricky and aren’t relevant to the problem at hand, we’re going to skip over that and instead focus on what’s happening inside of characterCounter when it gets evaluated.

The first thing we do inside of characterCounter is read the contents of the file using the path that we passed in. Since the value we applied to this function is the somePath thunk from earlier, we’re finally going to need to calculate a value for our path.

When we need the value of a thunk, the first thing that happens is we run the code in the code section of the heap object. Generally, that will result in some new value being created and stored as a brand new heap object. That new value is the actual value of our thunk. Once that’s done, we need a way to get to the answer from the thunk, so the value of the thunk is updated. Any references we were holding onto in the payload section can be released, and thunk is updated with an indirection . The indirection tells us where to look for the value we calculated from the thunk. All this happens transparently and automatically the first time we try to read the value of the thunk, and all we see is the final result: the path to the file we want to open.

With our path available, we can read the contents of the file; again we’ll skip over the details of IO for now. The last thing we do is to return a new function. Functions, like thunks, are allocated as heap objects, and just like a thunk, a function will store references to anything it needs to compute a value in the payload section of the heap object. Let’s take another look at the function we’re returning so we can figure out what references it would need to have in its payload:

​  ​ \ ​needle ->
​  ​ Text ​.count needle haystack
​  + ​ Text ​.count needle (​ Text ​.pack filePath)

There are quite a few different values that we’re referencing in this function. First, we’re calling the Prelude function (+) , and we’re calling both count and pack from the Data.Text module. Keeping references to top-level functions like this doesn’t typically have much of a performance impact, since the same values can be referenced by everything in the program that needs to refer to them. In addition to the top-level functions that we’re referencing, the body of our function is also referencing the value of its parameter, needle . Since this is a parameter to the function, and not a value that’s referencing some existing heap object, we don’t actually need to store anything for that now. The last two values we’re referencing are filePath and haystack . These are both part of the function’s closure . That’s a fancy way to say that they are values that are in scope when we’re defining this function, but they aren’t top-level values or functions that can be shared across the entire program.

What we’ve just described is the information stored in the heap object for a function, but like anything else we’re not going to start by generating a function. Instead, we’ll return a thunk that when evaluated will compute a function. In practice, thunks and function heap objects are quite similar though, and all the values we had to store in the function object’s payload will also be in the thunk’s payload.

The last thing we do in our example is call ‘writeIORef‘ to update our counter. The value that we pass to it is yet another thunk. This thunk contains the thunk that we created that will eventually evaluate to the counting function we returned from characterCounter , along with the parameter we want to pass to that function. Just as in our earlier example, we’ve created a small space leak here. The problem once again is that when we write the thunk into our IO reference, we’re keeping around a reference to the contents of our text file, preventing that data from being garbage collected. Now that we understand a bit more about how thunks and heap objects work, we can start to formulate a solution to this type of problem.

images/thunks.png

The crux of the problem in both our original code and our smaller example here is that when we write a value into our reference, what we’re writing is a thunk that contains references to all of the data in its closure, including the contents of our file. If we could force the thunk to get evaluated, we might be able to let the garbage collector free the memory that we’ve allocated to hold the contents of our file, but only if we evaluate the thunk in the right way.

Right now we have a thunk that contains this code:

​  (counter ​ ' ' ​)

If we could naively evaluate this thunk, we’d replace the code in this thunk with a reference to a computed value that calls counter , which is just another thunk. Even if we evaluated the counter thunk, we’d still be left with a function heap object that contains the file contents in its closure. We need a way to get our thunk evaluated enough that we don’t have to hold this kind of information anymore. To do that, we need to evaluate the value into weak head normal form .

A value in weak head normal form has to follow some very particular rules. First, it can’t be a thunk, although it can have references to other thunks. Second, the heap object has to be either a function or a constructor. Finally, if the object is a function, we have to have applied any arguments to it that we could have applied.

Let’s look at some examples. First, we’ll look at some value constructors that are in weak head normal form:

​  100
​  ​ 'H' ​ : <thunk>
​  ​ \ ​x -> x + 1
​  ​ Just ​ <thunk>

In these examples, 100 is in weak head normal form because a numeric literal is a value constructor for a numeric type. The list ’H’ : <thunk> is in weak head normal form because the heap object contains a value constructor for a list, (:) . Even though the tail of the list is a thunk, the expression is in weak head normal form because the actual heap object is a data constructor. Next, the function \x -> x + 1 is in weak head normal form because we don’t have any values that we can apply to the function. Finally, Just <thunk> is in weak head normal form because it, like our list, is a value constructor, even though the actual value is a thunk.

On the other hand, we can also write some expressions that aren’t in weak head normal form. Let’s see some examples of those:

​  <thunk>
​  (​ \ ​x -> x + 1) 5
​  5 + 1

The first example here is an unevaluated thunk. Even if the thunk would be evaluated to a function or value constructor, the thunk itself is neither, and so it’s not in weak head normal form. In our second example, the expression (\x -> x + 1) 5 isn’t in weak head normal form either. In this case, we have a value, 5 , that we could apply to the function. If we did apply 5 to our function, we’d get to our final example, 5 + 1 . This function is also not in weak head normal form, since (+) is a function. This is more obvious if we rewrite 5 + 1 using prefix notation, (+) 5 1 . Since we have parameters we haven’t yet applied, it isn’t in weak head normal form.

Let’s work through turning our thunk representing (counter " ") into weak head normal form manually to see what we’d get by doing the reduction.

First, let’s expand counter , replacing it with its definition:

​  (​ \ ​needle ->
​  ​ Text ​.count needle haystack
​  + ​ Text ​.count needle (​ Text ​.pack filePath)) ​ " " ​

We can see right away that before we can have a value in weak head normal form we’ll need to apply our parameter. That gives us this new expression:

​  ​ Text ​.count ​ " " ​ haystack + ​ Text ​.count ​ " " ​ (​ Text ​.pack filePath)

Next we have several other functions that haven’t had all of their arguments applied. If we take yet another reduction that next step, we’d end up with something like this:

​  ​ Text ​.count ​ " " ​ ​ "haystack contents" ​ + ​ Text ​.count ​ " " ​ ​ "/path/to/haystack" ​

We still need to apply our values to Text.count on both sides of our expression, which gives us: 1 + 0 . That’s still not in weak head normal form, so we need to apply our parameters one more time, and we’re left with the value constructor 1 .

By reducing the expression down to weak head normal form, we’ve removed any heap objects that need to hold references to the contents of the file we’ve opened, so that it can be safely garbage collected. We’ve also freed up several intermediate heap objects and removed a lot of indirection, potentially giving ourselves better performance. Of course, if we weren’t ever going to use the results of our count, we might have done all of that work for nothing, so we wouldn’t want to go reducing things for no reason.

The main problem we have left is that we’ve manually reduced our value down to weak head normal form as an example, but we need a way to tell the compiler to do it for us. Thankfully, we have a few ways to do it.

The first option that we have, and in this particular case the easiest, is to use a strict function to write data into our IORef . Some functions, like modifyIORef , offer strict versions that will reduce one of their arguments to weak head normal form when they are called. In this case, we can use the strict modifyIORef’ to ensure our counter is reduced before it’s written.

In this particular example, turning our lazy call to writeIORef into a strict call to modifyIORef’ is a single line change that can drastically improve the performance of our program:

​  modifyIORef' countRef (const $ counter ​ " " ​)

If we apply the same change to our metrics application, we’ll also see a drastic reduction in the amount of memory being used. For example, by changing our timer function slightly, we can reduce both the total amount of memory in use and the maximum residency significantly:

​  timeFunction metrics ​ "histogram" ​ $ ​ do ​
​  oldHistogram <- readIORef histogramRef
​  ​ let ​
​  addCharToHistogram histogram letter =
​  ​ Map ​.insertWith (+) letter 1 histogram
​  newHistogram = ​ Text ​.foldl' addCharToHistogram oldHistogram contents
​  modifyIORef' histogramRef (const newHistogram)

If we run our example program from earlier with the single small change, we can see that we’ve significantly reduced the memory usage of our application:

​  1,999,084,672 bytes allocated in the heap
​  46,426,400 bytes copied during GC
​  2,210,696 bytes maximum residency (26 sample(s))
​  513,144 bytes maximum slop
​  8 MiB total memory in use (0 MB lost due to fragmentation)
​  
​  Tot time (elapsed) Avg pause Max pause
​  Gen 0 1828 colls, 0 par 0.023s 0.023s 0.0000s 0.0003s
​  Gen 1 26 colls, 0 par 0.011s 0.011s 0.0004s 0.0005s
​  
​  INIT time 0.000s ( 0.000s elapsed)
​  MUT time 0.422s ( 0.421s elapsed)
​  GC time 0.034s ( 0.034s elapsed)
​  EXIT time 0.000s ( 0.000s elapsed)
​  Total time 0.456s ( 0.456s elapsed)
​  
​  %GC time 0.0% (0.0% elapsed)
​  
​  Alloc rate 4,739,720,785 bytes per MUT second
​  
​  Productivity 92.6% of total user, 92.5% of total elapsed

Unfortunately, not all functions offer a strict version that works for us out of the box. If we need to implement strictness ourselves, there are several helper functions that are available in base and in some libraries. Most of these use one of two basic approaches to making data strict: calling the seq function, or using a popular GHC extension, BangPatterns .

BangPatterns

| images/aside-icons/info.png | The BangPatterns extension has been available since GHC 6.8.1. It’s enabled by default in GHC2021 , but you’ll need to manually enable it in Haskell2010 . This is a safe extension and shouldn’t generally cause any changes to code that doesn’t directly use the feature. |

The seq function is available in Prelude. Its type is seq :: a -> b -> b , and its purpose is to ensure that its first argument is evaluated to weak head normal and to return its second argument. It’s typically used when you need to strictly evaluate an argument that you’ll pass into a function. For example, we could replace our call to modifyIORef’ with some code that uses seq directly instead:

​  newHistogram `seq` writeIORef histogramRef newHistogram

Here we have forced newHistogram to be reduced to weak head normal form before we pass it into writeIORef . In cases like this where the last parameter of a function is the one that we want to apply strictly, we can also use the strict function application operator from base, ($!) . This function works just like the regular ($) operator that you’re already familiar with, but it reduces its right-hand argument to weak head normal form before applying it to the function. For example, we can rewrite our somewhat verbose seq version much more tersely:

​  writeIORef histogramRef $! newHistogram

The use of the ! symbol in $! mirrors the last tool that we have for evaluating values to weak head normal form: using the BangPatterns extension. This extension allows us to add a strictness annotation by putting a ! symbol in front of let bindings and named parameters to ensure that they are evaluated to weak head normal form. Although they aren’t usually used this way, we can use a bang pattern to ensure that newHistogram is evaluated to weak head normal form:

​  ​ {-# LANGUAGE BangPatterns #-} ​
​  
​  ​ let ​
​  addCharToHistogram histogram letter =
​  ​ Map ​.insertWith (+) letter 1 histogram
​  !newHistogram = ​ Text ​.foldl' addCharToHistogram oldHistogram contents
​  writeIORef histogramRef newHistogram

More commonly, bang patterns are used with the parameters of functions to ensure one or more of the function’s arguments are evaluated strictly, or with the fields in records to ensure that the data in the record is always reduced to weak head normal form before being stored. For example, instead of using modifyIORef’ we could write our own writeIORef’ function that ensures that the value we are writing is strict:

​  writeIORef' :: ​ IORef ​ a -> a -> ​ IO ​ ()
​  writeIORef' ref !val = writeIORef ref val

By including the bang pattern on the val parameter, we ensure the argument will always be evaluated to weak head normal form whenever the result of the function is evaluated. Since writeIORef’ is an IO action that will generally be evaluated right away, we’ll immediately evaluate the histogram thunk before we write it into the references.

Using bang patterns in records and data constructors follows the same pattern. Imagine if, instead of writing the histogram as a number, we had defined a new data type to hold the histogram:

​  ​ data ​ ​ FileStats ​ = ​ FileStats ​ (​ Map ​.​ Map ​ ​ Char ​ ​ Int ​)

Let’s update the timer function of our code with the minimal changes required to use this new data type:

​  timeFunction metrics ​ "histogram" ​ $ ​ do ​
​  (​ FileStats ​ oldHistogram) <- readIORef histogramRef
​  ​ let ​
​  addCharToHistogram histogram letter =
​  ​ Map ​.insertWith (+) letter 1 histogram
​  newHistogram =
​  ​ FileStats ​ (​ Text ​.foldl' addCharToHistogram oldHistogram contents)
​  writeIORef' histogramRef newHistogram

Running this version of the code with summary metrics, you’ll notice we’ve regressed back to our original larger memory footprint, even though we are continuing to use our strict writeIORef’ function that was previously giving us substantial improvements. The problem is our implementation of writeIORef’ reduces its argument to weak head normal form. Now that we’re writing a FileStats value instead of a map into our reference, reducing the argument to weak head normal form means we’re only reducing the value down as far as the value constructor, and keeping the histogram calculation inside of a thunk. What we actually want is for the field of the record to be evaluated to weak head normal form when we construct the record.

Using BangPatterns we can add a strictness annotation to the types of fields in data types and records. Let’s rewrite FileStats to ensure that our histogram will always be evaluated to weak head normal form:

​  ​ data ​ ​ FileStats ​ = ​ FileStats ​ !(​ Map ​.​ Map ​ ​ Char ​ ​ Int ​)

If we’d used a record for FileStats the syntax would be similar:

​  ​ data ​ ​ FileStats ​ = ​ FileStats ​
​  { fileHistogram :: !(​ Map ​.​ Map ​ ​ Char ​ ​ Int ​)
​  }

With this small change, if we rebuild and re-run our program we can once again see that we’re back to the lower memory footprint that we had before we added the value constructor.