Skip to content

Commit 6b404b0

Browse files
committed
Merge pull request #70 from parsonsmatt/cont
Add Cont monad
2 parents b77bce1 + 5c01fae commit 6b404b0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/Control/Monad/Cont.purs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
-- | This module defines the `Cont`inuation monad.
2+
3+
module Control.Monad.Cont
4+
( Cont
5+
, cont
6+
, runCont
7+
, module X
8+
) where
9+
10+
import Prelude
11+
12+
import Control.Monad.Cont.Trans (ContT(ContT), mapContT, runContT, withContT)
13+
import Control.Monad.Cont.Class (callCC) as X
14+
import Data.Identity (Identity(Identity), runIdentity)
15+
16+
-- | The `Cont` monad is a synonym for the `ContT` monad transformer applied to
17+
-- | the `Identity` monad.
18+
type Cont r a = ContT r Identity a
19+
20+
-- | Creates a computation in the `Cont` monad.
21+
cont :: forall a r. ((a -> r) -> r) -> Cont r a
22+
cont f = ContT (\c -> Identity (f (runIdentity <<< c)))
23+
24+
-- | Runs a computation in the `Cont` monad.
25+
runCont :: forall r a. ContT r Identity a -> (a -> r) -> r
26+
runCont cc k = runIdentity (runContT cc (Identity <<< k))
27+
28+
-- | Transform the result of a continuation-passing function.
29+
mapCont :: forall r a. (r -> r) -> Cont r a -> Cont r a
30+
mapCont f = mapContT (Identity <<< f <<< runIdentity)
31+
32+
-- | Transform the continuation passed into the continuation-passing function.
33+
withCont :: forall a b r. ((b -> r) -> (a -> r)) -> Cont r a -> Cont r b
34+
withCont f = withContT (compose Identity <<< f <<< compose runIdentity)

0 commit comments

Comments
 (0)