Ticket #1169: Cont.2.hs

File Cont.2.hs, 7.5 KB (added by guest, 7 years ago)

Version 4 of the module source. Accomodated latest Cont changes.

Line 
1{-# OPTIONS -fallow-undecidable-instances #-}
2-- Search for -fallow-undecidable-instances to see why this is needed
3
4{- |
5Module      :  Control.Monad.Cont
6Copyright   :  (c) The University of Glasgow 2001,
7               (c) Jeff Newbern 2003-2007,
8               (c) Andriy Palamarchuk 2007
9License     :  BSD-style (see the file libraries/base/LICENSE)
10
11Maintainer  :  libraries@haskell.org
12Stability   :  experimental
13Portability :  non-portable (multi-parameter type classes)
14
15[Computation type:] Computations which can be interrupted and resumed.
16
17[Binding strategy:] Binding a function to a monadic value creates
18a new continuation which uses the function as the continuation of the monadic
19computation.
20
21[Useful for:] Complex control structures, error handling,
22and creating co-routines.
23
24[Zero and plus:] None.
25
26[Example type:] @'Cont' r a@
27
28The Continuation monad represents computations in continuation-passing style
29(CPS).
30In continuation-passing style function result is not returned,
31but instead is passed to another function,
32received as a parameter (continuation).
33Computations are built up from sequences
34of nested continuations, terminated by a final continuation (often @id@)
35which produces the final result.
36Since continuations are functions which represent the future of a computation,
37manipulation of the continuation functions can achieve complex manipulations
38of the future of the computation,
39such as interrupting a computation in the middle, aborting a portion
40of a computation, restarting a computation, and interleaving execution of
41computations.
42The Continuation monad adapts CPS to the structure of a monad.
43
44Before using the Continuation monad, be sure that you have
45a firm understanding of continuation-passing style
46and that continuations represent the best solution to your particular
47design problem.
48Many algorithms which require continuations in other languages do not require
49them in Haskell, due to Haskell's lazy semantics.
50Abuse of the Continuation monad can produce code that is impossible
51to understand and maintain.
52-}
53
54module Control.Monad.Cont (
55    module Control.Monad.Cont.Class,
56    Cont(..),
57    mapCont,
58    withCont,
59    ContT(..),
60    mapContT,
61    withContT,
62    module Control.Monad,
63    module Control.Monad.Trans,
64    -- * Example 1: Simple Continuation Usage
65    -- $simpleContExample
66
67    -- * Example 2: Using @callCC@
68    -- $callCCExample
69   
70    -- * Example 3: Using @ContT@ Monad Transformer
71    -- $ContTExample
72  ) where
73
74import Control.Monad
75import Control.Monad.Cont.Class
76import Control.Monad.Reader.Class
77import Control.Monad.State.Class
78import Control.Monad.Trans
79
80{- |
81Continuation monad.
82@Cont r a@ is a CPS computation that produces an intermediate result
83of type @a@ within a CPS computation whose final result type is @r@.
84
85The @return@ function simply creates a continuation which passes the value on.
86
87The @>>=@ operator adds the bound function into the continuation chain.
88-}
89newtype Cont r a = Cont {
90
91    {- | Runs a CPS computation, returns its result after applying
92    the final continuation to it.
93    Parameters:
94
95    * a continuation computation (@Cont@).
96
97    * the final continuation, which produces the final result (often @id@).
98    -}
99    runCont :: (a -> r) -> r
100}
101
102mapCont :: (r -> r) -> Cont r a -> Cont r a
103mapCont f m = Cont $ f . runCont m
104
105withCont :: ((b -> r) -> (a -> r)) -> Cont r a -> Cont r b
106withCont f m = Cont $ runCont m . f
107
108instance Functor (Cont r) where
109    fmap f m = Cont $ \c -> runCont m (c . f)
110
111instance Monad (Cont r) where
112    return a = Cont ($ a)
113    m >>= k  = Cont $ \c -> runCont m $ \a -> runCont (k a) c
114
115instance MonadCont (Cont r) where
116    callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a)) c
117
118{- |
119The continuation monad transformer.
120Can be used to add continuation handling to other monads.
121-}
122newtype ContT r m a = ContT { runContT :: (a -> m r) -> m r }
123
124mapContT :: (m r -> m r) -> ContT r m a -> ContT r m a
125mapContT f m = ContT $ f . runContT m
126
127withContT :: ((b -> m r) -> (a -> m r)) -> ContT r m a -> ContT r m b
128withContT f m = ContT $ runContT m . f
129
130instance (Monad m) => Functor (ContT r m) where
131    fmap f m = ContT $ \c -> runContT m (c . f)
132
133instance (Monad m) => Monad (ContT r m) where
134    return a = ContT ($ a)
135    m >>= k  = ContT $ \c -> runContT m (\a -> runContT (k a) c)
136
137instance (Monad m) => MonadCont (ContT r m) where
138    callCC f = ContT $ \c -> runContT (f (\a -> ContT $ \_ -> c a)) c
139
140-- ---------------------------------------------------------------------------
141-- Instances for other mtl transformers
142
143instance MonadTrans (ContT r) where
144    lift m = ContT (m >>=)
145
146instance (MonadIO m) => MonadIO (ContT r m) where
147    liftIO = lift . liftIO
148
149-- Needs -fallow-undecidable-instances
150instance (MonadReader r' m) => MonadReader r' (ContT r m) where
151    ask       = lift ask
152    local f m = ContT $ \c -> do
153        r <- ask
154        local f (runContT m (local (const r) . c))
155
156-- Needs -fallow-undecidable-instances
157instance (MonadState s m) => MonadState s (ContT r m) where
158    get = lift get
159    put = lift . put
160
161{- $simpleContExample
162Calculating length of a list continuation-style:
163
164>calculateLength :: [a] -> Cont r Int
165>calculateLength l = return (length l)
166
167Here we use @calculateLength@ by making it to pass its result to @print@:
168
169>main = do
170>  runCont (calculateLength "123") print
171>  -- result: 3
172
173It is possible to chain 'Cont' blocks with @>>=@.
174
175>double :: Int -> Cont r Int
176>double n = return (n * 2)
177>
178>main = do
179>  runCont (calculateLength "123" >>= double) print
180>  -- result: 6
181-}
182
183{- $callCCExample
184This example gives a taste of how escape continuations work, shows a typical
185pattern for their usage.
186
187>-- Returns a string depending on the length of the name parameter.
188>-- If the provided string is empty, returns an error.
189>-- Otherwise, returns a welcome message.
190>whatsYourName :: String -> String
191>whatsYourName name =
192>  (`runCont` id) $ do                      -- 1
193>    response <- callCC $ \exit -> do       -- 2
194>      validateName name exit               -- 3
195>      return $ "Welcome, " ++ name ++ "!"  -- 4
196>    return response                        -- 5
197>
198>validateName name exit = do
199>  when (null name) (exit "You forgot to tell me your name!")
200
201Here is what this example does:
202
203(1) Runs an anonymous 'Cont' block and extracts value from it with
204@(\`runCont\` id)@. Here @id@ is the continuation, passed to the @Cont@ block.
205
206(1) Binds @response@ to the result of the following 'callCC' block,
207binds @exit@ to the continuation.
208
209(1) Validates @name@.
210This approach illustrates advantage of using 'callCC' over @return@.
211We pass the continuation to @validateName@,
212and interrupt execution of the @Cont@ block from /inside/ of @validateName@.
213
214(1) Returns the welcome message from the @callCC@ block.
215This line is not executed if @validateName@ fails.
216
217(1) Returns from the @Cont@ block.
218-}
219
220{-$ContTExample
221'ContT' can be used to add continuation handling to other monads.
222Here is an example how to combine it with @IO@ monad:
223
224>import Control.Monad.Cont
225>import System.IO
226>
227>main = do
228>  hSetBuffering stdout NoBuffering
229>  runContT (callCC askString) reportResult
230>
231>askString :: (String -> ContT () IO String) -> ContT () IO String
232>askString next = do
233>  liftIO $ putStrLn "Please enter a string"
234>  s <- liftIO $ getLine
235>  next s
236>
237>reportResult :: String -> IO ()
238>reportResult s = do
239>  putStrLn ("You entered: " ++ s)
240
241Action @askString@ requests user to enter a string,
242and passes it to the continuation.
243@askString@ takes as a parameter a continuation taking a string parameter,
244and returning @IO ()@.
245Compare its signature to 'runContT' definition.
246-}