In Haskell, rather than storing a value that is directly mutable, we store an immutable reference to some data that we can change using the reference. There are several different types of mutable references that you can use, depending on the specific needs of your application. You’ll learn about several different types of references throughout this chapter, but for the moment we’ll focus on particular type of reference, the IORef .

A value with the type IORef a is a normal Haskell value that holds an immutable pointer to some internal data that is managed by the GHC runtime.

You can use an IORef like any other normal Haskell value. You can pass it into a function, return it, store it in a record, or capture the value in a closure. Creating a new IORef, or using one to read or write the value at the reference, is always an IO action. Let’s dive into some basics of how to use IORefs, and then we’ll move on to some ways that you can use IORefs in real-world applications.

Creating IORefs

You can create a new IORef a by calling newIORef from Data.IORef and giving it an initial value to store at your reference. In this example, we’ll create a new IORef that will hold an Int and initialize it to 0 :

​  ​ λ ​ ​ import ​ ​ Data.IORef ​
​  ​ λ ​ numRef <- newIORef @​ Int ​ 0

Since you need to initialize any newly created reference, there’s no chance of accidentally getting a null or uninitialized reference. If you have a reference that may not have a value, you can use a Maybe value, just like you would with a non-reference value.

​  ​ λ ​ optionalNumRef <- newIORef @(​ Maybe ​ ​ Int ​) ​ Nothing ​

Reading and Writing IORefs

Data.IORef is a small module with only a few exported functions that let you create, read, write, and modify IORefs in place. You’ve already learned how to create a new IORef, so let’s work through an example of how to modify them. We’ll start by using writeIORef :: IORef a -> a -> IO () and readIORef :: IORef a -> IO a to first write a value to an IORef and then to read it back:

​  ​ {-# LANGUAGE TypeApplications #-} ​
​  ​ module ​ ​ Main ​ ​ where ​
​  ​ import ​ ​ Data.IORef ​
​  
​  readWriteRef :: ​ IO ​ ​ Int ​
​  readWriteRef = ​ do ​
​  myRef <- newIORef @​ Int ​ 0
​  writeIORef myRef 7
​  refValue <- readIORef myRef
​  pure refValue
​  
​  main :: ​ IO ​ ()
​  main = readWriteRef >>= print

In this example, the readWriteRef function is an IO action that creates a new IORef, writes a value to it, and then reads the value and returns it.

Using IORefs to Traverse a Directory Tree

To see an example of how to use IORefs in a real-world application, let’s write a function that will allow us to traverse part of a filesystem. We’ll make use of two libraries from Hackage for this application:

  • directory gives us functions to deal with files and directories.
  • containers provides the Set data structure.

Create a new project and add the directory and containers dependencies. We’ll start by adding the TypeApplications extension and importing a few modules that we’ll be using:

​  ​ {-# LANGUAGE TypeApplications #-} ​
​  ​ module ​ ​ Main ​ ​ where ​
​  
​  ​ import ​ ​ Control.Exception ​ (​ IOException ​, ​ handle ​)
​  ​ import ​ ​ Control.Monad ​ (​ join ​, ​ void ​, ​ when ​)
​  ​ import ​ ​ Data.Foldable ​ (​ for_ ​)
​  ​ import ​ ​ Data.IORef ​ (​ modifyIORef ​, ​ newIORef ​, ​ readIORef ​, ​ writeIORef ​)
​  ​ import ​ ​ Data.List ​ (​ isSuffixOf ​)
​  ​ import ​ ​ System.Directory ​
​  ( ​ canonicalizePath ​
​  , ​ doesDirectoryExist ​
​  , ​ doesFileExist ​
​  , ​ listDirectory ​
​  )
​  ​ import ​ ​ qualified ​ ​ Data.Set ​ ​ as ​ Set (empty, insert, member)
​  ​ import ​ ​ Text.Printf ​ (​ printf ​)

Since we’ll be using several new functions throughout this example, we’ve listed each function in our import statement. You may choose to import the entire modules here if you want to experiment with the examples as you work through them.

Next, we need to define a couple of helper functions that will make it easier for us to implement our directory traversal. The first helper function we’ll write, dropSuffix , will let us easily strip off any trailing slashes from a path provided by a user:

​  dropSuffix :: ​ String ​ -> ​ String ​ -> ​ String ​
​  dropSuffix suffix s
​  | suffix `isSuffixOf` s =
​  take (length s - length suffix) s
​  | otherwise = s

As we’re traversing the contents of a directory, we need to classify the files that we find. We’ll want to identify subdirectories that we want to descend into, plain files that we want to work with, and special files (for example, named pipes, Unix sockets, or block and character devices) that we’ll ignore. To make this easier we’ll add a new type, FileType , and a function, classifyFile , which will take the path to a file and return the file’s type:

​  ​ data ​ ​ FileType ​
​  = ​ FileTypeDirectory ​
​  | ​ FileTypeRegularFile ​
​  | ​ FileTypeOther ​
​  
​  classifyFile :: ​ FilePath ​ -> ​ IO ​ ​ FileType ​
​  classifyFile fname = ​ do ​
​  isDirectory <- doesDirectoryExist fname
​  isFile <- doesFileExist fname
​  pure $ ​ case ​ (isDirectory, isFile) ​ of ​
​  (​ True ​, ​ False ​) -> ​ FileTypeDirectory ​
​  (​ False ​, ​ True ​) -> ​ FileTypeRegularFile ​
​  _otherwise -> ​ FileTypeOther ​

Let’s start by looking at a naive traversal implementation that doesn’t make use of IORefs:

​  naiveTraversal :: ​ FilePath ​ -> (​ FilePath ​ -> a) -> ​ IO ​ [a]
​  naiveTraversal rootPath action = ​ do ​
​  classification <- classifyFile rootPath
​  ​ case ​ classification ​ of ​
​  ​ FileTypeOther ​ ->
​  pure ​ [] ​
​  ​ FileTypeRegularFile ​ ->
​  pure $ [action rootPath]
​  ​ FileTypeDirectory ​ -> ​ do ​
​  contents <- map (fixPath rootPath) <$> listDirectory rootPath
​  results <- concat <$> getPaths contents
​  pure results
​  ​ where ​
​  fixPath parent fname = parent <> ​ "/" ​ <> fname
​  getPaths = mapM (​ \ ​path -> naiveTraversal path action)

In our naive example function, we start traversing a directory structure by classifying the file we’re given. If it’s some special file, we don’t do anything and return an empty list. If it’s a plain file, we construct a singleton list by applying the user-provided function to the file. If we’re looking at a directory, we recursively traverse each file in the directory. You’ll notice that listDirectory returns a relative file name (without a trailing / ), so we prefix our current path to it.

This function works, but we have two problems. The first problem that we have is an inefficiency—we’re constructing a large number of intermediate lists that we’re concatenating together. For large directories with many files and subdirectories also containing many files, this can lead us to making a lot of allocations and holding a lot of data in memory as we’re trying to create our final result. The second problem is a bug. We are not accounting for circular references that we might encounter while traversing the directory structure, so there’s a risk that we could end up waiting forever—or at least until our program runs out of memory and crashes.

IORefs can help us address both of these problems. We’ll still use the same basic algorithm, but now we’ll keep some history of directories we’ve visited, and we’ll avoid creating intermediate lists as we’re building up our set of results.

Our new function, traverseDirectory , will have the same type as our naive traversal function:

​  traverseDirectory :: ​ FilePath ​ -> (​ FilePath ​ -> a) -> ​ IO ​ [a]
​  traverseDirectory rootPath action = ​ do ​

Next, let’s consider the problem of encountering loops in our filesystem. A loop will occur when a directory contains a symbolic link to a directory that is an ancestor of the current directory. In other words, imagine the following directory structure:

​  user@host:/tmp$ tree hasLoop/
​  hasLoop/
​  └── foo
​  └── theLoop -> /tmp/hasLoop
​  
​  2 directories, 0 files

If we begin traversing in hasLoop we will eventually decend into theLoop . After a few iterations, we’ll start to see paths like:

​  user@host:/tmp$ tree /tmp/hasLoop/foo/theLoop/foo/theLoop/foo/theLoop
​  /tmp/hasLoop/foo/theLoop/foo/theLoop/foo/theLoop
​  └── foo
​  └── theLoop -> /tmp/hasLoop

One way to fix this is to use the canonicalizePath function from System.Directory . This function will look at the path to a file, and if the file is a symbolic link, it will give us the path that the link references:

​  ​ λ ​ canonicalizePath ​ "/tmp/hasLoop/foo/theLoop" ​
​  ​ "/tmp/hasLoop" ​

We can use this function to keep track of the canonical path of all of the directories that we’ve ever tried to descend into, we just need a way to keep a list of every directory that we’ve seen. We’ll manage that using a Set from the containers library. Let’s create a new IORef to reference an empty set:

​  seenRef <- newIORef ​ Set ​.empty

We’re also going to create a new IORef to hold the list of results that we want to eventually return. We’ll make use of this a bit later in our function:

​  resultRef <- newIORef ​ [] ​

Now that we have a way to hold a set of the directories we’ve already dealt with, it’d be nice to have a couple of helper functions to make it easy for us to test whether we’ve already dealt with a directory, and to say we’ve already dealt with one. We want these functions to have access to the seenRef reference we just defined, so we’ll define our new functions inside of a let block:

​  ​ let ​
​  haveSeenDirectory canonicalPath =
​  ​ Set ​.member canonicalPath <$> readIORef seenRef
​  
​  addDirectoryToSeen canonicalPath = ​ do ​
​  seen <- readIORef seenRef
​  writeIORef seenRef $ ​ Set ​.insert canonicalPath seen

In the example, we’ve added two new helper functions. The first, haveSeenDirectory , takes a canonical path and looks to see whether it is a member of the set that is currently in the IORef.

The second function, addDirectoryToSeen , takes a canonical path and updates the set of paths that we’ve seen to include this new path. We first extract the set of paths we’ve seen, then add our new one and update the reference. This pattern of extracting a value from a reference, updating it, and writing it again can start to get a little tedious. The modifyIORef has the type modifyIORef :: IORef a -> (a -> a) -> IO () , and it allows you to apply a function to the value at a reference. Let’s refactor addDirectoryToSeen to use it:

​  addDirectoryToSeen canonicalPath =
​  modifyIORef seenRef $ ​ Set ​.insert canonicalPath

With the helper functions in place, we can start implementing our traversal logic. Like haveSeenDirectory and addDirectoryToSeen , we’ll add our new function to the our let block:

​  traverseSubdirectory subdirPath = ​ do ​

The first thing we’ll want to do when we’re looking at any directory is to get a list of all of the contents:

​  contents <- listDirectory subdirPath

Once we have a list of the contents of the current directory, we want to iterate over them so that we can either handle the files, or decend into the subdirectories. Instead of using a map or fold here, we’re going to make use of a new function from Data.Foldable , for_ .

for_ is handy function that lets you apply some Applicative or Monad computation to each item in a collection of elements. For example, you can print out a list of numbers with:

​  ​ λ ​ for_ [1..10] $ ​ \ ​num -> putStr $ show num <> ​ " " ​
​  1 2 3 4 5 6 7 8 9 10
​  ​ λ ​

For our directory traversal function we’re going to iterate over the contents that we’ve just gotten from the current directory.

​  for_ contents $ ​ \ ​file' ->

Dealing with file IO on a live system is tricky—a lot of things can go wrong. Files may be deleted between when we list the directory contents and when we try to access them, broken symbolic links might point to files that no longer exist, or parts of the filesystem could become unmounted. All of these cases could lead to IO Exceptions being raised.

In some cases, handling IO exceptions can be quite challenging, but thankfully in this case, if we run into an error with handling a file, we can safely skip it and move on to the next file.

We’ll handle our potential errors with the handle function from Control.Exception . This function works just like the catch function that you’ve already used, except the arguments are reversed and we provide our error handler first. In cases like our current function with very simple error handling this can make our code easier to read:

​  handle @​ IOException ​ (​ \ ​​ _ ​ -> pure ()) $ ​ do ​

The first thing we’ll want to do as we’re processing any given file is to fix up the name and classify the file type. After that, we’ll match on the file classification. For any nonstandard file type, we’ll ignore it and move on:

​  ​ let ​ file = subdirPath <> ​ "/" ​ <> file'
​  canonicalPath <- canonicalizePath file
​  classification <- classifyFile canonicalPath
​  ​ case ​ classification ​ of ​
​  ​ FileTypeOther ​ -> pure ()

Finally, we can add in the code to handle files and directories while making use of our IORef-based approach. For an individual file, we no longer return a value, instead we’ll just cons the result of applying our user-supplied function directly onto our reference list:

​  ​ FileTypeRegularFile ​ ->
​  modifyIORef resultRef (​ \ ​results -> action file : results)

For directories, we no longer have to keep an intermediate list of results and concatenate them together, we do however need to ensure that we add our directory to the list of directories we’ve already processed. We’ll use when from Control.Monad . This function has the type when :: Applicative f => Bool -> f () -> f () , and it allows us to conditionally run a computation:

​  ​ FileTypeDirectory ​ -> ​ do ​
​  alreadyProcessed <- haveSeenDirectory file
​  when (not alreadyProcessed) $ ​ do ​
​  addDirectoryToSeen file
​  traverseSubdirectory file

The last thing we need to do is call traverseSubdirectory with the root path (and remove the trailing ’/’ if present), and then return the contents of our list. The final function is:

​  traverseDirectory :: ​ FilePath ​ -> (​ FilePath ​ -> a) -> ​ IO ​ [a]
​  traverseDirectory rootPath action = ​ do ​
​  seenRef <- newIORef ​ Set ​.empty
​  resultRef <- newIORef ​ [] ​
​  ​ let ​
​  haveSeenDirectory canonicalPath =
​  ​ Set ​.member canonicalPath <$> readIORef seenRef
​  
​  addDirectoryToSeen canonicalPath =
​  modifyIORef seenRef $ ​ Set ​.insert canonicalPath
​  
​  traverseSubdirectory subdirPath = ​ do ​
​  contents <- listDirectory subdirPath
​  for_ contents $ ​ \ ​file' ->
​  handle @​ IOException ​ (​ \ ​​ _ ​ -> pure ()) $ ​ do ​
​  ​ let ​ file = subdirPath <> ​ "/" ​ <> file'
​  canonicalPath <- canonicalizePath file
​  classification <- classifyFile canonicalPath
​  ​ case ​ classification ​ of ​
​  ​ FileTypeOther ​ -> pure ()
​  ​ FileTypeRegularFile ​ ->
​  modifyIORef resultRef (​ \ ​results -> action file : results)
​  ​ FileTypeDirectory ​ -> ​ do ​
​  alreadyProcessed <- haveSeenDirectory file
​  when (not alreadyProcessed) $ ​ do ​
​  addDirectoryToSeen file
​  traverseSubdirectory file
​  
​  traverseSubdirectory (dropSuffix ​ "/" ​ rootPath)
​  readIORef resultRef

We still have some opportunities to refactor this function a bit, but before we do, let’s load it up in ghci and test it to see how it works. In the following examples we’ll use this directory structure:

​  user@host:~$ tree /tmp/test/
​  /tmp/test/
​  ├── a
​  │   └── b
​  │   └── c
​  │   └── d
​  │   └── d-file
​  ├── fizz
​  │   ├── buzz
​  │   │   └── buzz-file.1
​  │   └── fizz-file
​  └── foo
​  ├── bar
​  │   ├── bar-file.1
​  │   └── baz
​  │   └── baz-file.1
​  └── foo-file.1
​  
​  9 directories, 6 files

We can start testing our directory traversal function by using it to give us a list of all of the files that it encounters:

​  ​ λ ​ :​ type ​ traverseDirectory ​ "/tmp/test/" ​ id
​  traverseDirectory ​ "/tmp/test/" ​ id :: ​ IO ​ [​ FilePath ​]
​  ​ λ ​ traverseDirectory ​ "/tmp/test/" ​ id
​  [ ​ "/tmp/test/foo/bar/bar-file.1" ​
​  , ​ "/tmp/test/foo/bar/baz/baz-file.1" ​
​  , ​ "/tmp/test/foo/foo-file.1" ​
​  , ​ "/tmp/test/a/b/c/d/d-file" ​
​  , ​ "/tmp/test/fizz/fizz-file" ​
​  , ​ "/tmp/test/fizz/buzz/buzz-file.1" ​ ]

We can also do some transformations on the filenames. For example, if we wanted to get the length of the filenames:

​  ​ λ ​ traverseDirectory ​ "/tmp/test/" ​ length
​  [28,32,24,24,24,31]

Imagine though that instead of simply working with the names of the files themselves, we wanted to do something that involved the contents of the file, like reading the file in and counting the number of bytes:

​  ​ import ​ ​ Data.ByteString ​ (​ ByteString ​)
​  ​ import ​ ​ qualified ​ ​ Data.ByteString ​ ​ as ​ BS
​  
​  countBytes :: ​ FilePath ​ -> ​ IO ​ (​ FilePath ​, ​ Integer ​)
​  countBytes path = ​ do ​
​  bytes <- fromIntegral . ​ BS ​.length <$> ​ BS ​.readFile path
​  pure (path, bytes)

Let’s try passing in countBytes to our traversal function to see what we get back:

​  ​ λ ​ traverseDirectory ​ "/tmp/test/" ​ countBytes
​  ​ λ ​

Nothing! If that’s unexpected, we might get some help from looking at the type of the expression:

​  ​ λ ​ :​ type ​ traverseDirectory
​  traverseDirectory :: ​ FilePath ​ -> (​ FilePath ​ -> a) -> ​ IO ​ [a]
​  ​ λ ​ :​ type ​ traverseDirectory ​ "/tmp/test/" ​ countBytes
​  traverseDirectory ​ "/tmp/test/" ​ countBytes
​  :: ​ IO ​ [​ IO ​ (​ FilePath ​, ​ Integer ​)]

When we call traverseDirectory with countBytes we’re getting back a computation that itself contains a list of computations which, if evaluated, will give us the number of bytes in a file. We can work around this by evaluating all the computations in the list. The sequence and join functions will take care of this for us:

​  ​ λ ​ :​ type ​ sequence
​  sequence :: (​ Traversable ​ t, ​ Monad ​ m) => t (m a) -> m (t a)
​  ​ λ ​ :​ type ​ join
​  join :: ​ Monad ​ m => m (m a) -> m a
​  ​ λ ​ join . fmap sequence $ traverseDirectory ​ "/tmp/test/" ​ countBytes
​  [(​ "/tmp/test/foo/bar/bar-file.1" ​,0)
​  ,(​ "/tmp/test/foo/bar/baz/baz-file.1" ​,0)
​  ,(​ "/tmp/test/foo/foo-file.1" ​,0)
​  ,(​ "/tmp/test/a/b/c/d/d-file" ​,0)
​  ,(​ "/tmp/test/fizz/fizz-file" ​,0)
​  ,(​ "/tmp/test/fizz/buzz/buzz-file.1" ​,0)]

This approach still has the problem of causing us to accumulate a potentially large number of unevaluated computations. It would be ideal if our traverseDirectory function could evaluate an IOAction for us as it’s doing its other work. Let’s take on a small refactor to see this in action:

​  traverseDirectory :: ​ FilePath ​ -> (​ FilePath ​ -> ​ IO ​ ()) -> ​ IO ​ ()
​  traverseDirectory rootPath action = ​ do ​
​  seenRef <- newIORef ​ Set ​.empty
​  ​ let ​
​  haveSeenDirectory canonicalPath =
​  ​ Set ​.member canonicalPath <$> readIORef seenRef
​  
​  addDirectoryToSeen canonicalPath =
​  modifyIORef seenRef $ ​ Set ​.insert canonicalPath
​  
​  traverseSubdirectory subdirPath = ​ do ​
​  contents <- listDirectory subdirPath
​  for_ contents $ ​ \ ​file' ->
​  handle @​ IOException ​ (​ \ ​​ _ ​ -> pure ()) $ ​ do ​
​  ​ let ​ file = subdirPath <> ​ "/" ​ <> file'
​  canonicalPath <- canonicalizePath file
​  classification <- classifyFile canonicalPath
​  ​ case ​ classification ​ of ​
​  ​ FileTypeOther ​ -> pure ()
​  ​ FileTypeRegularFile ​ ->
​  action file
​  ​ FileTypeDirectory ​ -> ​ do ​
​  alreadyProcessed <- haveSeenDirectory file
​  when (not alreadyProcessed) $ ​ do ​
​  addDirectoryToSeen file
​  traverseSubdirectory file
​  
​  traverseSubdirectory (dropSuffix ​ "/" ​ rootPath)

This version of our function no longer keeps a results reference around. Instead of appending a result to a list of results, we instead simply run some IOAction with the current file. This means that we don’t, necessarily, need to store any intermediate files at all. If, for example, we wanted to print the file sizes out as we go, we can say:

​  ​ λ ​ traverseDirectory ​ "/tmp/test/" ​ $ ​ \ ​file -> countBytes file >>= print
​  (​ "/tmp/test/fizz/buzz/buzz-file.1" ​,0)
​  (​ "/tmp/test/fizz/fizz-file" ​,0)
​  (​ "/tmp/test/a/b/c/d/d-file" ​,0)
​  (​ "/tmp/test/foo/foo-file.1" ​,0)
​  (​ "/tmp/test/foo/bar/baz/baz-file.1" ​,0)
​  (​ "/tmp/test/foo/bar/bar-file.1" ​,0)

You can also recreate the capabilities of the original function by factoring out the use of an IORef to accumulate results into a new function:

​  traverseDirectory' :: ​ FilePath ​ -> (​ FilePath ​ -> a) -> ​ IO ​ [a]
​  traverseDirectory' rootPath action = ​ do ​
​  resultsRef <- newIORef ​ [] ​
​  traverseDirectory rootPath $ ​ \ ​file -> ​ do ​
​  modifyIORef resultsRef (action file :)
​  readIORef resultsRef

These two functions, traverseDirectory and traverseDirectory’ , demonstrate one of the common ways that you’ll use IORefs in real-world applications. By creating an IORef that is part of the closure of a function that you pass around, or call recursively, you can get data and run computations that would be awkward or expensive to do without external mutable state.

Let’s look at one more example, just to drive the point home. Imagine that you want to get the contents of the largest file in our directory tree. We’ll assume for the sake of the example that the filesystem does not allow any easier way to get the size of a file except for reading it into memory. If you were to use the original version of traverseDirectory that returns a list of values, you could read the contents of each file and then take the longest file, but that would mean that you’d need to possibly store all of the contents of all of the files in memory. That could put quite unreasonable memory pressure on the application. Alternatively, you could store a computation that returns the length and fold over it, but that requires traversing the entire directory structure twice. Using an IORef, we can re-use our existing traverseDirectory function and get the longest file in a single pass:

​  longestContents :: ​ FilePath ​ -> ​ IO ​ ​ ByteString ​
​  longestContents rootPath = ​ do ​
​  contentsRef <- newIORef ​ BS ​.empty
​  ​ let ​
​  takeLongestFile a b =
​  ​ if ​ ​ BS ​.length a >= ​ BS ​.length b
​  ​ then ​ a
​  ​ else ​ b
​  
​  traverseDirectory rootPath $ ​ \ ​file -> ​ do ​
​  contents <- ​ BS ​.readFile file
​  modifyIORef contentsRef (takeLongestFile contents)
​  
​  readIORef contentsRef

Using an IORef here allows us to re-use our existing traversal function, make a single pass through the directory structure, and keep at most two files worth of data in memory at a time.