# User:Benmachine/Cont

### From HaskellWiki

< User:Benmachine(Difference between revisions)

Benmachine (Talk | contribs) |
Benmachine (Talk | contribs) |

## Revision as of 22:23, 19 January 2012

I found a bug with the <hask> tag. I put it on its own page so it doesn't ruin my user page.

It seems to me likeCont

ContT

contstuff :: Magic a contstuff = do thing1 thing2 -- Here I want to manipulate the rest of the computation. -- So I want a magic function that will give me the rest of it to -- play with. magic $ \rest -> -- Now I can just do it (tm), or do it twice, or discard it, or -- do it and then use the result to do it again... it's easy to -- imagine why this might be useful. thing3

magic

r

magic

r

r

magic

x <- magic $ \rest -> -- ... thingInvolving x

x

magic

a -> r

r

(a -> r) -> r

magic :: (a -> r) -> r -> Magic a

Magic a = Cont r a magic = Cont

Tada!

The thing withCont

Functor

instance Functor (Cont r) where fmap f (Cont g) = -- ...

Cont

fmap f (Cont g) = Cont $ \rest -> -- ...

g

\rest -> stuffWith (rest val)

val

<-

rest

f

fmap f (Cont g) = Cont $ \rest -> g (\val -> rest (f val))

Applicative

instance Applicative (Cont r) where pure x = Cont $ \rest -> -- ...

We don't want to do anything special here. The rest of the computation wants a value, let's just give it one:

pure x = Cont $ \rest -> rest x

<*>

Cont f <*> Cont x = Cont $ \rest -> -- ...

fmap

Cont f <*> Cont x = Cont $ \rest -> f (\fn -> x (\val -> rest (fn val)))

Monad

runCont

case

let

### What about ContT?

The thing withContT

*think*the following definition works fine:

newtype ContT r m a = ContT (Cont (m r) a) deriving (Functor, Applicative, Monad) runContT :: ContT r m a -> (a -> m r) -> m r runContT (ContT m) = runCont m

MonadTrans