What is the use of the Mon Mon instance?

I play with CPS and Control.Monad.Cont and wonder what we get when we notice the monadic structure. For this code:

 sumOfSquares'cps :: Cont r Int -> Cont r Int -> Cont r Int sumOfSquares'cps xy = x >>= \x' -> y >>= \y' -> return (x'*x' + y'*y') 

It can be easily rewritten as

 type Cont' ra = (a -> r) -> r sos'cps :: Cont' r Int -> Cont' r Int -> Cont' r Int sos'cps xy = \k -> x $ \x' -> y $ \y' -> k (x'*x' + y'*y') 

Do not get me wrong, but I don’t see the feeling here, except for the ability to use the do and newtype notation. I don't think callCC depends on the monad instance.

I do not have enough imagination to give an example. What do we really get for declaring a Cont r monad?

+7
haskell monads continuation-passing
source share
2 answers

You can ask the same question about any Monad . From head to toe, I can imagine three benefits:

  • You get access to a huge collection of features that are designed to work with Monad s.
  • You can use do notation.
  • You can stack monodata transformers to create something more powerful.

It also allows you to better talk about your code, as you can rely on identity and associative properties, etc.

+9
source share

One obvious advantage is that you can use combinators defined for Monads (and Functors ). For example, your function could be written using liftM2 :

 sumOfSquares'cps :: Cont r Int -> Cont r Int -> Cont r Int sumOfSquares'cps = liftM2 sumSquares where sumSquares xy = x * x + y * y 

this function does not rely on the Cont monad and can be written with a more general type, for example.

 sumOfSquaresM :: Monad m => m Int -> m Int -> m Int 
+6
source share

All Articles