https://wiki.haskell.org/api.php?action=feedcontributions&user=Ods94043&feedformat=atomHaskellWiki - User contributions [en]2021-01-26T00:25:14ZUser contributionsMediaWiki 1.27.4https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36353MonadCont under the hood2010-07-26T00:29:28Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Basic Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>f1 -> f2 -> f3</hask>, and let's say you had a continuation <hask>c3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>f3</hask> needs to invoke <hask>c3</hask> when it's done.<br />
* <hask>f2</hask> needs to invoke a continuation <hask>c2</hask> that will invoke <hask>f3</hask>, which will invoke <hask>c3</hask>.<br />
* <hask>f1</hask> needs to invoke a continuation <hask>c1</hask>,<br/>&nbsp;which will invoke <hask>f2</hask>,<br/>&nbsp;&nbsp;which will invoke <hask>c2</hask>,<br/>&nbsp;&nbsp;&nbsp;which will invoke <hask>f3</hask>,<br/>&nbsp;&nbsp;&nbsp;&nbsp;which will finally invoke <hask>c3</hask>.<br />
<br />
To chain the <hask>Cont</hask> objects together, then, we need to create the appropriate continuation functions <hask>c1</hask> and <hask>c2</hask> and make sure they get passed as the continuation argument to <hask>f1</hask> and <hask>f2</hask> respectively.<br />
<br />
==Extending to Monad==<br />
Extending this idea to the <hask>Monad</hask> class in general, there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* The bind operator <hask>(>>=)</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
Thus, <hask>return</hask> in the <hask>Cont</hask> monad passes the result of its computation directly to the continuation it's given.<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? <hask>(k a)</hask> has become part of the continuation that <hask>m</hask> is given, and <hask>m</hask> passes its value to <hask>k</hask> by simply passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' The sequence of terms <hask>runCont Cont $</hask> effectively cancel out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
doC = let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
If you changed doC to <hask>return 4 >>= h</hask>, the derivation would be almost identical to the above, except that 4 would pass through to h, which would unfold to g instead. "Done: 2" should be the result.<br />
<br />
=MonadCont and callCC= <br />
One final extension to this monad, which can be extremely useful in practice, is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes a function to construct a <hask>Cont</hask> object, and then runs it with the continuation it's given. However, it provides that function an ''alternate'' continuation that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask> is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36352MonadCont under the hood2010-07-26T00:28:56Z<p>Ods94043: Rewriting "basic sequencing" section to remove misleading references to "applicative"</p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Basic Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>f1 -> f2 -> f3</hask>, and let's say you had a continuation <hask>c3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>f3</hask> needs to invoke <hask>c3</hask> when it's done.<br />
* <hask>f2</hask> needs to invoke a continuation <hask>c2</hask> that will invoke <hask>f3</hask>, which will invoke <hask>c3</hask>.<br />
* <hask>f1</hask> needs to invoke a continuation <hask>c1</hask>,<br/>&nbsp;which will invoke <hask>f2</hask>,<br/>&nbsp;&nbsp;which will invoke <hask>c2</hask>,<br/>&nbsp;&nbsp;&nbsp;which will invoke <hask>f3</hask>,<br/>&nbsp;&nbsp;&nbsp;&nbsp;which will finally invoke <hask>c3</hask>.<br />
<br />
To chain the <hask>Cont</hask> objects together, then, we need to create the appropriate continuation functions <hask>c1</hask> and <hask>c2</hask>. and make sure they get passed as the continuation argument to <hask>f1</hask> and <hask>f2</hask> respectively.<br />
<br />
==Extending to Monad==<br />
Extending this idea to the <hask>Monad</hask> class in general, there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* The bind operator <hask>(>>=)</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
Thus, <hask>return</hask> in the <hask>Cont</hask> monad passes the result of its computation directly to the continuation it's given.<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? <hask>(k a)</hask> has become part of the continuation that <hask>m</hask> is given, and <hask>m</hask> passes its value to <hask>k</hask> by simply passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' The sequence of terms <hask>runCont Cont $</hask> effectively cancel out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
doC = let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
If you changed doC to <hask>return 4 >>= h</hask>, the derivation would be almost identical to the above, except that 4 would pass through to h, which would unfold to g instead. "Done: 2" should be the result.<br />
<br />
=MonadCont and callCC= <br />
One final extension to this monad, which can be extremely useful in practice, is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes a function to construct a <hask>Cont</hask> object, and then runs it with the continuation it's given. However, it provides that function an ''alternate'' continuation that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask> is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36338MonadCont under the hood2010-07-24T03:33:19Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask> when it's done.<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask>,<br/>&nbsp;which will invoke <hask>F2</hask>,<br/>&nbsp;&nbsp;which will invoke <hask>C2</hask>,<br/>&nbsp;&nbsp;&nbsp;which will invoke <hask>F3</hask>,<br/>&nbsp;&nbsp;&nbsp;&nbsp;which will finally invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* The bind operator <hask>(>>=)</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
Thus, <hask>return</hask> in the <hask>Cont</hask> monad passes the result of its computation directly to the continuation it's given.<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? <hask>(k a)</hask> has become part of the continuation that <hask>m</hask> is given, and <hask>m</hask> passes its value to <hask>k</hask> by simply passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' The sequence of terms <hask>runCont Cont $</hask> effectively cancel out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
doC = let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
If you changed doC to <hask>return 4 >>= h</hask>, the derivation would be almost identical to the above, except that 4 would pass through to h, which would unfold to g instead. "Done: 2" should be the result.<br />
<br />
=MonadCont and callCC= <br />
One final extension to this monad, which can be extremely useful in practice, is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes a function to construct a <hask>Cont</hask> object, and then runs it with the continuation it's given. However, it provides that function an ''alternate'' continuation that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask> is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36337MonadCont under the hood2010-07-24T03:21:25Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask> when it's done.<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask>,<br/>&nbsp;which will invoke <hask>F2</hask>,<br/>&nbsp;&nbsp;which will invoke <hask>C2</hask>,<br/>&nbsp;&nbsp;&nbsp;which will invoke <hask>F3</hask>,<br/>&nbsp;&nbsp;&nbsp;&nbsp;which will finally invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* The bind operator <hask>(>>=)</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
Thus, <hask>return</hask> in the <hask>Cont</hask> monad passes the result of its computation directly to the continuation it's given.<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? <hask>(k a)</hask> has become part of the continuation that <hask>m</hask> is given, and <hask>m</hask> passes its value to <hask>k</hask> by simply passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' The sequence of terms <hask>runCont Cont $</hask> effectively cancel out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes a function to construct a <hask>Cont</hask> object, and then runs it with the continuation it's given. However, it provides that function an ''alternate'' continuation that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask> is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36336MonadCont under the hood2010-07-24T03:20:30Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask> when it's done.<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask>,<br/>&nbsp;which will invoke <hask>F2</hask>,<br/>&nbsp;&nbsp;which will invoke <hask>C2</hask>,<br/>&nbsp;&nbsp;&nbsp;which will invoke <hask>F3</hask>,<br/>&nbsp;&nbsp;&nbsp;&nbsp;which will finally invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* The bind operator <hask>(>>=)</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
Thus, <hask>return</hask> in the <hask>Cont</hask> monad passes the result of its computation directly to the continuation it's given.<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? <hask>(k a)</hask> has become part of the continuation that <hask>m</hask> is given, and <hask>m</hask> passes its value to <hask>k</hask> by simply passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' The sequence of terms <hask>runCont Cont $</hask> effectively cancel out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes a function to construct a <hask>Cont</hask> object, and then runs it with the continuation it's given. However, it provides that function an ''alternate'' continuation that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask> is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36335MonadCont under the hood2010-07-24T03:19:11Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask> when it's done.<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask>,<br/>&nbsp;which will invoke <hask>F2</hask>,<br/>&nbsp;&nbsp;which will invoke <hask>C2</hask>,<br/>&nbsp;&nbsp;&nbsp;which will invoke <hask>F3</hask>,<br/>&nbsp;&nbsp;&nbsp;&nbsp;which will finally invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* The bind operator <hask>(>>=)</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
Thus, <hask>return</hask> in the <hask>Cont</hask> monad passes the result of its computation directly to the continuation it's given.<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? <hask>(k a)</hask> has become part of the continuation that <hask>m</hask> is given, and <hask>m</hask> passes its value to <hask>k</hask> by simply passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' The sequence of terms <hask>runCont Cont $</hask> effectively cancel out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes a function to construct a <hask>Cont</hask> object, and then runs it with the continuation it's given. However, it provides that function an ''alternate'' continuation that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36334MonadCont under the hood2010-07-24T03:16:22Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask> when it's done.<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask>,<br/>&nbsp;which will invoke <hask>F2</hask>,<br/>&nbsp;&nbsp;which will invoke <hask>C2</hask>,<br/>&nbsp;&nbsp;&nbsp;which will invoke <hask>F3</hask>,<br/>&nbsp;&nbsp;&nbsp;&nbsp;which will finally invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
Thus, <hask>return</hask> in the <hask>Cont</hask> monad passes the result of its computation directly to the continuation it's given.<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? <hask>(k a)</hask> has become part of the continuation that <hask>m</hask> is given, and <hask>m</hask> passes its value to <hask>k</hask> by simply passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes a function to construct a <hask>Cont</hask> object, and then runs it with the continuation it's given. However, it provides that function an ''alternate'' continuation that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=Tutorials&diff=36333Tutorials2010-07-24T03:15:15Z<p>Ods94043: Added "MonadCont under the hood" to the list of other Monad tutorials.</p>
<hr />
<div>==Introductions to Haskell==<br />
<br />
These are the recommended places to start learning, short of buying a textbook.<br />
<br />
=== Best places to start ===<br />
<br />
;[http://book.realworldhaskell.org/ Real World Haskell]<br />
: A free online version of the complete book, with numerous reader-submitted comments.<br />
<br />
;[http://learnyouahaskell.com Learn You a Haskell for Great Good!]<br />
: Nicely illustrated tutorial showing Haskell concepts while interacting in GHCi. Written and drawn by Miran Lipovača.<br />
<br />
;[http://darcs.haskell.org/yaht/yaht.pdf Yet Another Haskell Tutorial]<br />
:By Hal Daume III et al. A recommended tutorial for Haskell that is still under construction but covers already much ground. Also a classic text. Now available [http://en.wikibooks.org/wiki/Haskell/YAHT as a wikibook].<br />
<br />
;[http://en.wikibooks.org/wiki/Haskell Haskell Wikibook] <br />
:A communal effort by several authors to produce the definitive Haskell textbook. Its very much a work in progress at the moment, and contributions are welcome.<br />
<br />
;[http://en.wikibooks.org/wiki/Write_Yourself_a_Scheme_in_48_Hours Write Yourself a Scheme in 48 Hours in Haskell]<br />
:A Haskell Tutorial, by Jonathan Tang. Most Haskell tutorials on the web seem to take a language-reference-manual approach to teaching. They show you the syntax of the language, a few language constructs, and then have you construct a few simple functions at the interactive prompt. The "hard stuff" of how to write a functioning, useful program is left to the end, or sometimes omitted entirely. This tutorial takes a different tack. You'll start off with command-line arguments and parsing, and progress to writing a fully-functional Scheme interpreter that implements a good-sized subset of R5RS Scheme. Along the way, you'll learn Haskell's I/O, mutable state, dynamic typing, error handling, and parsing features. By the time you finish, you should be fairly fluent in both Haskell and Scheme.<br />
<br />
;[http://acm.wustl.edu/functional/haskell.php How to Learn Haskell]<br />
:Some students at Washington University in St. Louis documented the path they took to learning Haskell and put together a nice meta-tutorial to guide beginners through some of the available resources. Experienced programmers looking for some quick code examples may be interested in their [http://acm.wustl.edu/functional/hs-breads.php breadcrumbs].<br />
<br />
=== More tutorials ===<br />
<br />
;[http://www.haskell.org/tutorial/ A Gentle Introduction to Haskell] :By Paul Hudak, John Peterson, and Joseph H. Fasel. The title is misleading. Some knowledge of another functional programming language is expected. The emphasis is on the type system and those features which are really new in Haskell (compared to other functional programming languages). A classic, but not for the faint of heart (it's not so gentle). Also available in [http://gorgonite.developpez.com/livres/traductions/haskell/gentle-haskell/ French] and [http://www.rsdn.ru/article/haskell/haskell_part1.xml Russian].<br />
<br />
;[[H-99: Ninety-Nine Haskell Problems]]<br />
:A collection of programming puzzles, with Haskell solutions. Solving these is a great way to get into Haskell programming.<br />
<br />
;[http://www.haskell.org/~pairwise/intro/intro.html Haskell Tutorial for C Programmers]<br />
:By Eric Etheridge. From the intro: "This tutorial assumes that the reader is familiar with C/C++, Python, Java, or Pascal. I am writing for you because it seems that no other tutorial was written to help students overcome the difficulty of moving from C/C++, Java, and the like to Haskell."<br />
<br />
;[http://www-106.ibm.com/developerworks/edu/os-dw-linuxhask-i.html Beginning Haskell] <br />
:From IBM developerWorks. This tutorial targets programmers of imperative languages wanting to learn about functional programming in the language Haskell. If you have programmed in languages such as C, Pascal, Fortran, C++, Java, Cobol, Ada, Perl, TCL, REXX, JavaScript, Visual Basic, or many others, you have been using an imperative paradigm. This tutorial provides a gentle introduction to the paradigm of functional programming, with specific illustrations in the Haskell 98 language. (Free registration required.)<br />
<br />
;[http://www.informatik.uni-bonn.de/~ralf/teaching/Hskurs_toc.html Online Haskell Course] <br />
:By Ralf Hinze (in German).<br />
<br />
;[http://www.cs.chalmers.se/~rjmh/tutorials.html Tutorial Papers in Functional Programming].<br />
:A collection of links to other Haskell tutorials, from John Hughes.<br />
<br />
;[http://www.cs.ou.edu/cs1323h/textbook/haskell.shtml Two Dozen Short Lessons in Haskell] <br />
:By Rex Page. A draft of a textbook on functional programming, available by ftp. It calls for active participation from readers by omitting material at certain points and asking the reader to attempt to fill in the missing information based on knowledge they have already acquired. The missing information is then supplied on the reverse side of the page. <br />
<br />
;[ftp://ftp.geoinfo.tuwien.ac.at/navratil/HaskellTutorial.pdf Haskell-Tutorial] <br />
:By Damir Medak and Gerhard Navratil. The fundamentals of functional languages for beginners. <br />
<br />
;[http://video.s-inf.de/#FP.2005-SS-Giesl.(COt).HD_Videoaufzeichnung Video Lectures] <br />
:Lectures (in English) by Jürgen Giesl. About 30 hours in total, and great for learning Haskell. The lectures are 2005-SS-FP.V01 through 2005-SS-FP.V26. Videos 2005-SS-FP.U01 through 2005-SS-FP.U11 are exercise answer sessions, so you probably don't want those.<br />
<br />
;[http://www.cs.utoronto.ca/~trebla/fp/ Albert's Functional Programming Course] <br />
:A 15 lesson introduction to most aspects of Haskell.<br />
<br />
;[http://www.iceteks.com/articles.php/haskell/1 Introduction to Haskell]<br />
:By Chris Dutton, An "attempt to bring the ideas of functional programming to the masses here, and an experiment in finding ways to make it easy and interesting to follow".<br />
<br />
;[http://www.csc.depauw.edu/~bhoward/courses/0203Spring/csc122/haskintro/ An Introduction to Haskell]<br />
:A brief introduction, by Brian Howard.<br />
<br />
;[http://web.syntaxpolice.org/lectures/haskellTalk/slides/index.html Introduction to Haskell]<br />
:By Isaac Jones (2003).<br />
<br />
;[http://www.linuxjournal.com/article/9096 Translating Haskell into English]<br />
:By Shannon Behrens, a glimpse of the Zen of Haskell, without requiring that they already be Haskell converts.<br />
<br />
;[http://www.shlomifish.org/lecture/Perl/Haskell/slides/ Haskell for Perl Programmers]<br />
:Brief introduction to Haskell, with a view to what perl programmers are interested in<br />
<br />
;[http://lisperati.com/haskell/ How To Organize a Picnic on a Computer]<br />
:Fun introduction to Haskell, step by step building of a program to seat people at a planned picnic, based on their similarities using data from a survey and a map of the picnic location.<br />
<br />
;[http://cs.wwc.edu/KU/PR/Haskell.html Haskell Tutorial]<br />
<br />
;[http://www.lisperati.com/haskell/ Conrad Barski's Haskell tutorial .. with robots]<br />
<br />
;[[Media:Introduction.pdf|Frederick Ross's Haskell introduction]]<br />
<br />
;[http://de.wikibooks.org/wiki/Haskell Dirk's Haskell Tutorial]<br />
:in German for beginners by a beginner. Not so deep, but with a lot examples with very small steps.<br />
<br />
<br />
== Motivation for using Haskell ==<br />
<br />
;[http://www.md.chalmers.se/~rjmh/Papers/whyfp.html Why Functional Programming Matters] <br />
:By [http://www.md.chalmers.se/~rjmh/ John Hughes], The Computer Journal, Vol. 32, No. 2, 1989, pp. 98 - 107. Also in: David A. Turner (ed.): Research Topics in Functional Programming, Addison-Wesley, 1990, pp. 17 - 42.<BR> Exposes the advantages of functional programming languages. Demonstrates how higher-order functions and lazy evaluation enable new forms of modularization of programs.<br />
<br />
;[[Why Haskell matters]] <br />
:Discussion of the advantages of using Haskell in particular. An excellent article.<br />
<br />
;[http://www.cs.ukc.ac.uk/pubs/1997/224/index.html Higher-order + Polymorphic = Reusable] <br />
:By [http://www.cs.ukc.ac.uk/people/staff/sjt/index.html Simon Thompson]. Unpublished, May 1997.<BR> <STRONG>Abstract:</STRONG> This paper explores how certain ideas in object oriented languages have their correspondents in functional languages. In particular we look at the analogue of the iterators of the C++ standard template library. We also give an example of the use of constructor classes which feature in Haskell 1.3 and Gofer.<br />
<br />
;[http://www-128.ibm.com/developerworks/java/library/j-cb07186.html Explore functional programming with Haskell]<br />
:Introduction to the benefits of functional programming in Haskell by Bruce Tate.<br />
<br />
== Blog articles ==<br />
<br />
There are a large number of tutorials covering diverse Haskell topics<br />
published as blogs. Some of the best of these articles are collected<br />
here:<br />
<br />
;[[Blog articles]]<br />
<br />
==Practical Haskell==<br />
<br />
These tutorials examine using Haskell to writing complex real-world applications<br />
<br />
;[http://research.microsoft.com/%7Esimonpj/Papers/marktoberdorf Tackling the awkward squad: monadic input/output, concurrency, exceptions, and foreign-language calls in Haskell]<br />
:Simon Peyton Jones. Presented at the 2000 Marktoberdorf Summer School. In "Engineering theories of software construction", ed Tony Hoare, Manfred Broy, Ralf Steinbruggen, IOS Press, ISBN 1-58603-1724, 2001, pp47-96. The standard reference for monadic IO in GHC/Haskell. <br><strong>Abstract:</strong>Functional programming may be beautiful, but to write real applications we must grapple with awkward real-world issues: input/output, robustness, concurrency, and interfacing to programs written in other languages.<br />
<br />
;[[Hitchhikers Guide to the Haskell]]<br />
: Tutorial for C/Java/OCaml/... programers by Dmitry Astapov. From the intro: "This text intends to introduce the reader to the practical aspects of Haskell from the very beginning (plans for the first chapters include: I/O, darcs, Parsec, QuickCheck, profiling and debugging, to mention a few)".<br />
<br />
;[http://haskell.org/haskellwiki/IO_inside Haskell I/O inside: Down the Rabbit's Hole]<br />
:By Bulat Ziganshin (2006), a comprehensive tutorial on using IO monad.<br />
<br />
;[http://web.archive.org/web/20060622030538/http://www.reid-consulting-uk.ltd.uk/docs/ffi.html A Guide to Haskell's Foreign Function Interface]<br />
:A guide to using the foreign function interface extension, using the rich set of functions in the Foreign libraries, design issues, and FFI preprocessors.<br />
<br />
;[[Haskell IO for Imperative Programmers]]<br />
:A short introduction to IO from the perspective of an imperative programmer.<br />
<br />
;[[A brief introduction to Haskell|A Brief Introduction to Haskell]]<br />
:A translation of the article, [http://www.cs.jhu.edu/~scott/pl/lectures/caml-intro.html Introduction to OCaml], to Haskell.<br />
<br />
;[[Roll your own IRC bot]]<br />
:This tutorial is designed as a practical guide to writing real world code in Haskell and hopes to intuitively motivate and introduce some of the advanced features of Haskell to the novice programmer, including monad transformers. Our goal is to write a concise, robust and elegant IRC bot in Haskell.<br />
<br />
;[http://haskell.org/gtk2hs/docs/tutorial/glade/ Glade Tutorial (GUI Programming)]<br />
:For the absolute beginner in both Glade and Gtk2Hs. Covers the basics of Glade and how to access a .glade file and widgets in Gtk2Hs. Estimated learning time: 2 hours.<br />
;[http://www.muitovar.com/glade/es-index.html Tutorial de Glade]<br />
:A Spanish translation of the Glade tutorial<br />
<br />
;[http://www.muitovar.com/gtk2hs/index.html Gtk2Hs Tutorial]<br />
: An extensive Gtk2Hs programming guide, based on the GTK+2.0 tutorial by Tony Gale and Ian Main. This tutorial on GUI programming with Gtk2Hs has 22 chapters in 7 sections, plus an appendix on starting drawing with Cairo. A Spanish translation and source code of the examples are also available.<br />
<br />
;Applications of Functional Programming<br />
:Colin Runciman and David Wakeling (ed.), UCL Press, 1995, ISBN 1-85728-377-5 HB. From the cover:<blockquote>This book is unique in showcasing real, non-trivial applications of functional programming using the Haskell language. It presents state-of-the-art work from the FLARE project and will be an invaluable resource for advanced study, research and implementation.</blockquote><br />
<br />
;[[DealingWithBinaryData]] a guide to bytestrings, the various <tt>Get</tt> monads and the <tt>Put</tt> monad.<br />
<br />
;[[Internationalization of Haskell programs]]<br />
:Short tutorial on how to use GNU gettext utility to make applications, written on Haskell, multilingual.<br />
<br />
===Testing===<br />
<br />
;[http://blog.moertel.com/articles/2006/10/31/introductory-haskell-solving-the-sorting-it-out-kata Small overview of QuickCheck]<br />
<br />
;[[Introduction to QuickCheck]]<br />
<br />
==Reference material==<br />
<br />
;[http://haskell.org/haskellwiki/Category:Tutorials A growing list of Haskell tutorials on a diverse range of topics]<br />
:Available on this wiki<br />
<br />
;[http://haskell.org/haskellwiki/Category:How_to "How to"-style tutorials and information]<br />
<br />
;[http://undergraduate.csse.uwa.edu.au/units/230.301/lectureNotes/tourofprelude.html A Tour of the Haskell Prelude (basic functions)] <br />
:By Bernie Pope and Arjan van IJzendoorn.<br />
<br />
;[http://cs.anu.edu.au/Student/comp1100/haskell/tourofsyntax.html Tour of the Haskell Syntax] <br />
:By Arjan van IJzendoorn.<br />
<br />
;[http://zvon.org/other/haskell/Outputglobal/index.html Haskell Reference] <br />
:By Miloslav Nic.<br />
<br />
;[http://members.chello.nl/hjgtuyl/tourdemonad.html A tour of the Haskell Monad functions]<br />
:By Henk-Jan van Tuyl.<br />
<br />
;[http://www.cse.unsw.edu.au/~en1000/haskell/inbuilt.html Useful Haskell functions]<br />
:An explanation for beginners of many Haskell functions that are predefined in the Haskell Prelude.<br />
<br />
;[http://www.cs.chalmers.se/Cs/Grundutb/Kurser/d1pt/d1pta/ListDoc/ Haskell's Standard List Functions]<br />
:A tour of the standard Haskell functions, directed by what you want to achieve<br />
<br />
;[http://haskell.org/ghc/docs/latest/html/libraries/ Documentation for the standard libraries]<br />
:Complete documentation of the standard Haskell libraries.<br />
<br />
;[http://www.haskell.org/haskellwiki/Category:Idioms Haskell idioms]<br />
:A collection of articles describing some common Haskell idioms. Often quite advanced.<br />
<br />
;[http://www.haskell.org/haskellwiki/Blow_your_mind Useful idioms]<br />
:A collection of short, useful Haskell idioms.<br />
<br />
;[http://www.haskell.org/haskellwiki/Programming_guidelines Programming guidelines]<br />
:Some Haskell programming and style conventions.<br />
<br />
;[http://www.md.chalmers.se/~rjmh/Combinators/LightningTour/index.htm Lightning Tour of Haskell]<br />
:By John Hughes, as part of a Chalmers programming course<br />
<br />
;[http://www.cs.chalmers.se/~augustss/AFP/manuals/haskeller.dvi.gz The Little Haskeller] <br />
:By Cordelia Hall and John Hughes. 9. November 1993, 26 pages. An introduction using the Chalmers Haskell B interpreter (hbi). Beware that it relies very much on the user interface of hbi which is quite different for other Haskell systems, and the tutorials cover Haskell 1.2 , not Haskell 98.<br />
<br />
;[http://www.cs.uu.nl/people/jeroen/courses/fp-eng.pdf Functional Programming]<br />
:By Jeroen Fokker, 1995. (153 pages, 600 KB). Textbook for learning functional programming with Gofer (an older implementation of Haskell). Here without Chapters&nbsp;6 and&nbsp;7.<br />
<br />
== Comparisons to other languages ==<br />
<br />
Articles constrasting feature of Haskell with other languages.<br />
<br />
;[http://programming.reddit.com/goto?id=nq1k Haskell versus Scheme]<br />
:Mark C. Chu-Carroll, Haskell and Scheme: Which One and Why?<br />
<br />
;[http://wiki.python.org/moin/PythonVsHaskell Comparing Haskell and Python]<br />
:A short overview of similarities and differences between Haskell and Python.<br />
<br />
;[http://programming.reddit.com/goto?id=nwm2 Monads in OCaml]<br />
:Syntax extension for monads in OCaml<br />
<br />
;[http://www.shlomifish.org/lecture/Perl/Haskell/slides/ Haskell for Perl programmers]<br />
:Short intro for perlers<br />
<br />
;[[A_brief_introduction_to_Haskell|Introduction to Haskell]] versus [http://www.cs.jhu.edu/~scott/pl/lectures/caml-intro.html Introduction to OCaml].<br />
<br />
;[http://www.thaiopensource.com/relaxng/derivative.html An algorithm for RELAX NG validation]<br />
:by James Clark (of RELAX NG fame). Describes an algorithm for validating an XML document against a RELAX NG schema, uses Haskell to describe the algorithm. The algorithm in Haskell and Java is then [http://www.donhopkins.com/drupal/node/117 discussed here].<br />
<br />
;[http://mult.ifario.us/articles/2006/10/11/first-steps-with-haskell-for-web-applications Haskell + FastCGI versus Ruby on Rails]<br />
:A short blog entry documenting performance results with ruby on rails and Haskell with fastcgi<br />
<br />
;[http://haskell.org/papers/NSWC/jfp.ps Haskell vs. Ada vs. C++ vs. Awk vs. ..., An Experiment in Software Prototyping Productivity] (postscript)<br />
:Paul Hudak and Mark P. Jones, 16 pages.<blockquote>Description of the results of an experiment in which several conventional programming languages, together with the functional language Haskell, were used to prototype a Naval Surface Warfare Center requirement for Geometric Region Servers. The resulting programs and development metrics were reviewed by a committee chosen by the US Navy. The results indicate that the Haskell prototype took significantly less time to develop and was considerably more concise and easier to understand than the corresponding prototypes written in several different imperative languages, including Ada and C++. </blockquote> <br />
<br />
;[http://www.osl.iu.edu/publications/prints/2003/comparing_generic_programming03.pdf A Comparative Study of Language Support for Generic Programming] (pdf)<br />
:Ronald Garcia, Jaakko Jrvi, Andrew Lumsdaine, Jeremy G. Siek, and Jeremiah Willcock. In Proceedings of the 2003 ACM SIGPLAN conference on Object-oriented programming, systems, languages, and applications (OOPSLA'03), October 2003.<blockquote>An interesting comparison of generic programming support across languages, including: Haskell, SML, C++, Java, C#. Haskell supports all constructs described in the paper -- the only language to do so. </blockquote><br />
<br />
;[http://homepages.inf.ed.ac.uk/wadler/realworld/index.html Functional Programming in the Real World]<br />
:A list of functional programs applied to real-world tasks. The main criterion for being real-world is that the program was written primarily to perform some task, not primarily to experiment with functional programming. Functional is used in the broad sense that includes both `pure' programs (no side effects) and `impure' (some use of side effects). Languages covered include CAML, Clean, Erlang, Haskell, Miranda, Scheme, SML, and others.<br />
<br />
;[http://www.defmacro.org/ramblings/lisp-in-haskell.html Lisp in Haskell]<br />
:Writing A Lisp Interpreter In Haskell, a tutorial<br />
<br />
== Teaching Haskell ==<br />
<br />
;[http://www.cs.ukc.ac.uk/pubs/1997/208/index.html Where do I begin? A problem solving approach to teaching functional programming]<br />
:By [http://www.cs.ukc.ac.uk/people/staff/sjt/index.html Simon Thompson]. In Krzysztof Apt, Pieter Hartel, and Paul Klint, editors, First International Conference on Declarative Programming Languages in Education. Springer-Verlag, September 1997. <br> <STRONG>Abstract:</STRONG> This paper introduces a problem solving method for teaching functional programming, based on Polya's `How To Solve It', an introductory investigation of mathematical method. We first present the language independent version, and then show in particular how it applies to the development of programs in Haskell. The method is illustrated by a sequence of examples and a larger case study. <br />
<br />
;[http://www.cs.ukc.ac.uk/pubs/1995/214/index.html Functional programming through the curriculum]<br />
:By [http://www.cs.ukc.ac.uk/people/staff/sjt/index.html Simon Thompson] and Steve Hill. In Pieter H. Hartel and Rinus Plasmeijer, editors, Functional Programming Languages in Education, LNCS 1022, pages 85-102. Springer-Verlag, December 1995. <br> <STRONG>Abstract:</STRONG> This paper discusses our experience in using a functional language in topics across the computer science curriculum. After examining the arguments for taking a functional approach, we look in detail at four case studies from different areas: programming language semantics, machine architectures, graphics and formal languages. <br />
<br />
;[http://www.cse.unsw.edu.au/~chak/papers/CK02a.html The Risks and Benefits of Teaching Purely Functional Programming in First Year]<br />
:By [http://www.cse.unsw.edu.au/~chak Manuel M. T. Chakravarty] and [http://www.cse.unsw.edu.au/~keller Gabriele Keller]. Journal of Functional Programming 14(1), pp 113-123, 2004. An earlier version of this paper was presented at Functional and Declarative Programming in Education (FDPE02). <br> <strong>Abstract</strong> We argue that teaching purely functional programming as such in freshman courses is detrimental to both the curriculum as well as to promoting the paradigm. Instead, we need to focus on the more general aims of teaching elementary techniques of programming and essential concepts of computing. We support this viewpoint with experience gained during several semesters of teaching large first-year classes (up to 600 students) in Haskell. These classes consisted of computer science students as well as students from other disciplines. We have systematically gathered student feedback by conducting surveys after each semester. This article contributes an approach to the use of modern functional languages in first year courses and, based on this, advocates the use of functional languages in this setting.<br />
<br />
<br />
==Using monads==<br />
<br />
See also the [[Monad]] HaskellWiki page.<br />
<br />
<br />
===Recommended tutorials===<br />
<br />
;[http://www.haskell.org/all_about_monads/html/index.html All About Monads] <br />
:By Jeff Newbern. This tutorial aims to explain the concept of a monad and its application to functional programming in a way that is easy to understand and useful to beginning and intermediate Haskell programmers. Familiarity with the Haskell language is assumed, but no prior experience with monads is required. <br />
<br />
;[[Monads as computation]]<br />
:A tutorial which gives a broad overview to motivate the use of monads as an abstraction in functional programming and describe their basic features. It makes an attempt at showing why they arise naturally from some basic premises about the design of a library.<br />
<br />
;[[Monads as containers]]<br />
:A tutorial describing monads from a rather different perspective: as an abstraction of container-types, rather than an abstraction of types of computation.<br />
<br />
;[http://uebb.cs.tu-berlin.de/~magr/pub/Transformers.en.html Monad Transformers Step by Step]<br />
:By Martin Grabm&uuml;ller. A small tutorial on using monad transformers. In contrast to others found on the web, it concentrates on using them, not on their implementation.<br />
<br />
;[[What a Monad is not]]<br />
<br />
;[http://noordering.wordpress.com/2009/03/31/how-you-shouldnt-use-monad/ How you should(n’t) use Monads]<br />
<br />
;[http://www.sampou.org/haskell/a-a-monads/html/index.html モナドのすべて [All About Monads]]<br />
:A translation of Jeff Newbern's tutorial "All About Monads" into Japanese.<br />
<br />
===Parser===<br />
<br />
;[http://www.haskell.org/sitewiki/images/c/c6/ICMI45-paper-en.pdf The Parser monad and other monad (i.e. a monad with state and I/O string)]. <br />
:The parser monad is used to build modular, flexible, parsers. <br />
<br />
;[http://www.haskell.org/sitewiki/images/c/c6/ICMI45-paper-en.pdf How to build a monadic interpreter in one day] (pdf)<br />
:By Dan Popa. A small tutorial on how to build a language in one day, using the Parser Monad in the front end and a monad with state and I/O string in the back end. Read it if you are interested in learning: <br />
:# language construction and <br />
:# interpreter construction<br />
<br />
===More tutorials===<br />
<br />
;[http://stefan-klinger.de/files/monadGuide.pdf The Haskell Programmer's Guide to the IO Monad - Don't Panic.] <br />
:By Stefan Klinger. This report scratches the surface of category theory, an abstract branch of algebra, just deep enough to find the monad structure. It seems well written.<br />
<br />
;[http://www.prairienet.org/~dsb/monads.htm A (hopefully) painless introduction to monads] <br />
:By Dan Bensen. A straightforward beginner's guide with intuitive explanations and examples.<br />
<br />
;[http://www-users.mat.uni.torun.pl/~fly/materialy/fp/haskell-doc/Monads.html What the hell are Monads?] <br />
:By Noel Winstanley. A basic introduction to monads, monadic programming and IO. This introduction is presented by means of examples rather than theory, and assumes a little knowledge of Haskell. <br />
<br />
;[http://www.engr.mun.ca/~theo/Misc/haskell_and_monads.htm Monads for the Working Haskell Programmer -- a short tutorial]<br />
:By Theodore Norvell. <br />
<br />
;[http://sigfpe.blogspot.com/2006/08/you-could-have-invented-monads-and.html You Could Have Invented Monads! (And Maybe You Already Have.)]<br />
:A short tutorial on monads, introduced from a pragmatic approach, with less category theory references <br />
<br />
;[http://www.cs.chalmers.se/~augustss/AFP/monads.html Systematic Design of Monads]<br />
:By John Hughes and Magnus Carlsson. Many useful monads can be designed in a systematic way, by successively adding facilities to a trivial monad. The capabilities that can be added in this way include state, exceptions, backtracking, and output. Here we give a brief description of the trivial monad, each kind of extension, and sketches of some interesting operations that each monad supports.<br />
<br />
;[[Meet Bob The Monadic Lover]]<br />
:By Andrea Rossato. A by-the-author-supposed-to-be funny and short introduction to Monads, with code but without any reference to category theory: what monads look like and what they are useful for, from the perspective of a ... lover. (There is also the slightly more serious [[The Monadic Way]] by the same author.)<br />
<br />
;[http://www.haskell.org/pipermail/haskell-cafe/2006-November/019190.html Monstrous Monads]<br />
:Andrew Pimlott's humourous introduction to monads, using the metaphor of "monsters".<br />
<br />
;[http://strabismicgobbledygook.wordpress.com/2010/03/06/a-state-monad-tutorial/ A State Monad Tutorial]<br />
:A detailed tutorial with simple but practical examples.<br />
<br />
;Computational monads on Reddit, by [http://programming.reddit.com/info/ox6s/comments/coxiv tmoertel] and [http://programming.reddit.com/info/ox6s/comments/coxoh dons].<br />
<br />
;[http://www.loria.fr/~kow/monads/index.html Of monads and space suits]<br />
:By Eric Kow.<br />
<br />
;[[The Monadic Way]]<br />
<br />
;[http://www.alpheccar.org/fr/posts/show/60 Three kind of monads] : sequencing, side effects or containers<br />
<br />
;[[Simple monad examples]]<br />
<br />
;[http://en.wikipedia.org/wiki/Monads_in_functional_programming Article on monads on Wikipedia]<br />
<br />
;[[IO inside]] page<br />
:Explains why I/O in Haskell is implemented with a monad.<br />
<br />
;[http://haskell.org/haskellwiki/Blog_articles#Monads Blog articles]<br />
<br />
;[[Monad Transformers Explained]]<br />
<br />
;[http://www.muitovar.com/monad/moncow.html The Greenhorn's Guide to becoming a Monad Cowboy]<br />
:Covers basics, with simple examples, in a ''for dummies'' style. Includes monad transformers and monadic functions. Estimated learning time 2-3 days.<br />
<br />
;[http://ertes.de/articles/monads.html Understanding Haskell Monads]<br />
<br />
;[http://www.reddit.com/r/programming/comments/64th1/monads_in_python_in_production_code_you_can_and/c02u9mb A very clear explanation by 808140]<br />
<br />
;[[MonadCont under the hood]] is a detailed description of the ''Cont'' data type and its monadic operations, including the class ''MonadCont''.<br />
<br />
See also [[Research papers/Monads and arrows]]<br />
<br />
<br />
<br />
==Workshops on advanced functional programming==<br />
<br />
;[http://compilers.iecc.com/comparch/article/95-04-024 Advanced Functional Programming: 1st International Spring School on Advanced Functional Programming Techniques], Bastad, Sweden, May 24 - 30, 1995. Tutorial Text (Lecture Notes in Computer Science) <br />
<br />
;[http://www.cse.ogi.edu/PacSoft/conf/summerschool96.html Advanced Functional Programming: 2nd International School], Olympia, Wa, Usa, August 26-30, 1996 Tutorial Text (Lecture Notes in Computer Science) <br />
<br />
;[http://alfa.di.uminho.pt/~afp98/ Advanced Functional Programming: 3rd International School], AFP'98, Braga, Portugal, September 12-19, 1998, Revised Lectures (Lecture Notes in Computer Science) <br />
<br />
;[http://www.cs.uu.nl/~johanj/afp/afp4/ Advanced Functional Programming: 4th International School], AFP 2002, Oxford, UK, August 19-24, 2002, Revised Lectures (Lecture Notes in Computer Science) <br />
<br />
;[http://www.cs.ut.ee/afp04/ Advanced Functional Programming: 5th International School], AFP 2004, Tartu, Estonia, August 14-21, 2004, Revised Lectures (Lecture Notes in Computer Science) <br />
<br />
More advanced materials available from the [[Conferences|conference proceedings]], and the [[Research papers]] collection.<br />
<br />
<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36332MonadCont under the hood2010-07-24T03:06:09Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask>,<br/>&nbsp;which will invoke <hask>F2</hask>,<br/>&nbsp;&nbsp;which will invoke <hask>C2</hask>,<br/>&nbsp;&nbsp;&nbsp;which will invoke <hask>F3</hask>,<br/>&nbsp;&nbsp;&nbsp;&nbsp;which will finally invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
Thus, <hask>return</hask> in the <hask>Cont</hask> monad passes the result of its computation directly to the continuation it's given.<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? <hask>(k a)</hask> has become part of the continuation that <hask>m</hask> is given, and <hask>m</hask> passes its value to <hask>k</hask> by simply passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes a function to construct a <hask>Cont</hask> object, and then runs it with the continuation it's given. However, it provides that function an ''alternate'' continuation that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36331MonadCont under the hood2010-07-24T03:03:09Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask>,<br/>&nbsp;which will invoke <hask>F2</hask>,<br/>&nbsp;&nbsp;which will invoke <hask>C2</hask>,<br/>&nbsp;&nbsp;&nbsp;which will invoke <hask>F3</hask>,<br/>&nbsp;&nbsp;&nbsp;&nbsp;which will finally invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
Thus, <hask>return</hask> in the <hask>Cont</hask> monad passes the result of its computation directly to the continuation it's given.<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? <hask>(k a)</hask> has become part of the continuation that <hask>m</hask> is given, and <hask>m</hask> passes its value to <hask>k</hask> by simply passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes the function it's given, but provides a ''second'' continuation to that function that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36330MonadCont under the hood2010-07-24T03:01:22Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask>,<br/>&nbsp;which will invoke <hask>F2</hask>,<br/>&nbsp;&nbsp;which will invoke <hask>C2</hask>,<br/>&nbsp;&nbsp;&nbsp;which will invoke <hask>F3</hask>,<br/>&nbsp;&nbsp;&nbsp;&nbsp;which will finally invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
Thus, <hask>return</hask> in the <hask>Cont</hask> monad passes the result of its computation directly to the continuation it's given.<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? (k a) has become part of the continuation that m is given, and m passes its value to k simply by passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes the function it's given, but provides a ''second'' continuation to that function that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36329MonadCont under the hood2010-07-24T02:57:34Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask>,<br/>which will invoke <hask>F2</hask>,<br/> which will invoke <hask>C2</hask><br/>, which will invoke<hask>F3</hask><br/>, which will finally invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? (k a) has become part of the continuation that m is given, and m passes its value to k simply by passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes the function it's given, but provides a ''second'' continuation to that function that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36328MonadCont under the hood2010-07-24T02:51:41Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> operations in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad does its thing. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing under the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask> which will invoke <hask>F2</hask>, which will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? (k a) has become part of the continuation that m is given, and m passes its value to k simply by passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Exploring the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes the function it's given, but provides a ''second'' continuation to that function that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36327MonadCont under the hood2010-07-24T02:50:00Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad works. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing, particularly below the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Introducing Continuations and the Cont type=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask> which will invoke <hask>F2</hask>, which will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? (k a) has become part of the continuation that m is given, and m passes its value to k simply by passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Applying the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=Understanding MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes the function it's given, but provides a ''second'' continuation to that function that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36326MonadCont under the hood2010-07-24T02:48:05Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad works. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing, particularly below the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Continuations and the Cont monad=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask> which will invoke <hask>F2</hask>, which will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? (k a) has become part of the continuation that m is given, and m passes its value to k simply by passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Applying the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=Understanding MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes the function it's given, but provides a ''second'' continuation to that function that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36325MonadCont under the hood2010-07-24T02:44:19Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad works. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing, particularly below the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Continuations and the Cont monad=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
# takes a continuation as an argument<br />
# does whatever it needs to do<br />
# produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask> which will invoke <hask>F2</hask>, which will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? (k a) has become part of the continuation that m is given, and m passes its value to k simply by passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Applying the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=Understanding MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes the function it's given, but provides a ''second'' continuation to that function that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36324MonadCont under the hood2010-07-24T02:43:28Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad works. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing, particularly below the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Continuations and the Cont monad=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
1. takes a continuation as an argument<br />
2. does whatever it needs to do<br />
3. produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask> that will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask> which will invoke <hask>F2</hask>, which will invoke <hask>F3</hask>, which will invoke <hask>C3</hask>.<br />
<br />
What I've described so far is the ''applicative'' operation of continuations.<br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? (k a) has become part of the continuation that m is given, and m passes its value to k simply by passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Applying the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=Understanding MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes the function it's given, but provides a ''second'' continuation to that function that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36323MonadCont under the hood2010-07-24T02:41:09Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of <tt>Cont</tt> and <tt>MonadCont</tt> in the [http://hackage.haskell.org/packages/archive/mtl/1.1.0.2/doc/html/Control-Monad-Cont.html Control.Monad.Cont documentation], but it doesn't really describe how the continuation monad works. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing, particularly below the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Continuations and the Cont monad=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
1. takes a continuation as an argument<br />
2. does whatever it needs to do<br />
3. produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask>that will invoke <hask>F3</hask><br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask> that will invoke <hask>F2</hask>, then <hask>F3</hask>, then <hask>C3</hask>.<br />
<br />
What I've described so far is the <hask>Applicative</hask> operation of continuations. <br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? (k a) has become part of the continuation that m is given, and m passes its value to k simply by passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Applying the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=Understanding MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes the function it's given, but provides a ''second'' continuation to that function that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36322MonadCont under the hood2010-07-24T02:38:46Z<p>Ods94043: </p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of Cont and MonadCont in the Control.Monad.Cont documentation, but it doesn't really describe how the continuation monad works. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing, particularly below the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Continuations and the Cont monad=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as <tt>Cont</tt>'' objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
1. takes a continuation as an argument<br />
2. does whatever it needs to do<br />
3. produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 -> F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask>that will invoke <hask>F3</hask><br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask> that will invoke <hask>F2</hask>, then <hask>F3</hask>, then <hask>C3</hask>.<br />
<br />
What I've described so far is the <hask>Applicative</hask> operation of continuations. <br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? (k a) has become part of the continuation that m is given, and m passes its value to k simply by passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Applying the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=Understanding MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes the function it's given, but provides a ''second'' continuation to that function that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorials]]</div>Ods94043https://wiki.haskell.org/index.php?title=MonadCont_under_the_hood&diff=36321MonadCont under the hood2010-07-24T02:36:59Z<p>Ods94043: Initial import and edits from StackOverflow.</p>
<hr />
<div>This tutorial is a response to the following [http://stackoverflow.com/questions/3322540/tutorial-to-disassemble-the-haskell-cont-monad/3323283#3323283 Stack Overflow question]. There's a short but useful description of Cont and MonadCont in the Control.Monad.Cont documentation, but it doesn't really describe how the continuation monad works. This is an attempt at much more detailed explanation of what Cont and MonadCont are doing, particularly below the hood.<br />
<br />
This tutorial assumes a working knowledge of Haskell, though of course it doesn't assume that you understood the implementation of <hask>Control.Monad.Cont</hask> the first time you read it!<br />
<br />
=Continuations and the Cont monad=<br />
<br />
Continuations are functions that represent "the remaining computation to do." Their representation here is <hask>a -> r</hask>, which is simply a function that takes some value produced by the current computation, of some type <hask>a</hask>, and returns the final result of type <hask>r</hask> from it.<br />
<br />
The type <hask>Cont r a</hask> (instances of which I will, in this tutorial, refer to as ''Cont objects'') represents a ''continuation-passing-style function that takes a single continuation as its only input''. In other words, its guts are a function that:<br />
<br />
1. takes a continuation as an argument<br />
2. does whatever it needs to do<br />
3. produces a value of type <hask>r</hask> at the end, presumably by invoking the continuation.<br />
<br />
Note that whatever it needs to do, i.e. whatever values it needs to be able to use to do its thing, must already be bound up into the <hask>Cont</hask> object. So, generally, we won't be dealing with <hask>Cont</hask> objects directly, but with functions that can ultimately produce one.<br />
<br />
=Sequencing Continuation-Style Computations=<br />
==Applicative Sequencing==<br />
<hask>Cont</hask> objects can be chained together, so that the continuation you pass in threads through the guts of all the <hask>Cont</hask> objects in the chain before it's finally invoked. The way they chain is the way <hask>Cont</hask> works: each object in the chain invokes a continuation that ''has the next object's computation prepended to the final continuation''. Let's say we have a chain of <hask>Cont</hask> objects <hask>F1 -> F2 ->F3</hask>, and let's say you had a continuation <hask>C3</hask> that you want to pass to the chain. Then:<br />
<br />
* <hask>F3</hask> needs to invoke <hask>C3</hask>when it's done<br />
* <hask>F2</hask> needs to invoke a continuation <hask>C2</hask>that will invoke <hask>F3</hask><br />
* <hask>F1</hask> needs to invoke a continuation <hask>C1</hask> that will invoke <hask>F2</hask>, then <hask>F3</hask>, then <hask>C3</hask>.<br />
<br />
What I've described so far is the <hask>Applicative</hask> operation of continuations. <br />
<br />
==Extending to Monad==<br />
With the <hask>Monad</hask> operation there's an extra wrinkle: we allow for the value of one computation to affect ''which'' <hask>Cont</hask> object gets invoked next. In this world:<br />
<br />
* <hask>return</hask> takes a value and produces a <hask>Cont</hask> object that just passes that value to its continuation. <br />
* <hask>bind</hask> takes a <hask>Cont</hask> object, and a ''function that produces another <hask>Cont</hask> object given a value from the first'', and chains them together into one <hask>Cont</hask> object. That object, when invoked, is going to:<br />
** take a single continuation object <hask>C</hask>,<br />
** produce an intermediate value,<br />
** use that intermediate value to select/create the next <hask>Cont</hask> object to invoke,<br />
** invoke that <hask>Cont</hask> object with <hask>C</hask><br />
<br />
=Understanding the Monad=<br />
==Return==<br />
The code:<br />
<br />
<haskell><br />
return a = Cont ($ a)<br />
</haskell><br />
<br />
is equivalent to the following code:<br />
<br />
<haskell><br />
return a = Cont $ \c -> c a<br />
</haskell><br />
<br />
Why? The code <hask>($ a)</hask> is a ''slice'' of the operator <hask>$</hask>, which represents application. In other words, <hask>($ a)</hask> can be equivalently written <hask>\f -> f a</hask>, or "take a function as input and apply it to a."<br />
<br />
==Bind==<br />
The code:<br />
<br />
<haskell><br />
m >>= k = Cont $ \c -> runCont m $ \a -> runCont (k a) c<br />
</haskell><br />
<br />
is a terse way of saying the following:<br />
<br />
<haskell><br />
m >>= k = let s c = runCont m c<br />
t c = \a -> runCont (k a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
Do you see what's happening? (k a) has become part of the continuation that m is given, and m passes its value to k simply by passing its value to its continuation. The <hask>Cont</hask> objects are being created "just in time" to be used, based on the computation so far.<br />
<br />
=Applying the Monad=<br />
Here's a simple example I've cooked up that should help illustrate the monad in action:<br />
<br />
<haskell><br />
f :: Int -> Cont r Int<br />
f x = Cont $ \c -> c (x * 3)<br />
g :: Int -> Cont r Int<br />
g x = Cont $ \c -> c (x - 2)<br />
</haskell><br />
<br />
These are simple functions that produce <hask>Cont</hask> objects, given an intermediate value <hask>x</hask>. You can see that the value being passed to the continuation is an Int, though we don't put any restrictions on what that continuation can ultimately produce.<br />
<br />
BTW, they can be equivalently written as:<br />
<br />
<haskell><br />
f x = return (x * 3)<br />
g x = return (x - 2)<br />
</haskell><br />
<br />
where they look very similar to normal functions. I'm writing them longhand to show you explicitly what the functions are doing.<br />
<br />
<haskell><br />
h :: Int -> Cont r Int<br />
h x | x == 5 = f x<br />
| otherwise = g x<br />
</haskell><br />
<br />
This is a more complicated function that chooses between two other <hask>Cont</hask> objects, based on the input it's given.<br />
<br />
Now let's create a top-level <hask>Cont</hask> object that does some chaining:<br />
<br />
<haskell><br />
doC :: Cont r Int<br />
doC = return 5 >>= h<br />
</haskell><br />
<br />
And we'll invoke it like this:<br />
<br />
<haskell><br />
finalC :: Show a => a -> String<br />
finalC x = "Done: " ++ show(x)<br />
<br />
runCont doC finalC<br />
</haskell><br />
<br />
Note that <hask>runCont doC</hask> produces a function of type <hask>(Int -> a) -> a</hask>, which is invoked on a continuation of type <hask>Show a => a -> String</hask>, which reduces in this context to <hask>Int -> String</hask>. The final value produced will be a <hask>String</hask>. Can you guess what it will say? What if you changed <hask>return 5</hask> to <hask>return 4</hask>?<br />
<br />
Let's see if you're right:<br />
<br />
<hask>return 5</hask> produces a <hask>Cont</hask> object that basically looks like this: <hask>Cont $ \c -> c 5</hask>. So that part is easy.<br />
<br />
<hask>h</hask> is a function that takes a value and produces a <hask>Cont</hask> object depending on the value it's given.<br />
<br />
''Lemma:'' <hask>runCont Cont $</hask> effectively cancels out, i.e. <hask>runCont (Cont $ \c -> ...)</hask> is simply the function <hask>\c -> ...</hask>. This is because <hask>runCont</hask> is a field selector of <hask>Cont</hask> objects, and <hask>Cont</hask> objects only have that one field.<br />
<br />
Therefore, <hask>(return 5) >>= h</hask> expands and simplifies to:<br />
<br />
<haskell><br />
let s c = c 5<br />
t c = \a -> runCont (h a) c<br />
in Cont $ \c -> s (t c)<br />
</haskell><br />
<br />
And finally, <hask>runCont doC finalC</hask> evaluates to:<br />
<br />
runCont doC finalC<br />
=> runCont (Cont $ \c -> s (t c)) finalC -- unfold doC<br />
=> s (t finalC) -- simplify with lemma and apply to finalC<br />
=> (t finalC) 5 -- unfold s<br />
=> (\a -> runCont (h a) finalC) 5 -- unfold t<br />
=> runCont (h 5) finalC -- apply \a... to 5<br />
=> runCont (f 5) finalC -- unfold h<br />
=> runCont (Cont $ \c -> c (5*3)) finalC -- unfold f<br />
=> (\c -> c (5*3)) finalC -- simplify with lemma<br />
=> finalC (5*3) -- apply \c... to finalC<br />
=> "Done: 15" -- apply *; apply finalC to final value!<br />
<br />
=Understanding MonadCont and callCC= <br />
One final extension to this which is frequently used is the <hask>MonadCont</hask> class, which provides a <hask>callCC</hask> operation. <hask>callCC</hask> creates a <hask>Cont</hask> object that invokes the function it's given, but provides a ''second'' continuation to that function that can be invoked to "break out" of the computation and simply pass a value to the continuation that was active when <hask>callCC</hask> was invoked. This function's operation is definitely easier to understand by seeing it in action. Evaluate the following code, replacing the corresponding functions above:<br />
<br />
<haskell><br />
h :: Int -> (Int -> Cont r Int) -> Cont r Int<br />
h x abort | x == 5 = f x<br />
| otherwise = abort (-1)<br />
<br />
doC n = return n >>= \x -> <br />
callCC (\abort -> h x abort) >>= \y -><br />
g y<br />
</haskell><br />
<br />
Run <hask>runCont (doC 5) finalC</hask>. h should invoke f, and g will be invoked afterward, so you should get 13 as the final answer.<br />
<br />
Now change <hask>(doC 5)</hask> to <hask>(doC 4)</hask>. In this case, h will call abort, which passes -1 to g. -3 should be the final answer.<br />
<br />
Now change <hask>doC</hask> to move g inside the callCC abort context:<br />
<br />
<haskell><br />
doC n = return n >>= \x -><br />
callCC (\abort -> h x abort >>= \y -><br />
g y)<br />
</haskell><br />
<br />
and run with <hask>(doC 4)</hask>. In this case, h invokes abort and g is never invoked! -1 is the final answer.<br />
<br />
Once you've converted all your operations to continuation-passing style by putting them in the <hask>Cont</hask> monad, and have a handle on how <hask>>>=</hask> works in that monad, understanding how <hask>callCC</hask> works is surprisingly simple:<br />
<br />
<haskell><br />
callCC f = Cont $ \c -> runCont (f (\a -> Cont $ \_ -> c a )) c<br />
</haskell><br />
<br />
can be written as<br />
<br />
<haskell><br />
callCC f = let backtrack a = Cont $ \_ -> c a<br />
in Cont $ \c -> runCont (f backtrack) c<br />
</haskell><br />
<br />
The key is <hask>backtrack</hask>, which takes whatever "inner" continuation is active when backtrack is invoked, completely ignores it, and simply passes its value to the "outer" continuation <hask>c</hask>. (Compare this to the definition of <hask>return</hask>, which always uses the continuation it's given.) <hask>f</hask>is the function passed to <hask>callCC</hask>, whose extent provides the context under which <hask>backtrack</hask> can be used.<br />
<br />
[[Category:Monad]]<br />
[[Category:Tutorial]]</div>Ods94043