Someone in the #haskell IRC channel mentioned the “reverse state monad” explaining that it used the state from the next computation and passed it to the previous one. Well, I just had to try this!

First, a demonstration: we will compute the fibonacci numbers by starting with them and mapping them back to the empty list.

-- cumulativeSums [1,2,3,4,5] = [0,1,3,6,10,15] cumulativeSums = scanl (+) 0 computeFibs = evalRState [] $ do -- here the state is what we want: the fibonacci numbers fibs <- get modify cumulativeSums -- now the state is the difference sequence of -- fibs, [1,0,1,1,2,3,5,8,13,...], because the -- cumulativeSums of that sequence is fibs. Notice -- that this sequence is the same as 1:fibs, so -- just put that to get here. put (1:fibs) -- And here the state is empty (or whatever else -- we want it to be, because we just overwrite it on -- the previous line -- but we defined it to be -- empty on the evalRState line) return fibs

And sure enough:

>>> take 15 computeFibs [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377]

And now the implementation:

newtype RState s a = RState { runRState :: s -> (a,s) } evalRState s f = fst (runRState f s) instance Monad (RState s) where return x = RState $ (,) x RState sf >>= f = RState $ \s -> let (a,s'') = sf s' (b,s') = runRState (f a) s in (b,s'') get = RState $ \s -> (s,s) modify f = RState $ \s -> ((),f s) put = modify . const

The important part is the definition of (>>=) . Notice how the data (a,b) flows forward, but the state (s,s’,s”) flows backward.