Memoization in Haskell
A State monad tutorial
Haskell provides a State monad, but it seems a bit too magical at times. There are many good introductions out there that try to derive the State monad from first principles, but they tend to focus on the "monad" part of it. Here I approach things from a different direction: as a solution to a practical problem.
i.e. this is the tutorial I wish I'd seen when I wanted to quickly learn how to use state monads.
The problem
We want to compute Fibonacci numbers. Before you start groaning, consider that this is a great example. We already know what the function should do, so we can focus on how to non-invasively memoizing functions that recursively call themselves. The approach we figure out will work for many recursive functions.
Let's start with a plain version
main :: IO ()
main = print $ fib 7
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
If you want to follow along hands on, copy paste this into a file, say fib.hs, and run it:
$ runghc fib.hs
13
From now I'll only mention the parts of the file that change, so you can keep modifying the same file and re-running the runghc fib.hs
command to see everything play out in action.
Let us memoize this. We want to create a table where we'll store the results of computing fib
for a particular number, so that when we're asked to compute the same fib
again, we don't do all that work again.
A more realistic way of doing this would use an array or a map to store the previous results, but I didn't want to distract from the essence of what we're discussing here, so let us just use a normal list. Each entry in the list will be a pair (n, fib n)
.
Such lists are quite common indeed, they turn out to be useful in all sorts of places, so much so that there is a name for them - they are called associative lists – and Haskell provides a function to quickly lookup a value in an associative list. That function is already part of prelude, and guess what, it's called lookup
. Here is an example of it in action (this is a ghci
prompt):
> lookup 7 [(1, "One"), (7, "Seven")]
Just "Seven"
Using this, we can create our memoized Fibonacci function:
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = let (r, _) = fibmemo n [] in r
type Cache = [(Int, Int)]
fibmemo :: Int -> Cache -> (Int, Cache)
fibmemo n s = case lookup n s of
Just v -> (v, s)
Nothing -> let r = fib (n - 1) + fib (n - 2)
in (r, (n, r) : s)
If you compile and run this, it'll still produce the correct result, but this version is completely buggy - there is no memoization happening!
Let's take a step back at this point. In almost all other languages, adding memoization is easy, we just plonk a global state somewhere, and we keep updating it as our function is called. This doesn't fly in Haskell, for very good reasons, but still it makes one wistful.
Already the memoized version in Haskell is starting to look messy, and it doesn't even work yet! But don't despair, we'll complicate this before we're able to make it simple again. Before enlightenment, carry wood chop water, after enlightenment, carry wood chop water.
So we'll just (for now) get rid of our concept of a separate "pure" fibonacci and a "memoized" layer on top - our implementation will have to mix these two concerns together. Here is a version that works:
main :: IO ()
main = print $ runFib 7
runFib :: Int -> (Int, Cache)
runFib n = fib n []
type Cache = [(Int, Int)]
fib :: Int -> Cache -> (Int, Cache)
fib 0 s = (0, s)
fib 1 s = (1, s)
fib n s = case lookup n s of
Just v -> (v, s)
Nothing -> let (r1, s1) = fib (n - 1) s
(r2, s2) = fib (n - 2) s1
r = r1 + r2
in (r, (n, r) : s)
Notice that we also return the Cache (which is our memo / lookup table) from the runFib
function. We'll eventually stop doing that and only return the result, but it is instructive to do that for now so that we can see both the result and the memoized values printed as we go about developing our solution.
$ runghc fib.hs
(13,[(7,13)])
Oh no! Our memo table is empty - it should have all the intermediate values, but it only has the last value – (7,13)
. Is our memoization still not working?
Turns out there is a small typo in the last line. (r, (n, r) : s)
should be (r, (n, r) : s2)
. Here is the fixed version of fib
:
fib :: Int -> Cache -> (Int, Cache)
fib 0 s = (0, s)
fib 1 s = (1, s)
fib n s = case lookup n s of
Just v -> (v, s)
Nothing -> let (r1, s1) = fib (n - 1) s
(r2, s2) = fib (n - 2) s1
r = r1 + r2
in (r, (n, r) : s2)
And if we run this again, we'll see that all intermediate entries are also present in our memoized table:
$ runghc fib.hs
(13,[(7,13),(6,8),(5,5),(4,3),(3,2),(2,1)])
This typo demonstrates how finicky and error prone it is to manually pass this state around. It gets worse with recursive functions, because we might not thread the state along one of the code paths accidentally, and everything will still work, just be dog slow.
Back to work. So what we've done here that instead of letting fib
be a function that takes an Int
and returns an Int
, we have made it into a function that takes an Int
and a Cache
, and returns an both the result Int
and (possibly) modified Cache
so that we can pass that along. Written as types, we have:
fib :: Int -> Cache -> (Int, Cache)
But the beauty of Haskell is that this same function signature can be interpreted in another way – fib
is a function that takes an Int
, and it returns a new function Cache -> (Int, Cache)
.
One thing that you might think here is that - shouldn't the arguments be the other way around? As in, how about if we'd written fib
this way:
fib :: Cache -> Int -> (Int, Cache)
We can even argue that this would make more logical sense. However, notice what happens if we want to memoize some two argument function, say plus
, in the future. If we'd done it in that hypothetically flipped way, it's type would look like:
plus :: Cache -> Int -> Int -> (Int, Cache)
In the way we're following, it's type would be
plus :: Int -> Int -> Cache -> (Int, Cache)
Notice how the trailing part of the type is the same! As in, keeping the state last means that we always return a Cache -> (Int, Cache)
, no matter how many arguments the original function that we're memoizing takes.
You might say that what if we want to memoize a function that returns something other than a Int
, or whose memo table has a different type like a Map
? Easy peasy, we can just parameterize these two types:
Let us call the type of the state as
s
.Let us call the result type as
a
.
So we end up with this pattern - any function that we want to memoize will take as many arguments, and of varying types, as it needs. The only requirement we place is that it should return a function of type s -> (a, s)
.
Such functions s -> (a, s)
are called the State monad. But we're getting ahead of ourselves with the "monad" part, forget that I said the m-word.
Let us just talk about values of type s -> (a, s)
. Trust me with this, and you'll see soon, that if we follow this convention – that any function that we want to memoize should return another function s -> (a, s)
– then it will become easy to compose them.
So that everyone doesn't go around defining their own typedefs and helper functions around this, the Haskell standard installation ships with this predefined. It is called a State
and is defined in the Control.Monad.State
module.
Note that the word "state" here refers to two different things. In general, state refers to anything that we want to automatically thread along our normal functions. The type
State
(capitalized one) is a shorthand for the "State monad".That is, the type
s -> (a, s)
is the "State monad" (and the Haskell type that refers to a "State monad" is calledState
). This type itself has two parameters -s
anda
. It is this lowercases
which is the actual state.Don't worry if this is confusing, that's why I kept this difference as an aside. It'll become clear once we complete our example.
So let us modify our code to use the standard library types:
import Control.Monad.State
main :: IO ()
main = print $ runFib 7
runFib :: Int -> (Int, Cache)
runFib n = (fib n) []
type Cache = [(Int, Int)]
fib :: Int -> State Cache Int
fib 0 = \s -> (0, s)
fib 1 = \s -> (1, s)
fib n = \s ->
case lookup n s of
Just v -> (v, s)
Nothing -> let (r1, s1) = (fib (n - 1)) s
(r2, s2) = (fib (n - 2)) s1
r = r1 + r2
in (r, (n, r) : s2)
Remember, State s a
(essentially) means s -> (a, s)
. So we've changed the type of fib
from Int -> Cache -> (Int, Cache)
to Int -> State Cache Int
. And it's implementation is changed from, say, fib 0 s = (0, s)
to fib 0 = \s -> (0, s)
to highlight that it is actually returning a function.
This doesn't actually compile though. When I said that State s a
essentially means s -> (a, s)
, I didn't lie, but there is a stress on essentially. Because the actual type of State
is a bit more complicated (for reasons that have nothing to do with what we're discussing here). To get this to compile, we have to make a few changes:
- Wrap the returned functions in a
StateT
. - Wrap the returned values from these functions in an
Identity
(this'll also require adding animport Control.Monad.Identity
at the top). - Wrap all calls to these functions in
runState
.
Don't despair if this is not making sense. It won't necessarily. Remember, it'll get complicated before it gets simple again. The reason it is getting so complicated in the middle is that this is not the way the state monad is used in practice, but to get to the simple way we'll need to wait till the end of this post.
Here is the fixed up code:
import Control.Monad.State
import Control.Monad.Identity
main :: IO ()
main = print $ runFib 7
runFib :: Int -> (Int, Cache)
runFib n = runState (fib n) []
type Cache = [(Int, Int)]
fib :: Int -> State Cache Int
fib 0 = StateT $ \s -> Identity (0, s)
fib 1 = StateT $ \s -> Identity (1, s)
fib n = StateT $ \s ->
case lookup n s of
Just v -> Identity (v, s)
Nothing -> let (r1, s1) = runState (fib (n - 1)) s
(r2, s2) = runState (fib (n - 2)) s1
r = r1 + r2
in Identity (r, (n, r) : s2)
We can now run this, and it'll give the result we expect.
$ runghc fib.hs
(13,[(7,13),(6,8),(5,5),(4,3),(3,2),(2,1)])
Alright, let us start simplifying this!
Monads!
Remember, "State" is a "monad". You don't need to really understand monads to follow along what's going to happen next - the tl;dr; you can keep in mind is that if something is a monad, then there are special functions that we can use to compose values of such types.
The first such function is pure
. It represents the "simplest" version of a particular value. In our case, what is the simplest value of type s -> (a, s)
. Well, it just needs to return the a
and not twiddle with the state. But how do we get an a
? We pass it to pure
!
-- Snipped for illustrative purposes
pure x = \s -> (x, s)
We can use pure
to simplify the first two clauses of our function definition.
fib 0 = pure 0
fib 1 = pure 1
If we run the code again after making that change, it'll still give the same result. That's weird, where did all the surrounding junk go!
It might seem like magic, or something that has a special case in the compiler, but no, this is all a library level abstraction. Haskell is a gift that'll keep giving.
Let's continue.
The other pattern that monads support is combining two values. Do something, take its output, and then something 2 with it. Like a factory line:
something → something 2. Cheeky as Haskellers are, they even created an arrow like symbol for this: >>=
. It is called "bind". What it does is, take the output of the first monad, and feeds it to a function that then something else with this value to modify it.
Again, my purpose here is not to explain monads. The monad tutorial fallacy is real. You might already have a basic understanding of monads, in which case this post should help you understand and use the state monad. The above explanations are for people who don't have the basic understanding of monads.
To such people, I'd say - just keep using them. It'll click. Reading about them doesn't help beyond a certain point.
So let use this bind >>=
operator to chain together our steps:
fib :: Int -> State Cache Int
fib 0 = pure 0
fib 1 = pure 1
fib n = StateT $ \s ->
case lookup n s of
Just v -> Identity (v, s)
Nothing -> runStateT (fib (n - 1)) s >>= \(r1, s1) ->
runStateT (fib (n - 2)) s1 >>= \(r2, s2) ->
let r = r1 + r2
in Identity (r, (n, r) : s2)
I also had to replace runState
with runStateT
(Don't fixate too much on the meaning behind these details and infelicities – in our final version we'll not be using any of them).
We can run our code again, and see that it still works the same way. To simplify further, we'll need to start getting into the specific tools provided by the state monad itself (above and beyond generic monads).
The State monad
The first thing to notice is at the top of fib
fib n = StateT $ \s ->
case lookup n s of
...
As you can imagine, this'll be a common requirement for functions that deal with state – read the current value of the state. Of course, the value of the state is getting passed to us right there, as an input to our function. But we want to "hide" it away so that it is not always in our face, and somehow access that value when we need it.
The State monad library provides a function for this task. It is called get
. When we call get
, we don't actually get back a value, we get back a state monad. However, we already know how to extract values from a monad – by using the bind operator >>=
. Let's change our function to use get
.
fib n = get >>= \s ->
case lookup n s of
If we make this change, I'll code will stop compiling though. This is because we no longer have a regular function that was wrapped in a StateT
, instead the code we're writing (case lookup ...
) now has to return another state monad to satisfy the type of >>=
.
To get the compiler to be happy, the code needs to be changed to:
Remove
Identity
, and also the tuples with s, and just return the value directly wrapped in apure
.Remove the
runStateT
and stop passing the state to fib, instead just return the fib values themselves (Reminder thatfib x
is a value of typeState Cache Int
, which is a state monad, which is what we should be passing into and returning from>>=
).
I'm not sure how helpful this is being – for people who don't have the necessary background these might be arbitrary changes. I'll think of better ways of conveying this in the future, but hopefully some of this is sticking.
With these changes, our code becomes:
fib :: Int -> State Cache Int
fib 0 = pure 0
fib 1 = pure 1
fib n = get >>= \s ->
case lookup n s of
Just v -> pure v
Nothing -> fib (n - 1) >>= \r1 ->
fib (n - 2) >>= \r2 ->
let r = r1 + r2
in pure r
This runs, and produces the correct answer, but our memoization is gone. Of course. We're only reading the state s, but we're never updating it. The code looks cleaner, there is no s moving around, but how do we update it now if we don't have access to it as the input and are not returning it as the output.
For this purpose, Control.Monad.State
provides another function that returns a new state monad, but with an updated state. This function is called put
. Let us use it to update our state before we return the final result r of our expression.
I think keeping in mind that these are just ordinary expressions, and the result of an of the expression is result of the branch that we ended up on, helps demystify Haskell in general, and monads in particular.
fib :: Int -> State Cache Int
fib 0 = pure 0
fib 1 = pure 1
fib n = get >>= \s ->
case lookup n s of
Just v -> pure v
Nothing -> fib (n - 1) >>= \r1 ->
fib (n - 2) >>= \r2 ->
let r = r1 + r2
in put ((n, r) : s) >>= \_ ->
pure r
In the final result, we're not actually using the value chained from the put, which is why we ignore it using the underscore wildcard. This is a common thing - sometimes we just want two things to happen one after the other, but the second thing doesn't use the result of the first. It is so common, that the Haskell standard library provides a sequence operator >>
to shorten this >>= \_ ->
pattern.
So after changing the last two lines to
in put ((n, r) : s) >>
pure r
if we run the code again,
$ runghc fib.hs
(13,[(7,13)])
this time we see that while the state was used, it only contains the table of the last value, not the intermediate ones.
Perhaps you've already guessed the issue. When we're updating the state using put
, we're using the value s
that we got from the initial get
. But remember, Haskell is a pure functional language. There is no mutation, in fact, there are no variables - the only things we have are bindings. These are not variables, because they never change, they are just names for things that were on the call stack.
In our case, when we recursively call fib, the recursive calls will update the state using put
. They'll use the correct state to put
into, because we've been chaining these state monads together using >>=
and the library is taking care that state that was set by the latest put
is the one that is carried along the chain.
However, when we get back to the original function (that called the recursive invocations), we overwrite the state using an old s
value that doesn't include the latest changes made by the put
s in the recursive calls.
The fix is simple. We need to get
again when put
ting, so that we update the latest value.
fib n = get >>= \s ->
case lookup n s of
Just v -> pure v
Nothing -> fib (n - 1) >>= \r1 ->
fib (n - 2) >>= \r2 ->
let r = r1 + r2
in get >>= \s2 ->
put ((n, r) : s) >>
pure r
After this change, if we run again, we'll notice all the intermediate values showing up in our cache (memo) table.
$ runghc fib.hs
(13,[(7,13),(6,8),(5,5),(4,3),(3,2),(2,1)])
As you might imagine, this is a very common requirement - get
ting the latest state and modifying it in some way and then put
ting it back - so Control.Monad.State
provides a convenience function for this combination. It is called, hold your breath, modify
. Using it, our code becomes:
fib n = get >>= \s ->
case lookup n s of
Just v -> pure v
Nothing -> fib (n - 1) >>= \r1 ->
fib (n - 2) >>= \r2 ->
let r = r1 + r2
in modify ((n, r) :) >>
pure r
Similarly, but in the other direction, at the start of our function we got the state, but we weren't really interested in the full state, we wanted some particular part of it. So there is a function called gets
to query the state using the provided query function, and only give us the result. We can use it to directly perform our lookup this way:
fib :: Int -> State Cache Int
fib 0 = pure 0
fib 1 = pure 1
fib n = gets (lookup n) >>= \s -> case s of
Just v -> pure v
Nothing -> fib (n - 1) >>= \r1 ->
fib (n - 2) >>= \r2 ->
let r = r1 + r2
in modify ((n, r) :) >>
pure r
Alright! Let's move on to the next stage of our simplification.
Abstracting memoize
At this point (or even before this), the other tutorials I've seen move on to using the do
notation to further simplify things. I feel that is a misstep, because the do
notation obscures the fact that everything in Haskell is just an expression. If we stay in expression-land, things might get nested and hairy, but it also becomes easier to visually see and then extract common patterns into reusable abstractions.
This is not to say one should never use
do
. Sometimes it is fine, and it is perhaps even a personal preference.
Instead of do
, I'm going to go off in the weeds in the other direction, and start lifting stuff. The word "lift" in Haskell comes from category theory, specifically functors, and it means that a normal function a -> b
is "lifted" into another universe f a -> f b
.
Apologies for the hand wavey explanation here, but trying to explain lifting in more detail would sidetrack too much from the focus here. For our specific use case, the thing I want you to be aware of is that this code:
fib (n - 1) >>= \r1 ->
fib (n - 2) >>= \r2 ->
let r = r1 + r2
is the same as this code:
liftM2 (+) (fib (n - 1)) (fib (n - 2)) >>= \r ->
That is, we're "lifting" the normal plus operator (+) from acting on Int
values, to get them to act on State Cache Int
values. How Haskell does that is not essential to know for our purposes here, just that Haskell can automatically do it for us.
So using liftM2
, our code becomes:
fib n = gets (lookup n) >>= \s -> case s of
Just v -> pure v
Nothing -> liftM2 (+) (fib (n - 1)) (fib (n - 2)) >>= \r ->
modify ((n, r) :) >> pure r
It still runs, and produces the same output as before.
Now comes the great jump. We notice that only some part of our fib
function deals with the actual computation, while the rest of it is checking to see if we already have that cached result. We can make this distinction more apparent by rewriting the fib function this way:
fib n = gets (lookup n) >>= \s -> case s of
Just v -> pure v
Nothing -> compute >>= \r -> modify ((n, r) :) >> pure r
where compute = liftM2 (+) (fib (n - 1)) (fib (n - 2))
In fact, we can just pass compute
as a parameter!
fib :: Int -> State Cache Int
fib 0 = pure 0
fib 1 = pure 1
fib n = memo n compute
where compute = liftM2 (+) (fib (n - 1)) (fib (n - 2))
memo :: Int -> State Cache Int -> State Cache Int
memo n compute = gets (lookup n) >>= \s -> case s of
Just v -> pure v
Nothing -> compute >>= \r -> modify ((n, r) :) >> pure r
In fact, this same memo will work with all other types of state monads, not just the State Cache Int
. The requirement is that the state should be such that we can lookup n
and (n, r) :
on it, but otherwise we can generalize the type signature.
We can replace the liftM2
by the more standard, so called, applicative style (+) <$> fib (n - 1) <*> fib (n - 2)
. We can also move the memo upwards so that it also covers the base cases:
fib :: Int -> State Cache Int
fib n = memo n (f n) where
f 0 = pure 0
f 1 = pure 1
f n = (+) <$> fib (n - 1) <*> fib (n - 2)
We can also use the LambdaCase
language extension to remove the noise in the implementation of memo. With all these changes, our code looks like this:
{-# LANGUAGE LambdaCase #-}
import Control.Monad.State
main :: IO ()
main = print $ runFib 7
runFib :: Int -> (Int, Cache)
runFib n = runState (fib n) []
type Cache = [(Int, Int)]
fib :: Int -> State Cache Int
fib n = memo n (f n) where
f 0 = pure 0
f 1 = pure 1
f n = (+) <$> fib (n - 1) <*> fib (n - 2)
memo :: (MonadState [(a, b)] m, Eq a) => a -> m b -> m b
memo n compute = gets (lookup n) >>= \case
Just v -> pure v
Nothing -> compute >>= \r -> modify ((n, r) :) >> pure r
We can run it again to ensure that everything looks good:
$ runghc fib.hs
(13,[(7,13),(6,8),(5,5),(4,3),(3,2),(2,1)])
Finally, since now that we know that the memoization is working, we don't need to see those intermediate values. We can modify our runFib
method to return only the first element of the tuple, say:
runFib n = fst $ runState (fib n) []
But there is a helper function for doing this too - evalState
. It is like runState
, except it throws away the state and only returns the final result.
runFib :: Int -> Int
runFib n = evalState (fib n) []
Let's see it in action.
$ runghc fib.hs
13
Nice.
More to memoization
We've reached quite an okay point. We started with this beauty:
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n - 1) + fib (n - 2)
and have ended up with:
fib :: Int -> State Cache Int
fib n = memo n (f n) where
f 0 = pure 0
f 1 = pure 1
f n = (+) <$> fib (n - 1) <*> fib (n - 2)
Not great, but not too bad. The second version implicitly memoizes all function calls under the hood, and for problems where memoization is of essence, this is an okay price to pay for the functionality we get. Indeed, even for the simple case of our fib
function, and for (relatively) small values of n - the difference in time is functionally (pun!) important (try running fib 700
in both cases - the first one goes nowhere while the second is instant).
Hope you found this useful.