In the last section, you learned how to use a data structure to cache results from an expensive function call. That approach works extremely well for certain types of problems, but it lacks the flexibility we sometimes need when trying to optimize our programs. In some cases, we need a more general type of mutability.

Earlier in this book, you learned about IORefs as a way to get mutability. IORef s do give us access to mutability, but at the steep cost of needing to move our entire function into an IO action. In general, we’d rather avoid putting otherwise pure functions into IO , and from the perspective of an outside caller, a function like editDistance should remain pure even if it happens to use some mutable state internally.

The idea that we might have a function that is referentially transparent and acts like a pure function from the outside, but uses mutable data as part of its implementation, is called internal mutability . We can get internal mutability in Haskell with ST actions. In this section, we’ll refactor our spellchecker again to use internal mutability, and look at some of the new things we can do when we’re using a more flexible approach to caching. First though, let’s take a look at the ST type and how to use ST actions.

An Introduction to ST

In the first chapter of this book, you were introduced to the idea of referential transparency . This is the idea that, thanks to Haskell being a pure functional language, any time we have some expression that evaluates to a value, we can replace the expression with the value, and the behavior of our program shouldn’t change. One of the reasons that IO allows us to write pure functional programs that have side effects is that they replace an expression that might not have referential transparency, for example, a function that uses a value inside of an IORef , with a referentially transparent function that returns an opaque IO action. We have to do this for IO because the real world is subject to external factors that we can’t control in our program. We might read from a file that was changed by another process, or access a mutable variable that we changed in another thread.

The problem with IO is that, once something gets embedded in an IO action, there’s no way to get it back into the world of pure Haskell values. We can’t simply write a function to turn an IO a into an a , because that would break referential transparency.

unsafePerformIO

| images/aside-icons/info.png | There is a family of functions that will let us turn IO actions back into ordinary Haskell values. For example, the unsafePerformIO function from System.IO.Unsafe has the type unsafePerformIO :: IO a -> a . These functions have some legitimate uses, but as their name implies, they are unsafe and can be be quite tricky to use correctly. In almost all cases, you should prefer ST over unsafePerformIO and friends when writing programs that need internal mutability. |

What if we could though? Let’s imagine a type called SafeIO that lets us make SafeIO actions and evaluate them in a referentially transparent way. We’ll also create a SafeRef type that is similar to an IORef but can be used with SafeIO . For the moment we’ll skip actually implementing any of these examples and fall back on undefined to help us sketch out the idea for our theoretical library without worrying about how to build it.

​  ​ data ​ ​ SafeIO ​ a = ​ SafeIO ​ a
​  ​ data ​ ​ SafeRef ​ a = ​ SafeRef ​ a
​  
​  ​ instance ​ ​ Functor ​ ​ SafeIO ​ ​ where ​
​  fmap = undefined
​  
​  ​ instance ​ ​ Applicative ​ ​ SafeIO ​ ​ where ​
​  pure = undefined
​  (<*>) = undefined
​  
​  ​ instance ​ ​ Monad ​ ​ SafeIO ​ ​ where ​
​  (>>=) = undefined
​  
​  runSafeIO :: ​ SafeIO ​ a -> a
​  runSafeIO (​ SafeIO ​ a) = a

What could we do with a function like this, and what limitations would we have to put on it?

First, SafeIO shouldn’t be able to access the outside world. That is to say, we can’t do things like read or write files. Why not?

​  appendToFile :: ​ FilePath ​ -> ​ String ​ -> ​ SafeIO ​ ()
​  appendToFile = undefined
​  
​  readFile :: ​ FilePath ​ -> ​ SafeIO ​ ​ String ​
​  readFile = undefined
​  
​  unsafeAction :: ​ String ​ -> ​ SafeIO ​ ​ String ​
​  unsafeAction contents =
​  appendToFile ​ "example.txt" ​ contents >> readFile ​ "example.txt" ​
​  
​  notValid :: ​ String ​
​  notValid =
​  runSafeIO (unsafeAction ​ "foo" ​) <> runSafeIO (unsafeAction ​ "foo" ​)

In this example, the expression runSafeIO (unsafeAction "foo") isn’t referentially transparent. If we assume that example.txt starts as an empty file, the first time we evaluate the expression, we’ll get back foo , and the second time we evaluate, it we’ll get back foofoo . Any example we can think of where our SafeIO actions are allowed to access the world outside of our program are at risk of the same problem. If we want to make SafeIO actions actually safe, we’ll need to restrict them from accessing anything outside of our program.

That doesn’t make SafeIO useless though. We can still allocate and free memory and have access to mutable references. Let’s imagine that we wanted to use a SafeIO equivalent to an IORef for some program:

​  newSafeRef :: a -> ​ SafeIO ​ (​ SafeRef ​ a)
​  newSafeRef = undefined
​  
​  modifySafeRef :: ​ SafeRef ​ a -> (a -> a) -> ​ SafeIO ​ ()
​  modifySafeRef = undefined
​  
​  readSafeRef :: ​ SafeRef ​ a -> ​ SafeIO ​ a
​  readSafeRef = undefined
​  
​  safeAction :: ​ String ​ -> ​ SafeIO ​ ​ Int ​
​  safeAction message = ​ do ​
​  safeRef <- newSafeRef 0
​  traverse_ (​ \ ​​ _ ​ -> modifySafeRef safeRef (+1)) message
​  readSafeRef safeRef
​  
​  valid :: ​ Int ​
​  valid =
​  runSafeIO (safeAction ​ "hello" ​) + runSafeIO (safeAction ​ "hello" ​)

In this example, runSafeIO (safeAction "hello") is referentially transparent. Even though it has side effects and modifies a reference, from the outside it behaves like a pure function. So, perhaps our SafeIO can have mutable references and remain safe? Let’s try another example:

​  updateRefWithCount :: ​ SafeRef ​ ​ Int ​ -> ​ String ​ -> ​ SafeIO ​ ​ Int ​
​  updateRefWithCount safeRef message =
​  modifySafeRef safeRef (+ length message) >> readSafeRef safeRef
​  
​  stillSafe :: ​ String ​ -> ​ SafeIO ​ ​ Int ​
​  stillSafe message = ​ do ​
​  ref <- newSafeRef 0
​  len1 <- updateRefWithCount ref message
​  len2 <- updateRefWithCount ref message
​  pure $ len1 + len2
​  
​  stillValid :: ​ Int ​
​  stillValid =
​  runSafeIO (safeAction ​ "hello" ​) + runSafeIO (safeAction ​ "hello" ​)

In this example, we’re passing shared state from stillSafe to updateRefWithCount , but all access to our safe reference is still held inside of a single SafeIO action that’s being evaluated. There’s never any shared state between different SafeIO actions, so they can’t interfere with one another. That means stillValid is still a safe function.

Unfortunately, a small change here could still break our code. If we call update RefWithCount directly with a SafeRef then we’ll still break referential transparency:

​  notSoSafe :: ​ Int ​
​  notSoSafe =
​  ​ let ​ someRef = runSafeIO (newSafeRef 0)
​  ​ in ​ runSafeIO (updateRefWithCount someRef ​ "hello" ​) +
​  runSafeIO (updateRefWithCount someRef ​ "hello" ​)

In this example, the first time we evaluate runSafeIO (updateRefWithCount someRef "hello") , the value in our reference will start at 0 and the function will return 5 , but the second time we evaluate the expression, the reference will start out at 5 and the expression will return 10 .

These examples help to demonstrate another restriction we’ll need to put on SafeIO if we want to be safe—we need to prevent any mutable data from being shared between different SafeIO actions. The question then is, how can we allow the safe example where we can compose SafeIO actions and evaluate them when they don’t share resources, but still prohibit the second case where resources would cross the boundaries between different SafeIO actions?

It turns out that there’s a clever way that we can use the type system to do this. Let’s take a look at the implementation and then untangle why it works.

We’ll start by updating the types of SafeIO and SafeRef to add an extra type parameter that we’ll call ‘s‘. This is a phantom type parameter; we won’t use it in the value of either of our types. Instead, this parameter will act as a sort of type level identifier of which SafeIO action generated a particular value.

​  ​ data ​ ​ SafeIO ​ s a = ​ SafeIO ​ a
​  ​ data ​ ​ SafeRef ​ s a = ​ SafeRef ​ a

We’ll also need to update the types of the functions that work with SafeIO actions. In particular, let’s look at the new type of runSafeIO and newSafeRef :

​  runSafeIO :: ​ SafeIO ​ s a -> a
​  runSafeIO (​ SafeIO ​ a) = a
​  
​  newSafeRef :: a -> ​ SafeIO ​ s (​ SafeRef ​ s a)
​  newSafeRef = undefined

You can update the rest of your examples. You should notice that right now everything will continue to compile. Our identifier doesn’t seem to be helping us at all yet. The problem is that we’re ensuring that the identifier of a SafeIO and a SafeRef are the same, but we’re not ensuring that they are unique. The compiler can give the same identifier to every single SafeIO action and every single SafeRef and that will make our code typecheck, but it isn’t what we want.

Luckily there’s a trick we can use to help ensure we can get unique identifiers when we run a particular SafeIO action. We just need to change the type of runSafeIO a bit. If we wanted to be a bit verbose, we could rewrite the current type of our function with an explicit forall quantifier as:

​  runSafeIO :: forall s a. ​ SafeIO ​ s a -> a

The forall here says that, essentially, the function should work for any types s and a , and we as the caller of the function can decide what values of s and a should be used. When we call runSafeIO we’re not providing any particular value, so the compiler picks one that satisfies the requirements for us and builds the application. Thankfully, there is a feature of the type system we can use to prevent the compiler from being so “helpful”: higher ranked types . In newer versions of GHC, this feature is enabled by default, but in older versions of the compiler you’ll need to enable the RankNTypes extension. When enabled, this extension lets us “nest” layers of polymorphism, passing one polymorphic function into another. It’s not obvious how this differs from the functions we have been working with throughout this book, so let’s dive into a hands-on example. With RankNTypes enabled, we can rewrite runSafeIO with a higher ranked type:

​  runSafeIO :: forall a. (forall s. ​ SafeIO ​ s a) -> a

Or, less verbosely:

​  runSafeIO :: (forall s. ​ SafeIO ​ s a) -> a
RankNTypes

| images/aside-icons/info.png | The RankNTypes extension has been available since GHC 6.8.1. This extension is enabled by default in GHC2021 but you’ll need to enable it manually if you are using Haskell2010 . This extension is generally safe, and shouldn’t break any existing code. This extension also implies the ExplicitForAll extension. If you’ve enabled RankNTypes you don’t need to explicitly enable ExplicitForAll . |

This function uses “rank 2” polymorphism. That means we’ve got a polymorphic function called runIO that needs to be able to work with any type a . We’re passing it in a value with the type (forall s. SafeIO s a) . The forall here is inside of an argument that’s being passed to the function. That means runSafeIO doesn’t have to be polymorphic over any type s ; instead, the function it’s being passed needs to be polymorphic and able to work with any s that runSafeIO chooses. In other words, neither we nor the compiler have the option of selecting a convenient value of s because it’s not decided by the caller of runSafeIO . Instead, we need to provide a SafeIO action that will itself work for any arbitrary state identifier. In practice, that means we can’t make any assumptions about what the type is, so each time we evaluate runSafeIO it will be with a new unique identifier. If you try to compile this version of the program you’ll see that we’re getting an error:

​  SafeIO.hs:67:28-39: error: …
​  • Couldn't match type ‘a’ with ‘SafeRef s Integer’
​  Expected: SafeIO s a
​  Actual: SafeIO s (SafeRef s Integer)
​  ‘a’ is a rigid type variable bound by
​  the inferred type of someRef :: a
​  at /home/user/EffectiveHaskell/Chapter14/st/SafeIO.hs:67:7-40
​  • In the first argument of ‘runSafeIO’, namely ‘(newSafeRef 0)’
​  In the expression: runSafeIO (newSafeRef 0)
​  In an equation for ‘someRef’: someRef = runSafeIO (newSafeRef 0)
​  • Relevant bindings include
​  someRef :: a
​  (bound at /home/user/EffectiveHaskell/Chapter14/st/SafeIO.hs:67:7)
​  |
​  Compilation failed.

The type error here is a little hard to untangle if you aren’t accustomed to this kind of error, but we can see what’s happening if we step through the code. In the expression runSafeIO (newSafeRef 0) we’re taking a value with the type SafeIO s (SafeRef s Int) and passing it to a function with type (forall s. SafeIO s a) -> a . If we expand the type variables out, we’ll get:

​  forall a. (forall s. ​ SafeIO ​ s (​ SafeRef ​ s a)) -> ​ SafeRef ​ s a

The problem is, this can’t typecheck, because the type of our identifier would escape the scope where it’s defined. This turns out to be exactly what we need to ensure that none of our mutable resources leak outside of a particular SafeIO action. As long as any mutable resource carries around the state identifier for the SafeIO action that created it, we can prevent it from escaping.

As you might have expected, it turns out that what we’ve been calling SafeIO is actually a type that already exists in base . It’s called ST , and it’s defined in Control.Monad.ST :

​  ​ data ​ ​ ST ​ s a
​  
​  runST :: (forall s. ​ ST ​ s a) -> a

The Data.STRef module from base gives us access to STRefs :

​  ​ data ​ ​ STRef ​ s a
​  
​  newSTRef :: a -> ​ ST ​ s (​ STRef ​ s a)
​  readSTRef :: ​ STRef ​ s a -> ​ ST ​ s a
​  writeSTRef :: ​ STRef ​ s a -> a -> ​ ST ​ s ()
​  modifySTRef :: ​ STRef ​ s a -> (a -> a) -> ​ ST ​ s ()

Edit Distance with ST

Now that we have a way to use mutable references in a pure function with ST , let’s revisit our edit distance function and look at how we can make use of this to write a more composable optimized version of our function. We’ll start by creating a newtype wrapper to hold a reference to a cache, and write some utility functions to make it easier to read and write from the cache. We’re going to go back to caching the text values rather than numeric offsets in this example:

​  ​ {-# LANGUAGE OverloadedStrings #-} ​
​  ​ module ​ ​ SpellCheck.STMemo ​ ​ where ​
​  ​ import ​ ​ Data.Foldable ​
​  ​ import ​ ​ Control.Monad ​
​  ​ import ​ ​ Data.Map.Strict ​ (​ Map ​)
​  ​ import ​ ​ qualified ​ ​ Data.Map.Strict ​ ​ as ​ Map
​  ​ import ​ ​ Data.STRef ​
​  ​ import ​ ​ Control.Monad.ST ​
​  ​ import ​ ​ Data.Text ​ (​ Text ​)
​  ​ import ​ ​ qualified ​ ​ Data.Text ​ ​ as ​ T
​  ​ import ​ ​ Types ​
​  
​  ​ newtype ​ ​ MemoCache ​ s = ​ MemoCache ​ (​ STRef ​ s (​ Map ​ (​ Text ​,​ Text ​) ​ Int ​))
​  
​  readCache :: ​ MemoCache ​ s -> ​ Text ​ -> ​ Text ​ -> ​ ST ​ s (​ Maybe ​ ​ Int ​)
​  readCache (​ MemoCache ​ ref) stringA stringB =
​  ​ Map ​.lookup (stringA, stringB) <$> readSTRef ref
​  
​  updateCache :: ​ MemoCache ​ s -> ​ Text ​ -> ​ Text ​ -> ​ Int ​ -> ​ ST ​ s ()
​  updateCache (​ MemoCache ​ ref) stringA stringB distance =
​  modifySTRef ref $ ​ Map ​.insert (stringA, stringB) distance
​  
​  newCache :: ​ ST ​ s (​ MemoCache ​ s)
​  newCache = ​ MemoCache ​ <$> newSTRef ​ Map ​.empty

Next, let’s update our editDistance function. In the last implementation of editDistance that we created, the memoization step was entirely self-contained inside of the editDistance function. That was by necessity—we needed to be able to map the arguments of our function to indexes in a list, and we could only do that for any two pairs of strings. Now that we have more flexibility in the type of cache that we’re using, and how we access it, we can use the same cache across all of the calls to editDistance . This will save us some time if we encounter duplicate words, or even just duplicate suffixes, in the document we’re spellchecking.

​  editDistance :: ​ MemoCache ​ s -> ​ Text ​ -> ​ Text ​ -> ​ ST ​ s ​ Int ​
​  editDistance cache a b =
​  memoizedEditDistance a b
​  ​ where ​
​  memoizedEditDistance stringA stringB = ​ do ​
​  result <- readCache cache stringA stringB
​  ​ case ​ result ​ of ​
​  ​ Just ​ distance ->
​  pure distance
​  ​ Nothing ​ -> ​ do ​
​  newDistance <- findDistance stringA stringB
​  updateCache cache stringA stringB newDistance
​  pure newDistance
​  
​  findDistance stringA stringB
​  | ​ T ​.null stringA = pure $ ​ T ​.length stringB
​  | ​ T ​.null stringB = pure $ ​ T ​.length stringA
​  | ​ T ​.head stringA == ​ T ​.head stringB =
​  memoizedEditDistance restOfA restOfB
​  | otherwise = ​ do ​
​  deleteCost <- memoizedEditDistance restOfA stringB
​  insertCost <- memoizedEditDistance stringA restOfB
​  swapCost <- memoizedEditDistance restOfA restOfB
​  pure $ 1 + minimum [swapCost, deleteCost, insertCost]
​  ​ where ​
​  restOfA = ​ T ​.tail stringA
​  restOfB = ​ T ​.tail stringB

As you can see, the pattern of our function remains quite similar to the earlier memoized version. We’re using do notation now, since we’re running inside of ST actions, but otherwise we’re accessing our code in the same way.

Before we move on to calling editDistance let’s take advantage of the composability of ST actions to add some heuristics to help make our spellchecking even faster:

Imagine that we wanted to have our spellchecker detect common variations of words and suggest the stem of the word. For example, if we found the word “eating” we would suggest “eat,” and if we found the word “jumps” we would suggest “jump.” One way that we can do that is to insert the corrections into our cache before we ever start running through our algorithm:

​  cacheSuffixDistances :: ​ MemoCache ​ s -> ​ Text ​ -> [​ Text ​] -> ​ ST ​ s ()
​  cacheSuffixDistances cache dictWord suffixes =
​  traverse_ cacheSuffix suffixes
​  ​ where ​
​  cacheSuffix suffix =
​  updateCache cache dictWord (dictWord <> suffix) (​ T ​.length suffix)

Now, when we want to spellcheck a word, we can add some suffixes:

​  spellcheckWord :: ​ MemoCache ​ s -> [​ Text ​] -> ​ Int ​ -> ​ Text ​ -> ​ ST ​ s [​ SuggestedMatch ​]
​  spellcheckWord cache dictionary threshold word =
​  foldM getSuggestions ​ [] ​ dictionary
​  ​ where ​
​  getSuggestions suggestions dictWord = ​ do ​
​  cacheSuffixDistances cache dictWord [​ "s" ​,​ "es" ​,​ "'s" ​,​ "ed" ​,​ "ing" ​]
​  distance <- editDistance cache dictWord word
​  ​ let ​
​  suggestion = ​ SuggestedMatch ​ dictWord word distance
​  ​ if ​ distance > 0 && distance <= threshold
​  ​ then ​ pure (suggestion : suggestions)
​  ​ else ​ pure suggestions

The last thing we need to do is add our spellchecking function. Up until now we’ve been creating ST actions, but thanks to runST we can make spellcheck a pure function, just like it is in our other implementations:

​  spellcheck :: [​ Text ​] -> ​ Int ​ -> [​ Text ​] -> [​ SuggestedMatch ​]
​  spellcheck dictionary threshold words = runST $ ​ do ​
​  cache <- newCache
​  concat <$> traverse (spellcheckWord cache dictionary threshold) words

Unfortunately, if you build and profile this version of our application, you’ll find that our new, more flexible version of spellchecking comes at a bit of a cost in both memory footprint and processing time. It’s not surprising that we’d have a large memory footprint now that we’re storing a single cache for all of our matches, but if we look at the profiling output we can see that we’re spending a substantial amount of time in both updateCache and readCache , with updateCache additionally taking up over half of our memory allocations. It seems that as convenient as our choice of data structure was for representing the cache, we’re paying a high cost for using a Map .

In the next section, we’ll look at how we can improve the performance of our programs using more efficient data structures, with a particular look at efficient vectors from the vectors package.