From HaskellWiki
Revision as of 22:44, 20 September 2010 by Ertes (talk | contribs) (Introduction: Fixed wiki markup typo.)
Jump to: navigation, search


The contstuff library implements a number of monad transformers and monads, which make heavy use of continuation passing style (CPS). This makes them both fast and flexible. Please note that this is neither a CPS tutorial nor a monad transformer tutorial. You should understand these concepts, before attempting to use contstuff.


The ContT monad transformer is the simplest of all CPS-based monads. It essentially gives you access to the current continuation, which means that it lets you label certain points of execution and reuse these points later in interesting ways. With ContT you get an elegant encoding of computations, which support:

  • abortion (premature termination),
  • resumption (start a computation at a certain spot),
  • branches (aka goto),
  • result accumulation,
  • etc.

All these features are effects of ContT. If you don't use them, then ContT behaves like the identity monad. A computation of type ContT r m a is a CPS computation with an intermediate result of type a and a final result of type r. The r type can be polymorphic most of the time. You only need to specify it, if you use some of the CPS effects like abort. Let's have a look at a small example:

testComp1 :: ContT () IO ()
testComp1 =
  forever $ do
    txt <- io getLine
    case txt of
      "info" -> io $ putStrLn "This is a test computation."
      "quit" -> abort ()
      _      -> return ()

This example demonstrates the most basic feature of ContT. First of all, ContT is a monad transformer, so you can for example lift IO actions to a CPS computation. The io function is a handy tool, which corresponds to liftIO from other transformer libraries and to inBase from monadLib, but is restricted to the IO monad. You can also use the more generic base function, which promotes a base monad computation to ContT.

Each ContT subcomputation receives a continuation, which is a function, to which the subcomputation is supposed to pass the result. However, the subcomputation may choose not to call the continuation at all, in which case the entire computation finishes with a final result. The abort function does that.

To run a ContT computation you can use runContT or the convenience function evalContT:

runContT  :: (a -> m r) -> ContT r m a -> m r
evalContT :: Applicative m => ContT r m r -> m r

The runContT function takes a final continuation transforming the last intermediate result into a final result. The evalContT function simply passes pure as the final continuation.