<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>The Comonad.Reader &#187; Kan Extensions</title>
	<atom:link href="http://comonad.com/reader/category/kan-extensions/feed/" rel="self" type="application/rss+xml" />
	<link>http://comonad.com/reader</link>
	<description>types, (co)monads, substructural logic</description>
	<lastBuildDate>Tue, 03 Apr 2012 00:51:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Searching Infinity Parametrically</title>
		<link>http://comonad.com/reader/2011/searching-infinity/</link>
		<comments>http://comonad.com/reader/2011/searching-infinity/#comments</comments>
		<pubDate>Sun, 25 Dec 2011 06:19:43 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Type Hackery]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=510</guid>
		<description><![CDATA[Andrej Bauer recently gave a really nice talk on how you can exploit side-effects to make a faster version of Martin Escardo's pseudo-paradoxical combinators. 
A video of his talk is available over on his blog, and his presentation is remarkably clear, and would serve as a good preamble to the code I'm going to present [...]]]></description>
			<content:encoded><![CDATA[<p>Andrej Bauer recently gave a really nice talk on how you can exploit side-effects to make a faster version of Martin Escardo's pseudo-paradoxical combinators. </p>
<p><a href="http://math.andrej.com/2011/12/06/how-to-make-the-impossible-functionals-run-even-faster/">A video of his talk is available over on his blog</a>, and his presentation is remarkably clear, and would serve as a good preamble to the code I'm going to present below.</p>
<p>Andrej gave a related invited talk back at <a href="http://msfp.org.uk/">MSFP 2008</a> in Iceland, and afterwards over lunch I cornered him (with Dan Piponi) and explained how you could use parametricity to close over the side-effects of monads (or arrows, etc) but I think that trick was lost in the chaos of the weekend, so I've chosen to resurrect it here, and improve it to handle some of his more recent performance enhancements, and show that you don't need side-effects to speed up the search after all!</p>
<p><span id="more-510"></span></p>
<p>First, we'll need to import a few things:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# LANGUAGE RankNTypes #-}</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">import</span> Data.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe"><span style="background-color: #efefbf; font-weight: bold;">Maybe</span></a> <span style="color: green;">&#40;</span>fromMaybe<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Control.Applicative
<span style="color: #06c; font-weight: bold;">import</span> Data.IntMap <span style="color: green;">&#40;</span>IntMap<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> <span style="color: #06c; font-weight: bold;">qualified</span> Data.IntMap <span style="color: #06c; font-weight: bold;">as</span> IntMap
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a>
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a>.Trans.Class
<span style="color: #06c; font-weight: bold;">import</span> Data.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>.Identity
&nbsp;</pre>
<p>What are looking for is an implementation of <a href="http://en.wikipedia.org/wiki/Epsilon_calculus">Hilbert's epsilon</a>. </p>
<p>This is a formal mechanism for eliminating existentials over some non-empty set <strong>X</strong> by defining a function</p>
<pre class="haskell">&nbsp;
ε: <span style="color: green;">&#40;</span>X -&gt; Prop<span style="color: green;">&#41;</span> -&gt; X
&nbsp;</pre>
<p>such that if there exists an <em>x</em> in <strong>X</strong> such that <em>p</em>(<strong>X</strong>) holds then <em>p</em>(<em>ε</em>(<em>p</em>)) holds.</p>
<p>As noted by Andrej, we could reify this constructively as a function "epsilon :: (X -> Bool) -> X" for some X.</p>
<p>Now, for some sets, Hilbert's epsilon is really easy to define. If X is a finite set, you can just exhaustively enumerate all of the options returning a member of X such that the property holds if any of them do, otherwise since X is non-empty, just return one of the elements that you tested.</p>
<p>This would be a pretty boring article and I'd be back to eating Christmas dinner with my family if that was all there was to it. However, certain infinite spaces can also be searched.</p>
<p>Last year, Luke Palmer wrote a post on <a href="http://lukepalmer.wordpress.com/2010/11/17/searchable-data-types/">"Searchable Data Types"</a> that might also serve as a good introduction. In that article he led off with the easiest infinite space to search, the lazy naturals, or the 'one point compactification of the naturals'. That is to say the natural numbers extended with infinity.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> LazyNat = Zero | Succ LazyNat
infinity :: LazyNat
infinity = Succ infinity
&nbsp;</pre>
<p>Now we can implement Palmer's epsilon (called <code>lyingSearch</code> in his article).</p>
<pre class="haskell">&nbsp;
palmer :: <span style="color: green;">&#40;</span>LazyNat -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; LazyNat
palmer p
  | p Zero = Zero
  | <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:otherwise"><span style="font-weight: bold;">otherwise</span></a> = Succ $ palmer $ p . Succ
&nbsp;</pre>
<p>The trick to making this work is that we place a requirement that the predicate that you pass has to terminate in a bounded amount of time no matter what input you give it, and since we're working with the naturals extended with <code>infinity</code>, if no natural satisfies the predicate, we'll just keep returning a longer and longer chain of <code>Succ</code>'s, effectively yielding <code>infinity</code>. </p>
<p>To check to see if the returned number satisfies the predicate you can always use <code>p (palmer p)</code>. The predicate is required to terminate in finite time, even when given infinity, so this will yield a Bool and not bottom out unless the user supplied predicate takes an unbounded amount of time.</p>
<p>I posted a reply to Luke's article when it came up on reddit which included a Hinze-style generic implementation of his <code>lyingSearch</code> predicate, which you can see now is just Hilbert's epsilon for arbitrary recursive polynomial data types.</p>
<p><a href="http://www.reddit.com/r/haskell/comments/e7nij/searchable_data_types/c15zs6l">http://www.reddit.com/r/haskell/comments/e7nij/searchable_data_types/c15zs6l</a></p>
<p>Another space we can search is <a href="http://en.wikipedia.org/wiki/Cantor_space">the Cantor space</a> 2^N.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Cantor = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a>
&nbsp;</pre>
<p>With that we jump clear from countable infinity to uncountable infinity, but it can still be searched in finite time!</p>
<p>This is the space we'll be paying attention to for the rest of this article.</p>
<p>First we'll define how to "<a href="http://en.wikipedia.org/wiki/Hilbert's_paradox_of_the_Grand_Hotel">book a room in Hilbert's Hotel</a>."</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixr</span> <span style="color: red;">0</span> #
<span style="color: green;">&#40;</span>#<span style="color: green;">&#41;</span> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a> -&gt; Cantor -&gt; Cantor
<span style="color: green;">&#40;</span>x # a<span style="color: green;">&#41;</span> <span style="color: red;">0</span> = x
<span style="color: green;">&#40;</span>x # a<span style="color: green;">&#41;</span> i = a <span style="color: green;">&#40;</span>i - <span style="color: red;">1</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Then this can be used to obtain the following implementation of Hilbert's epsilon for the Cantor space, attributed by Andrej to Ulrich Berger.</p>
<pre class="haskell">&nbsp;
berger :: <span style="color: green;">&#40;</span>Cantor -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; Cantor
berger p =
  <span style="color: #06c; font-weight: bold;">if</span> ex $ \a -&gt; p $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> # a
  <span style="color: #06c; font-weight: bold;">then</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> # berger $ \a -&gt; p $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> # a
  <span style="color: #06c; font-weight: bold;">else</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>  # berger $ \a -&gt; p $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a> # a
  <span style="color: #06c; font-weight: bold;">where</span> ex q = q <span style="color: green;">&#40;</span>berger q<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>This version is particularly close in structure to the one for searching the LazyNats, but it is dreadfully slow!</p>
<p>It would be nice to be able to search the space faster and that is just what Martin Escardo's improved version does, through a more sophisticated divide and conquer technique.</p>
<pre class="haskell">&nbsp;
escardo :: <span style="color: green;">&#40;</span>Cantor -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; Cantor
escardo p = go x l r <span style="color: #06c; font-weight: bold;">where</span>
  go x l r n =  <span style="color: #06c; font-weight: bold;">case</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:divMod"><span style="font-weight: bold;">divMod</span></a> n <span style="color: red;">2</span> <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span><span style="color: red;">0</span>, <span style="color: red;">0</span><span style="color: green;">&#41;</span> -&gt; x
    <span style="color: green;">&#40;</span>q, <span style="color: red;">1</span><span style="color: green;">&#41;</span> -&gt; l q
    <span style="color: green;">&#40;</span>q, <span style="color: red;">0</span><span style="color: green;">&#41;</span> -&gt; r $ q<span style="color: red;">-1</span>
  x = ex $ \l -&gt; ex $ \r -&gt; p $ go <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a> l r
  l = escardo $ \l -&gt; ex $ \r -&gt; p $ go x l r
  r = escardo $ \r -&gt; p $ go x l r
  ex q = q <span style="color: green;">&#40;</span>escardo q<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>To proceed from here I'll need a State monad:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> S s a = S <span style="color: green;">&#123;</span> runS :: s -&gt; <span style="color: green;">&#40;</span>a, s<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>S s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>S m<span style="color: green;">&#41;</span> = S $ \s -&gt; <span style="color: #06c; font-weight: bold;">case</span> m s <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span>a, s'<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f a, s'<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Applicative <span style="color: green;">&#40;</span>S s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a>
  <span style="color: green;">&#40;</span>&lt; *&gt;<span style="color: green;">&#41;</span> = ap
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>S m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = S $ \s -&gt; <span style="color: green;">&#40;</span>a, s<span style="color: green;">&#41;</span>
  S m &gt;&gt;= k = S $ \s -&gt; <span style="color: #06c; font-weight: bold;">case</span> m s <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span>a, s'<span style="color: green;">&#41;</span> -&gt; runS <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> s'
&nbsp;</pre>
<p>And now we've reached the point. From here,  Andrej's pure code ends, and his side-effecting ocaml and custom programming language start. The first thing he does is compute the modulus of continuity by using a side-effect that writes to a reference cell which he very carefully ensures doesn't leak out of scope, so he doesn't have to concern himself with the proposition code editing the value of the reference.</p>
<pre class="ocaml">&nbsp;
<span style="color: #06c; font-weight: bold;">let</span> mu f a =
  <span style="color: #06c; font-weight: bold;">let</span> r = <span style="color: #06c; font-weight: bold;">ref</span> <span style="color: #c6c;">0</span> <span style="color: #06c; font-weight: bold;">in</span>
  <span style="color: #06c; font-weight: bold;">let</span> b n = <span style="color: #6c6;">&#40;</span>r := <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALmax"><span style="">max</span></a> n ! r; a n<span style="color: #6c6;">&#41;</span> <span style="color: #06c; font-weight: bold;">in</span>
    <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html#VALignore"><span style="">ignore</span></a> <span style="color: #6c6;">&#40;</span>f b<span style="color: #6c6;">&#41;</span>;
    !r
&nbsp;</pre>
<p>To obtain the same effect we'll instead make a predicate using the state monad to model the single reference cell. </p>
<pre lang="haskell'>
modulus phi alpha = snd $ runS (phi beta) 0 where
  beta n = S $ \ i -> (alpha n, max i n)
</pre>
<p>But now, we've lost the safety that was implied by the local lexical scope. If we let the type checker give us a type we obtain:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- bad</span>
modulus :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> b, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="background-color: #efefbf; font-weight: bold;">Ord</span></a> s<span style="color: green;">&#41;</span> =&gt;
  <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>s -&gt; S s a<span style="color: green;">&#41;</span> -&gt; S b c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>s -&gt; a<span style="color: green;">&#41;</span> -&gt; b
&nbsp;</pre>
<p>We can mash b and s together, and try to make the ordering and number agree by claiming that it is instead Real and we'd get the slightly more reasonable looking type:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- still bad</span>
modulus :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Real"><span style="background-color: #efefbf; font-weight: bold;">Real</span></a> a =&gt;
  <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a -&gt; S n b<span style="color: green;">&#41;</span> -&gt; S n c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt; a
&nbsp;</pre>
<p>In the imperative code, lexical scoping had ensured that no other code could edit the reference cell, but with this type we don't have that. The predicate is allowed to use arbitrary state actions to muck with the modulus of convergence even though the only thing that should be editing it is the wrapper beta that we placed around alpha.</p>
<p>But how can we ensure that the end user couldn't gain access to any of the additional functionality from the monad? Parametricity!</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- getting better</span>
modulus :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Real"><span style="background-color: #efefbf; font-weight: bold;">Real</span></a> a =&gt;
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f =&gt; <span style="color: green;">&#40;</span>a -&gt; f b<span style="color: green;">&#41;</span> -&gt; f c<span style="color: green;">&#41;</span> -&gt;
  <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt;
  a
&nbsp;</pre>
<p>Here the only thing you are allowed to assume about f is that it forms a monad. This gives you access to return and >>=, but the predicate can't do anything interesting with them. All it can do is work with what is effectively the identity monad, since it knows no additional properties!</p>
<p>We can have mercy on the end user and give them a little bit more syntactic sugar, since it doesn't cost us anything to let them also have access to the Applicative instance.</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- good</span>
modulus :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Real"><span style="background-color: #efefbf; font-weight: bold;">Real</span></a> a =&gt;
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f, Applicative f<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>a -&gt; f b<span style="color: green;">&#41;</span> -&gt; f c<span style="color: green;">&#41;</span> -&gt;
  <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt;
  a
&nbsp;</pre>
<p>With that we can show Andrej's version of the modulus of convergence calculation does not need side-effects!</p>
<pre class="haskell">&gt;
&gt; modulus <span style="color: green;">&#40;</span>\a -&gt; a <span style="color: red;">10</span> &gt;&gt;= a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>\n -&gt; n * n<span style="color: green;">&#41;</span>
<span style="color: red;">100</span>
&nbsp;</pre>
<p>Admittedly plumbing around the monadic values in our proposition is a bit inconvenient.</p>
<p>His next example was written in a custom ocaml-like programming language. For translating his effect type into Haskell using parametricity, we'll need a CPS'd state monad, so we can retry from the current continuation while we track a map of assigned values.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> K r s a = K <span style="color: green;">&#123;</span> runK :: <span style="color: green;">&#40;</span>a -&gt; s -&gt; r<span style="color: green;">&#41;</span> -&gt; s -&gt; r <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>K r s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> = liftM
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Applicative <span style="color: green;">&#40;</span>K r s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a>
  <span style="color: green;">&#40;</span>&lt; *&gt;<span style="color: green;">&#41;</span> = ap
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>K r s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = K $ \k -&gt; k a
  K m &gt;&gt;= f = K $ \k -&gt; m $ \a -&gt; runK <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> k
&nbsp;</pre>
<p>For those of you who have been paying attention to my previous posts, <code>K r s</code> is just a <code>Codensity</code> monad!</p>
<pre class="haskell">&nbsp;
neighborhood ::
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <span style="color: green;">&#40;</span>Applicative f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt;
  IntMap <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a>
neighborhood phi = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> $ runK <span style="color: green;">&#40;</span>phi beta<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span> IntMap.empty <span style="color: #06c; font-weight: bold;">where</span>
  beta n = K $ \k s -&gt; <span style="color: #06c; font-weight: bold;">case</span> IntMap.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:lookup"><span style="font-weight: bold;">lookup</span></a> n s <span style="color: #06c; font-weight: bold;">of</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Just"><span style="font-weight: bold;">Just</span></a> b -&gt; k b s
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Nothing"><span style="font-weight: bold;">Nothing</span></a> -&gt; <span style="color: #06c; font-weight: bold;">case</span> k <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a> <span style="color: green;">&#40;</span>IntMap.insert n <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a> s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">of</span>
      <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>, _<span style="color: green;">&#41;</span> -&gt; k <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> <span style="color: green;">&#40;</span>IntMap.insert n <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> s<span style="color: green;">&#41;</span>
      r -&gt; r
&nbsp;</pre>
<p>With that we can adapt the final version of Hilbert's epsilon for the Cantor space that Andrej provided to run in pure Haskell.</p>
<pre class="haskell">&nbsp;
bauer ::
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <span style="color: green;">&#40;</span>Applicative f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt;
  Cantor
bauer p = \n -&gt; fromMaybe <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a> $ IntMap.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:lookup"><span style="font-weight: bold;">lookup</span></a> n m <span style="color: #06c; font-weight: bold;">where</span>
  m = neighborhood p
&nbsp;</pre>
<p>With a little work you can implement a version of an exists and forAll predicate on top of that by running them through the identity monad. </p>
<pre class="haskell">&nbsp;
exists ::
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <span style="color: green;">&#40;</span>Applicative f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt;
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a>
forAll ::
  <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> f. <span style="color: green;">&#40;</span>Applicative f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt;
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a>
&nbsp;</pre>
<p>I've gone further in playing with this idea, using monad homomorphisms rather than simply relying on the canonical homomorphism from the identity monad. You can get the gist of it here:</p>
<p><a href="https://gist.github.com/1518767">https://gist.github.com/1518767</a></p>
<p>This permits the predicates themselves to embed some limited monadic side-effects, but then you get more extensional vs. intensional issues.</p>
<p>An obvious direction from here is to fiddle with a version of Martin Escardo's search monad that takes advantage of these techniques, but I'll leave the exploration of these ideas to the reader for now and go enjoy Christmas dinner.</p>
<p>Happy Holidays,<br />
Edward Kmett</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/searching-infinity/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>A Product of an Imperfect Union</title>
		<link>http://comonad.com/reader/2011/a-product-of-an-imperfect-union/</link>
		<comments>http://comonad.com/reader/2011/a-product-of-an-imperfect-union/#comments</comments>
		<pubDate>Fri, 01 Jul 2011 03:49:10 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Monads]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=337</guid>
		<description><![CDATA[In the last few posts, I've been talking about how we can derive monads and monad transformers from comonads. Along the way we learned that there are more monads than comonads in Haskell.
The question I hope to answer this time, is whether or not we turn any Haskell Comonad into a comonad transformer.

Comonads from Comonads
In [...]]]></description>
			<content:encoded><![CDATA[<p>In the last few posts, I've been talking about how we can derive <a href="http://comonad.com/reader/2011/monads-from-comonads/">monads</a> and <a href="http://comonad.com/reader/2011/monad-transformers-from-comonads/">monad transformers</a> from comonads. Along the way we learned that there are more monads than comonads in Haskell.</p>
<p>The question I hope to answer this time, is whether or not we turn any Haskell <code>Comonad</code> into a <a href="http://hackage.haskell.org/packages/archive/comonad-transformers/1.8.0/doc/html/Control-Comonad-Trans-Class.html">comonad transformer</a>.</p>
<p><span id="more-337"></span></p>
<p><strong>Comonads from Comonads</strong></p>
<p>In <a href="http://comonad.com/reader/2011/monads-from-comonads/">Monads from Comonads</a>, we built the comonad-to-monad transformer</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Co w m a = Co <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. w <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>by sandwiching a <code>Comonad</code> <em>w</em> in the middle of a trivial Codensity monad, then proceeded to show that at least in the case where our comonad was given rise to by an adjunction <code>f -| g : Hask -> Hask</code>, we could reason about this as if we had</p>
<pre class="haskell">&nbsp;
Co w ~ Co <span style="color: green;">&#40;</span>f . g<span style="color: green;">&#41;</span> ~ g . f
&nbsp;</pre>
<p>Now, <code>Codensity</code> monads are a right <a href="http://en.wikipedia.org/wiki/Kan_extension">Kan extension</a>. </p>
<p>So, what happens if we try to do the same thing to a Left Kan extension?</p>
<p>Using</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# LANGUAGE GADTs, FlexibleInstances #-}</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a>
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a>.Trans.Class
&nbsp;</pre>
<p>we can define</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> L w a <span style="color: #06c; font-weight: bold;">where</span>
  L :: w <span style="color: green;">&#40;</span>r -&gt; a<span style="color: green;">&#41;</span> -&gt; r -&gt; L w a
&nbsp;</pre>
<p>and a number of instances pop out for free, cribbed largely from the definition for Density.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>L w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>L w r<span style="color: green;">&#41;</span> = L <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>f .<span style="color: green;">&#41;</span> w<span style="color: green;">&#41;</span> r
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> ComonadTrans L <span style="color: #06c; font-weight: bold;">where</span>
  lower <span style="color: green;">&#40;</span>L w r<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>$r<span style="color: green;">&#41;</span> w
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Extend w =&gt; Extend <span style="color: green;">&#40;</span>L w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a> <span style="color: green;">&#40;</span>L w s<span style="color: green;">&#41;</span> = L <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> L w<span style="color: green;">&#41;</span> s
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> <span style="color: green;">&#40;</span>L w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> <span style="color: green;">&#40;</span>L w r<span style="color: green;">&#41;</span> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> w r
&nbsp;</pre>
<p>Reasoning as before about <code>w</code> as if it were composed of an adjunction <code>f -| g : Hask -> Hask</code> to build some intuition, we can see:</p>
<pre class="haskell">&nbsp;
L w a ~ exists r. <span style="color: green;">&#40;</span>w <span style="color: green;">&#40;</span>r -&gt; a<span style="color: green;">&#41;</span>, r<span style="color: green;">&#41;</span>
      ~ exists r. <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>g <span style="color: green;">&#40;</span>r -&gt; a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>, r<span style="color: green;">&#41;</span>
      ~ exists r. <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>, g <span style="color: green;">&#40;</span>r -&gt; a<span style="color: green;">&#41;</span>, r<span style="color: green;">&#41;</span>
      ~ exists r. <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>, f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; r -&gt; a, r<span style="color: green;">&#41;</span>
      ~ exists r. <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; r -&gt; a, f r<span style="color: green;">&#41;</span>
      ~ exists r. <span style="color: green;">&#40;</span>f r -&gt; a, f r<span style="color: green;">&#41;</span>
      ~ Density f a
      ~ <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f f a
      ~ <span style="color: green;">&#40;</span>f . <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f Id<span style="color: green;">&#41;</span> a
      ~ <span style="color: green;">&#40;</span>f . g<span style="color: green;">&#41;</span> a
      ~ w a
&nbsp;</pre>
<p>The latter few steps require identities established in my <a href="http://comonad.com/reader/2008/kan-extensions-ii/">second post on Kan extensions</a>.</p>
<p>With that we obtain the "remarkable" insight that <code>L ~ IdentityT</code>, which I suppose is much more obvious when just looking at the type</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> L w a <span style="color: #06c; font-weight: bold;">where</span>
  L :: w <span style="color: green;">&#40;</span>r -&gt; a<span style="color: green;">&#41;</span> -&gt; r -&gt; L w a
&nbsp;</pre>
<p>and seeing the existentially quantified <code>r</code> as a piece of the environment, being used to build an <code>a</code>, since there is nothing else we can do with it, except pass it in to each function wrapped by <code>w</code>! So at first blush, we've gained nothing.</p>
<p>The key observation is that in one case we would up with something isomorphic to the codensity monad of our right adjoint, while in the other case we would up with the density comonad of our left adjoint. The former is isomorphic to the monad given by our adjunction, while the latter is isomorphic to the comonad, which is, unfortunately, right where we started!</p>
<p><strong>In The Future All Comonads are Comonad Transformers!</strong></p>
<p>Of course, we don't have to just modify a trivial left Kan extension. Let's tweak the <code>Density</code> comonad of another comonad!</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> D f w a <span style="color: #06c; font-weight: bold;">where</span>
  D :: w <span style="color: green;">&#40;</span>f r -&gt; a<span style="color: green;">&#41;</span> -&gt; f r -&gt; D f w a
&nbsp;</pre>
<p>Since both arguments will be comonads, and I want this to be a comonad transformer, I'm going to swap the roles of the arguments relative to the definition of <code>CoT w m</code>. The reason is that <code>D f w</code> is a Comonad, regardless of the properties of f, so long as <code>w</code> is a <code>Comonad</code> This is similar to how <code>Density f</code> is a Comonad regardless of what <code>f</code> is, as long as it has kind <code>* -> *</code>.</p>
<p>The implementation of <code>D</code> is identical to <code>L</code> above, just as <code>CoT</code> and <code>Co</code> share implementations and <code>ContT</code> and <code>Cont</code> do.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>D f w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>D w r<span style="color: green;">&#41;</span> = D <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>f .<span style="color: green;">&#41;</span> w<span style="color: green;">&#41;</span> r
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Extend w =&gt; Extend <span style="color: green;">&#40;</span>D f w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a> <span style="color: green;">&#40;</span>D w s<span style="color: green;">&#41;</span> = D <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> D w<span style="color: green;">&#41;</span> s
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> <span style="color: green;">&#40;</span>D f w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> <span style="color: green;">&#40;</span>D w r<span style="color: green;">&#41;</span> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> w r
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> ComonadTrans <span style="color: green;">&#40;</span>D f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  lower <span style="color: green;">&#40;</span>D w r<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>$r<span style="color: green;">&#41;</span> w
&nbsp;</pre>
<p>But in addition to being able to <code>lower :: D f w a -> w a</code>, we can also lower to the other comonad!</p>
<pre class="haskell">&nbsp;
fstD :: <span style="color: green;">&#40;</span>Extend f, <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w<span style="color: green;">&#41;</span> =&gt; D f w a -&gt; f a
fstD <span style="color: green;">&#40;</span>D w r<span style="color: green;">&#41;</span> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> w<span style="color: green;">&#41;</span> r
&nbsp;
sndD :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; D f w a -&gt; w a
sndD = lower
&nbsp;</pre>
<p>This means that if either comonad provides us with a piece of functionality we can exploit it.</p>
<p><strong>Selling Products</strong></p>
<p>In general Monad products always exist:</p>
<pre>
newtype Product m n a = Pair { runFst :: m a, runSnd :: n a }

instance (Monad m, Monad n) => Monad (Product m n) where
   return a = Pair (return a) (return a)
   Pair ma na >>= f = Pair (ma >>= runFst . f) (na >>= runSnd . f)
</pre>
<p>and Comonad coproducts always exist:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Coproduct f g a = Coproduct <span style="color: green;">&#123;</span> getCoproduct :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a> <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
&nbsp;
left :: f a -&gt; Coproduct f g a
left = Coproduct . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Left"><span style="font-weight: bold;">Left</span></a>
&nbsp;
right :: g a -&gt; Coproduct f g a
right = Coproduct . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a>
&nbsp;
coproduct :: <span style="color: green;">&#40;</span>f a -&gt; b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>g a -&gt; b<span style="color: green;">&#41;</span> -&gt; Coproduct f g a -&gt; b
coproduct f g = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:either"><span style="font-weight: bold;">either</span></a> f g . getCoproduct
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Extend f, Extend g<span style="color: green;">&#41;</span> =&gt; Extend <span style="color: green;">&#40;</span>Coproduct f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> f = Coproduct . coproduct
    <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Left"><span style="font-weight: bold;">Left</span></a> . <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span>f . Coproduct . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Left"><span style="font-weight: bold;">Left</span></a><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
    <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a> . <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span>f . Coproduct . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> f, <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> g<span style="color: green;">&#41;</span> =&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> <span style="color: green;">&#40;</span>Coproduct f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> = coproduct <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a>
&nbsp;</pre>
<p>but Christoph Lüth and Neil Ghani showed that <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.8.3581">monad coproducts don't always exist</a>!</p>
<p>On the other hand what we built up above looks a lot like a comonad product!</p>
<p>Too see that, first we'll note some of the product-like things we can do:</p>
<p><code>fstD</code> and <code>sndD</code> act a lot like <code>fst</code> and <code>snd</code>, projecting our parts of our product and it turns out we can "braid" our almost-products, interchanging the left and right hand side. </p>
<pre class="haskell">&nbsp;
braid :: <span style="color: green;">&#40;</span>Extend f, <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w<span style="color: green;">&#41;</span> =&gt; D f w a -&gt; D w f a
braid <span style="color: green;">&#40;</span>D w r<span style="color: green;">&#41;</span> = D <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a><span style="color: green;">&#41;</span> r<span style="color: green;">&#41;</span> w
&nbsp;</pre>
<p>(I use scary air-quotes around braid, because it doesn't let us braid them in a categorical sense, as we'll see.)</p>
<p>After braiding, one of our projections swaps places as we'd expect:</p>
<pre class="haskell">&nbsp;
sndD <span style="color: green;">&#40;</span>braid <span style="color: green;">&#40;</span>D w r<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> = <span style="color: #5d478b; font-style: italic;">-- by braid def</span>
sndD <span style="color: green;">&#40;</span>D <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a><span style="color: green;">&#41;</span> r<span style="color: green;">&#41;</span> w<span style="color: green;">&#41;</span> = <span style="color: #5d478b; font-style: italic;">-- by sndD (and lower) def</span>
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>$w<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a><span style="color: green;">&#41;</span> r<span style="color: green;">&#41;</span> = <span style="color: #5d478b; font-style: italic;">-- extend fmap fusion</span>
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>$w<span style="color: green;">&#41;</span> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a><span style="color: green;">&#41;</span> r = <span style="color: #5d478b; font-style: italic;">-- @unpl</span>
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span>\t -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> t w<span style="color: green;">&#41;</span> r = <span style="color: #5d478b; font-style: italic;">-- flip . flip = id</span>
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> w<span style="color: green;">&#41;</span> r = <span style="color: #5d478b; font-style: italic;">-- by fstD def</span>
fstD <span style="color: green;">&#40;</span>D w r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>But we stall when we try to show <code>fstD . braid = sndD</code>.</p>
<p>Why is that?</p>
<p><strong>A Product of an Imperfect Union</strong></p>
<p><a href="http://comonad.com/reader/2011/more-on-comonads-as-monad-transformers/">Last time</a>, when we inspected <code>CoT w m a</code> we demonstrated that on one hand given a suitable adjunction <code>f -| g</code>, such that <code>w = f . g</code>, <code>Co w ~ Co (f . g) ~ (g . f)</code>, but on the other <code>CoT w m a</code> was bigger than <code>g . m . f</code>, and that if n -| m, then <code>CoT w m a ~ g . m . n . f</code>. </p>
<p>Of course, these two results agree, if you view <code>Co w</code> as <code>CoT w Identity</code>, where <code>Identity -| Identity</code>, since <code>Identity ~ Identity . Identity</code></p>
<p>Therefore it should come as no surprise that given <code>w = f . g</code>, for a suitable adjunction <code>f -| g</code>, then <code>D w j a</code> is bigger than <code>f . j . g</code>. In fact if, <code>j -| k</code>, then <code>D w j ~ f . j . k . g</code>.</p>
<p>So what is happening is that we have only managed to "break one of our comonads in half", and <code>D w j a</code> lets you do 'too much stuff' with the <code>j</code> portion of the comonad. This keeps us from being symmetric.</p>
<p>Moreover it turns out to be a bit trickier to build one than to just hand in a <code>w (f a)</code> or <code>w a</code> and an <code>f a</code> to build our product-like construction.</p>
<p>Even so, exploiting Density <em>was</em> enough to transform any comonad into a comonad-transformer and to enable us to access the properties of either the comonad we are transforming with, or the comonad that we are transforming.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/a-product-of-an-imperfect-union/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>More on Comonads as Monad Transformers</title>
		<link>http://comonad.com/reader/2011/more-on-comonads-as-monad-transformers/</link>
		<comments>http://comonad.com/reader/2011/more-on-comonads-as-monad-transformers/#comments</comments>
		<pubDate>Thu, 30 Jun 2011 19:15:22 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Monads]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=328</guid>
		<description><![CDATA[Last time in Monad Transformers from Comonads I showed that given any comonad we can derive the monad-transformer
&#160;
newtype CoT w m a = CoT &#123; runCoT :: w &#40;a -&#62; m r&#41; -&#62; m r
&#160;
and so demonstrated that there are fewer comonads than monads in Haskell, because while every Comonad gives rise to a Monad [...]]]></description>
			<content:encoded><![CDATA[<p>Last time in <a href="http://comonad.com/reader/2011/monad-transformers-from-comonads/">Monad Transformers from Comonads</a> I showed that given any comonad we can derive the monad-transformer</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> CoT w m a = CoT <span style="color: green;">&#123;</span> runCoT :: w <span style="color: green;">&#40;</span>a -&gt; m r<span style="color: green;">&#41;</span> -&gt; m r
&nbsp;</pre>
<p>and so demonstrated that there are fewer comonads than monads in Haskell, because while every Comonad gives rise to a Monad transformer, there are Monads that do not like <code>IO</code>, <code>ST s</code>, and <code>STM</code>.</p>
<p>I want to elaborate a bit more on this topic.</p>
<p><span id="more-328"></span></p>
<p>In <a href="http://comonad.com/reader/2011/monads-from-comonads/">Monads from Comonads</a> we observed that for non-transformer version of <code>CoT</code></p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Co w = CoT w Identity
&nbsp;</pre>
<p>under the assumption that <code>w = f . g</code> for <code>f -| g : Hask -> Hask</code>, then </p>
<pre class="haskell">&nbsp;
Co w ~ Co <span style="color: green;">&#40;</span>f . g<span style="color: green;">&#41;</span> ~ g . f
&nbsp;</pre>
<p>This demonstrated that the <code>Co w</code> is isomorphic to the monad we obtain by composing the adjunction that gave rise to our comonad the other way around.</p>
<p>But what about <code>CoT</code>?</p>
<p>Sadly <code>CoT</code> is a bit bigger.</p>
<p>We can see by first starting to apply the same treatment that we gave <code>Co</code>.</p>
<pre class="haskell">&nbsp;
CoT w m a ~ <span style="color: #06c; font-weight: bold;">forall</span> r. w <span style="color: green;">&#40;</span>a -&gt; m r<span style="color: green;">&#41;</span> -&gt; m r
          ~ <span style="color: #06c; font-weight: bold;">forall</span> r. f <span style="color: green;">&#40;</span>g <span style="color: green;">&#40;</span>a -&gt; m r<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; m r
          ~ <span style="color: #06c; font-weight: bold;">forall</span> r. f <span style="color: green;">&#40;</span>f<span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; a -&gt; m r<span style="color: green;">&#41;</span> -&gt; m r
          ~ <span style="color: #06c; font-weight: bold;">forall</span> r. f <span style="color: green;">&#40;</span>a -&gt; f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; m r<span style="color: green;">&#41;</span> -&gt; m r
          ~ <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; m r, f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; m r
          ~ <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; m r<span style="color: green;">&#41;</span> -&gt; f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; m r
          ~ <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; g <span style="color: green;">&#40;</span>m r<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; g <span style="color: green;">&#40;</span>m r<span style="color: green;">&#41;</span>
          ~ Codensity <span style="color: green;">&#40;</span>g . m<span style="color: green;">&#41;</span> a
&nbsp;</pre>
<p>(I'm using <code>.</code> to represent <code>Compose</code> for readability.)</p>
<p>But we've seen before that <code>Codensity g a</code> is in a sense bigger than <code>g a</code>, since given an Adjunction <code>f -| g</code>, <code>Codensity g a ~ (g . f) a</code>, <strong>not</strong> <code>g a</code>.</p>
<p>Moreover can compose adjunctions:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span>
    <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g, <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f' g'<span style="color: green;">&#41;</span> =&gt;
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> <span style="color: green;">&#40;</span>Compose f' f<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Compose g g'<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:unit"><span style="font-weight: bold;">unit</span></a>   = Compose . <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> Compose<span style="color: green;">&#41;</span>
  <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:counit"><span style="font-weight: bold;">counit</span></a> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> getCompose<span style="color: green;">&#41;</span> . getCompose
&nbsp;</pre>
<p>So if <code>n -| m</code>, then we can see that <code>Codensity (g . m) a ~ g . m . n . f</code>, rather than the smaller <code>g . m . f</code>, which we can obtain using  <code>AdjointT f g m</code> from <a href="http://hackage.haskell.org/packages/archive/adjunctions/1.8.0/doc/html/Control-Monad-Trans-Adjoint.html">Control.Monad.Trans.Adjoint</a> in <a href="http://hackage.haskell.org/package/adjunctions">adjunctions</a>.</p>
<p>So <code>CoT</code> isn't the smallest monad transformer that would be given by an adjunction. </p>
<p>In fact, it is isomorphic to <code>AdjointT f g (Codensity m) a</code> instead of <code>AdjointT f g m a</code>.</p>
<p>Sadly, there doesn't appear to be a general purpose construction of the smaller transformer just given an unseparated <code>w = f . g</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/more-on-comonads-as-monad-transformers/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Monad Transformers from Comonads</title>
		<link>http://comonad.com/reader/2011/monad-transformers-from-comonads/</link>
		<comments>http://comonad.com/reader/2011/monad-transformers-from-comonads/#comments</comments>
		<pubDate>Wed, 29 Jun 2011 01:51:43 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Monads]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=321</guid>
		<description><![CDATA[Last time, I showed that we can transform any Comonad in Haskell into a Monad in Haskell.
Today, I'll show that we can go one step further and derive a monad transformer from any comonad! 

A Comonad to Monad-Transformer Transformer
Given
&#160;
newtype CoT w m a = CoT &#123; runCoT :: forall r. w &#40;a -&#62; m r&#41; [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://comonad.com/reader/2011/monads-from-comonads/">Last time</a>, I showed that we can transform any Comonad in Haskell into a Monad in Haskell.</p>
<p>Today, I'll show that we can go one step further and derive a monad transformer from any comonad! </p>
<p><span id="more-321"></span></p>
<p><strong>A Comonad to Monad-Transformer Transformer</strong></p>
<p>Given</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> CoT w m a = CoT <span style="color: green;">&#123;</span> runCoT :: <span style="color: #06c; font-weight: bold;">forall</span> r. w <span style="color: green;">&#40;</span>a -&gt; m r<span style="color: green;">&#41;</span> -&gt; m r <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>we can easily embed the type of the previous <code>Co</code> and create a smart constructor and deconstructor in the style of the MTL.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Co w = CoT w Identity
&nbsp;
co :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w =&gt; <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. w <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; Co w a
co f = CoT <span style="color: green;">&#40;</span>Identity . f . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> runIdentity<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
runCo :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w =&gt; Co w a -&gt; w <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; r
runCo m = runIdentity . runCoT m . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> Identity<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>In fact, as with between Cont and ContT, none of the major instances even change!</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>CoT w m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>CoT w<span style="color: green;">&#41;</span> = CoT <span style="color: green;">&#40;</span>w . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>. f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Extend w =&gt; Apply <span style="color: green;">&#40;</span>CoT w m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  mf &lt; .&gt; ma = mf &gt;&gt;- \f -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f ma
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Extend w =&gt; Bind <span style="color: green;">&#40;</span>CoT w m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  CoT k &gt;&gt;- f = CoT <span style="color: green;">&#40;</span>k . <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span>\wa a -&gt; runCoT <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> wa<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; Applicative <span style="color: green;">&#40;</span>CoT w m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure a = CoT <span style="color: green;">&#40;</span>`<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a>` a<span style="color: green;">&#41;</span>
  mf &lt; *&gt; ma = mf &gt;&gt;= \f -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f ma
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>CoT w m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = CoT <span style="color: green;">&#40;</span>`<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a>` a<span style="color: green;">&#41;</span>
  CoT k &gt;&gt;= f = CoT <span style="color: green;">&#40;</span>k . <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span>\wa a -&gt; runCoT <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> wa<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>We can use CoT as a Monad transformer, or lift IO actions:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; MonadTrans <span style="color: green;">&#40;</span>CoT w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  lift m = CoT <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>m &gt;&gt;=<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w, MonadIO m<span style="color: green;">&#41;</span> =&gt; MonadIO <span style="color: green;">&#40;</span>CoT w m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  liftIO = lift . liftIO
&nbsp;</pre>
<p>(This monad transformer is available in my <a href="http://hackage.haskell.org/package/kan-extensions">kan-extensions</a> package as of 1.9.0 on hackage.)</p>
<p>And as before we can lift and lower CoKleisli arrows, although the results are monadic when lowered.</p>
<pre class="haskell">&nbsp;
liftCoT0 :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> a. w a -&gt; s<span style="color: green;">&#41;</span> -&gt; CoT w m s
liftCoT0 f = CoT <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> &lt; *&gt; f<span style="color: green;">&#41;</span>
&nbsp;
lowerCoT0 :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m<span style="color: green;">&#41;</span> =&gt; CoT w m s -&gt; w a -&gt; m s
lowerCoT0 m = runCoT m . <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> &lt; $<span style="color: green;">&#41;</span>
&nbsp;
lowerCo0 :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w =&gt; Co w s -&gt; w a -&gt; s
lowerCo0 m = runIdentity . runCoT m . <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> &lt; $<span style="color: green;">&#41;</span>
&nbsp;
liftCoT1 :: <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> a. w a -&gt; a<span style="color: green;">&#41;</span> -&gt; CoT w m <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
liftCoT1 f = CoT <span style="color: green;">&#40;</span>`f` <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
lowerCoT1 :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m<span style="color: green;">&#41;</span> =&gt; CoT w m <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; w a -&gt; m a
lowerCoT1 m = runCoT m . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a><span style="color: green;">&#41;</span>
&nbsp;
lowerCo1 :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w =&gt; Co w <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; w a -&gt; a
lowerCo1 m = runIdentity . runCoT m . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Since we could mean the MonadFoo instance derived from its comonadic equivalent or from the one we wrap as a monad transformer, we choose to default to the one from the monad, but we can still provide the lifted comonadic actions:</p>
<pre class="haskell">&nbsp;
posW :: <span style="color: green;">&#40;</span>ComonadStore s w, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m<span style="color: green;">&#41;</span> =&gt; CoT w m s
posW = liftCoT0 pos
&nbsp;
peekW :: <span style="color: green;">&#40;</span>ComonadStore s w, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m<span style="color: green;">&#41;</span> =&gt; s -&gt; CoT w m <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
peekW s = liftCoT1 <span style="color: green;">&#40;</span>peek s<span style="color: green;">&#41;</span>
&nbsp;
peeksW :: <span style="color: green;">&#40;</span>ComonadStore s w, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>s -&gt; s<span style="color: green;">&#41;</span> -&gt; CoT w m <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
peeksW f = liftCoT1 <span style="color: green;">&#40;</span>peeks f<span style="color: green;">&#41;</span>
&nbsp;
askW :: <span style="color: green;">&#40;</span>ComonadEnv e w, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m<span style="color: green;">&#41;</span> =&gt; CoT w m e
askW = liftCoT0 <span style="color: green;">&#40;</span>Env.ask<span style="color: green;">&#41;</span>
&nbsp;
asksW :: <span style="color: green;">&#40;</span>ComonadEnv e w, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>e -&gt; a<span style="color: green;">&#41;</span> -&gt; CoT w m a
asksW f = liftCoT0 <span style="color: green;">&#40;</span>Env.asks f<span style="color: green;">&#41;</span>
&nbsp;
traceW :: <span style="color: green;">&#40;</span>ComonadTraced e w, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m<span style="color: green;">&#41;</span> =&gt; e -&gt; CoT w m <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
traceW e = liftCoT1 <span style="color: green;">&#40;</span>Traced.trace e<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and we just lift the monadic actions as usual:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w, MonadReader e m<span style="color: green;">&#41;</span> =&gt; MonadReader e <span style="color: green;">&#40;</span>CoT w m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  ask = lift Reader.ask
  local f m = CoT <span style="color: green;">&#40;</span>local f . runCoT m<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w, MonadState s m<span style="color: green;">&#41;</span> =&gt; MonadState s <span style="color: green;">&#40;</span>CoT w m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  get = lift get
  put = lift . put
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w, MonadWriter e m<span style="color: green;">&#41;</span> =&gt; MonadWriter e <span style="color: green;">&#40;</span>CoT w m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  tell = lift . tell
  pass m = CoT <span style="color: green;">&#40;</span>pass . runCoT m . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> aug<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    aug f <span style="color: green;">&#40;</span>a,e<span style="color: green;">&#41;</span> = liftM <span style="color: green;">&#40;</span>\r -&gt; <span style="color: green;">&#40;</span>r,e<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
  listen = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> <span style="color: #3c7331;">&quot;Control.Monad.Co.listen: TODO&quot;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w, MonadError e m<span style="color: green;">&#41;</span> =&gt; MonadError e <span style="color: green;">&#40;</span>CoT w m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  throwError = lift . throwError
  catchError = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> <span style="color: #3c7331;">&quot;Control.Monad.Co.catchError: TODO&quot;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w, MonadCont m<span style="color: green;">&#41;</span> =&gt; MonadCont <span style="color: green;">&#40;</span>CoT w m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  callCC = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> <span style="color: #3c7331;">&quot;Control.Monad.Co.callCC: TODO&quot;</span>
&nbsp;</pre>
<p>I welcome help working through the missing methods above.</p>
<p>This should go a long way towards showing the fact that there are strictly fewer comonads than monads in Haskell, and of course that there are no analogues to IO, STM and ST s in the world of Haskell comonads!</p>
<p>Every comonad gives you a monad-transformer, but not every monad is a monad transformer.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/monad-transformers-from-comonads/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Monads from Comonads</title>
		<link>http://comonad.com/reader/2011/monads-from-comonads/</link>
		<comments>http://comonad.com/reader/2011/monads-from-comonads/#comments</comments>
		<pubDate>Mon, 27 Jun 2011 20:50:32 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=291</guid>
		<description><![CDATA[Today I'll show that you can derive a Monad from any old Comonad you have lying around.

But first, we'll need to take a bit of a bit of a detour.
A Monad Sandwich
We'll need the definition of an adjunction on the category of Haskell types, which we can strip down and borrow from my adjunctions package.
&#160;
class [...]]]></description>
			<content:encoded><![CDATA[<p>Today I'll show that you can derive a <code>Monad</code> from any old <code>Comonad</code> you have lying around.</p>
<p><span id="more-291"></span></p>
<p>But first, we'll need to take a bit of a bit of a detour.</p>
<p><strong>A Monad Sandwich</strong></p>
<p>We'll need the definition of an <a href="http://en.wikipedia.org/wiki/Adjoint_functors">adjunction</a> on the category of Haskell types, which we can strip down and borrow from my <a href="http://hackage.haskell.org/package/adjunctions">adjunctions</a> package.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, Representable u<span style="color: green;">&#41;</span> =&gt;
         <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f u | f -&gt; u, u -&gt; f <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> :: <span style="color: green;">&#40;</span>f a -&gt; b<span style="color: green;">&#41;</span> -&gt; a -&gt; u b
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> :: <span style="color: green;">&#40;</span>a -&gt; u b<span style="color: green;">&#41;</span> -&gt; f a -&gt; b
&nbsp;</pre>
<p>Here we can define our Adjunction by defining leftAdjunct and rightAdjunct, such that they witness an isomorphism from <code>(f a -> b)</code> to <code>(a -> u b)</code></p>
<p>Every <a href="http://hackage.haskell.org/packages/archive/adjunctions/1.0.0/doc/html/Data-Functor-Adjunction.html">Adjunction</a> <code>F -| G : C -> D</code>, gives rise to a monad GF on D and a Comonad FG on C.</p>
<p>In addition to this, you can sandwich an additional monad M on C in between GF to give a monad GMF on D:</p>
<p><a href="http://hackage.haskell.org/packages/archive/adjunctions/1.0.0/doc/html/Control-Monad-Trans-Adjoint.html">Control.Monad.Trans.Adjoint</a></p>
<p>and you can sandwich a comonad W on D in between F and G to yield the comonad FWG on C:</p>
<p><a href="http://hackage.haskell.org/packages/archive/adjunctions/1.0.0/doc/html/Control-Comonad-Trans-Adjoint.html">Control.Comonad.Trans.Adjoint</a></p>
<p><strong>A Contravariant Comonad Sandwich</strong></p>
<p>As was first shown to me me by Derek Elkins, this construction works even when you C is not the category of Haskell types!</p>
<p>Consider the <a href="http://hackage.haskell.org/packages/archive/contravariant/0.1.2/doc/html/Data-Functor-Contravariant.html">Contravariant</a> functor <code>Op r</code>:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Op a b = Op <span style="color: green;">&#123;</span> getOp :: b -&gt; a <span style="color: green;">&#125;</span> 
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Contravariant <span style="color: green;">&#40;</span>Op a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  contramap f g = Op <span style="color: green;">&#40;</span>getOp g . f<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>We can view <code>Op r</code> as a functor from <code>Hask^op -> Hask</code> or as one from <code>Hask -> Hask^op</code>.</p>
<p>We can define a notion of a contravariant adjunction <code>F -| G : Hask^op -> Hask</code>.</p>
<p><a href="http://hackage.haskell.org/packages/archive/adjunctions/1.0.0/doc/html/Data-Functor-Contravariant-Adjunction.html">Data.Functor.Contravariant.Adjunction</a></p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span>Contravariant f, Corepresentable g<span style="color: green;">&#41;</span> =&gt;
       <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g | f -&gt; g, g -&gt; f <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> :: <span style="color: green;">&#40;</span>b -&gt; f a<span style="color: green;">&#41;</span> -&gt; a -&gt; g b
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> :: <span style="color: green;">&#40;</span>a -&gt; g b<span style="color: green;">&#41;</span> -&gt; b -&gt; f a
&nbsp;</pre>
<p>Where, now, <code>leftAdjunct</code> and <code>rightAdjunct</code> witness the isomorphism from <code>(f a < - b)</code> to </code><code>(a -> g b)</code>, which means once you flip the arrow around both seem to be going the same way. Ultimately any contravariant adjunction on Hask is comprised of two isomorphic functors, each self-adjoint.</p>
<p>This gives rise to one notion of a comonad-to-monad transformer!</p>
<p><a href="http://hackage.haskell.org/packages/archive/adjunctions/1.0.0/doc/html/Control-Monad-Trans-Contravariant-Adjoint.html">Control.Monad.Trans.Contravariant.Adjoint</a></p>
<p>But we can we do better?</p>
<p><strong>An End as the Means</strong></p>
<p>First, some boilerplate.</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# LANGUAGE Rank2Types, FlexibleInstances, FlexibleContexts, MultiParamTypeClasses, UndecidableInstances #-}</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">import</span> Data.Monoid
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a>
<span style="color: #06c; font-weight: bold;">import</span> Control.Applicative
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a>.Store.Class
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a>.Env.Class <span style="color: #06c; font-weight: bold;">as</span> Env
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a>.Traced.Class <span style="color: #06c; font-weight: bold;">as</span> Traced
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a>.Reader.Class
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a>.Writer.Class
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a>.State.Class
<span style="color: #06c; font-weight: bold;">import</span> Data.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>.Bind
&nbsp;</pre>
<p>Our new comonad to monad transformer is given by</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Co w a = Co <span style="color: green;">&#123;</span> runCo :: <span style="color: #06c; font-weight: bold;">forall</span> r. w <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; r <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>What we've done is added a quantifier to prevent the use of the type <em>r</em>, as we did when describing <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.1/doc/html/Control-Monad-Codensity.html"><code>Codensity</code></a> and <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.1/doc/html/Data-Functor-KanExtension.html"><code>Ran</code></a>, categorically we've taken some kind of <a href="http://en.wikipedia.org/wiki/End_(category_theory)">end</a>. This idea came to me after an observation was made by Russell O'Connor that <code>Conts (Store s) a</code> was pretty close to a continuation passing style version of <code>State s</code>.</p>
<p>Now, we can start spitting out instances for this type. </p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Co w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Co w<span style="color: green;">&#41;</span> = Co <span style="color: green;">&#40;</span>w . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>. f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>Co w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = Co <span style="color: green;">&#40;</span>`<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a>` a<span style="color: green;">&#41;</span>
   Co k &gt;&gt;= f = Co <span style="color: green;">&#40;</span>k .<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span>\wa a -&gt; runCo <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> wa<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; Applicative <span style="color: green;">&#40;</span>Co w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   mf &lt; *&gt; ma = mf &gt;&gt;= \f -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f ma
   pure a = Co <span style="color: green;">&#40;</span>`<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a>` a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>In my break-out of category-extras, I've split off the semigroupoid structure of Kleisli-, co-Kleisli-, and static- arrow composition as <code>Bind</code>, <code>Extend</code> and <code>Apply</code> respectively, so we can make use of slightly less structure and get slightly less structure in turn:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Extend w =&gt; Bind <span style="color: green;">&#40;</span>Co w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   Co k &gt;&gt;- f = Co <span style="color: green;">&#40;</span>k .<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <span style="color: green;">&#40;</span>\wa a -&gt; runCo <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> wa<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Extend w =&gt; Apply <span style="color: green;">&#40;</span>Co w<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   mf &lt; .&gt; ma = mf &gt;&gt;- \f -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f ma
&nbsp;</pre>
<p><strong>From comonad-transformers to the mtl</strong></p>
<p>We can look at how this transforms some particular comonads. </p>
<p>The comonadic version of <a href="http://hackage.haskell.org/packages/archive/mtl/2.0.1.0/doc/html/Control-Monad-State-Lazy.html"><code>State</code></a> is <a href="http://hackage.haskell.org/packages/archive/comonad-transformers/1.7/doc/html/Control-Comonad-Trans-Store-Lazy.html"><code>Store</code></a>. Looking at <code>Co (Store s) a</code></p>
<pre class="haskell">&nbsp;
Co <span style="color: green;">&#40;</span>Store s<span style="color: green;">&#41;</span> a ~ <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>s -&gt; a -&gt; r, s<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span>
               ~ <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>s -&gt; a -&gt; r<span style="color: green;">&#41;</span> -&gt; s -&gt; r
               ~ <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; s -&gt; r<span style="color: green;">&#41;</span> -&gt; s -&gt; r
               ~ Codensity <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span>s<span style="color: green;">&#41;</span> a
               ~ State s a
&nbsp;</pre>
<p>This gives rise to a leap of intuition that we'll motivate further below:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> ComonadStore s m =&gt; MonadState s <span style="color: green;">&#40;</span>Co m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   get = Co <span style="color: green;">&#40;</span>\w -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> w <span style="color: green;">&#40;</span>pos w<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
   put s = Co <span style="color: green;">&#40;</span>\w -&gt; peek s w <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Sadly this breaks down a little for <code>Writer</code> and <code>Reader</code> as the <code>mtl</code> unfortunately has historically included a bunch of extra baggage in these classes. In particular, in reader, the notion of <code>local</code> isn't always available, blocking some otherwise perfectly good <code>MonadReader</code> instances, and I've chosen not to repeat this mistake in <code>comonad-transformers</code>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> ComonadEnv e m =&gt; MonadReader e <span style="color: green;">&#40;</span>Co m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   ask = Co <span style="color: green;">&#40;</span>\w -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> w <span style="color: green;">&#40;</span>Env.ask w<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
   local = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> <span style="color: #3c7331;">&quot;local&quot;</span>
&nbsp;</pre>
<p>Ideally, local belongs in a subclass of <code>MonadReader</code>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; MonadReader e m | m -&gt; e <span style="color: #06c; font-weight: bold;">where</span>
   ask :: m a -&gt; e
&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> MonadReader e m =&gt; MonadLocal e m | m -&gt; e <span style="color: #06c; font-weight: bold;">where</span>
   local :: <span style="color: green;">&#40;</span>e -&gt; e<span style="color: green;">&#41;</span> -&gt; m a -&gt; m a
&nbsp;</pre>
<p>Similarly there is a lot of baggage in the <code>MonadWriter</code>. The <code>Monoid</code> constraint isnt necessary for the class itself, just for most instances, and the <code>listen</code> and <code>pass</code> members should be a member of a more restricted subclass as well to admit some missing <code>MonadWriter</code> instances, but we can at least provide the notion of tell that is critical to <code>Writer</code>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Monoid e, ComonadTraced e m<span style="color: green;">&#41;</span> =&gt; MonadWriter e <span style="color: green;">&#40;</span>Co m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   tell m = Co <span style="color: green;">&#40;</span>\w -&gt; Traced.trace m w <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
   listen = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> <span style="color: #3c7331;">&quot;listen&quot;</span>
   pass = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> <span style="color: #3c7331;">&quot;pass&quot;</span>
&nbsp;</pre>
<p>But given the split out</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; MonadWriter e m | m -&gt; e <span style="color: #06c; font-weight: bold;">where</span>
    tell :: e -&gt; m <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadWriter e m =&gt; MonadListen e m | m -&gt; e
    listen :: m a -&gt; m <span style="color: green;">&#40;</span>a, w<span style="color: green;">&#41;</span>
    pass :: m <span style="color: green;">&#40;</span>a, w -&gt; w<span style="color: green;">&#41;</span> -&gt; m a
&nbsp;</pre>
<p>We could provide this functionality more robustly. (There is a similar subset of <code>Comonad</code>s that can provide listen and pass analogues.)</p>
<p>While I am now the maintainer of the mtl, I can't really justify making the above corrections to the class hierarchy at this time. They would theoretically break a lot of code. I would be curious to see how much code would break in practice though.</p>
<p><strong>Combinators Please!</strong></p>
<p>There is a recurring pattern in the above code, so we can also improve this construction by providing some automatic lifting combinators that take certain cokleisli arrows and give us monadic values</p>
<pre class="haskell">&nbsp;
lift0 :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> a. w a -&gt; s<span style="color: green;">&#41;</span> -&gt; Co w s
lift0 f = Co <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> &lt; *&gt; f<span style="color: green;">&#41;</span>
&nbsp;
lift1 :: <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> a. w a -&gt; a<span style="color: green;">&#41;</span> -&gt; Co w <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
lift1 f = Co <span style="color: green;">&#40;</span>`f` <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>along with their inverses</p>
<pre class="haskell">&nbsp;
lower0 :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w =&gt; Co w s -&gt; w a -&gt; s
lower0 <span style="color: green;">&#40;</span>Co f<span style="color: green;">&#41;</span> w = f <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> &lt; $ w<span style="color: green;">&#41;</span>
&nbsp;
lower1 :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> w =&gt; Co w <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; w a -&gt; a
lower1 <span style="color: green;">&#40;</span>Co f<span style="color: green;">&#41;</span> w = f <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> w<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>(The proofs that these are inverses are quite hairy, and lean heavily on parametricity.)</p>
<p>Then in the above, the code simplifies to:</p>
<pre class="haskell">&nbsp;
get = lift0 pos
put s = lift1 <span style="color: green;">&#40;</span>peek s<span style="color: green;">&#41;</span>
ask = lift0 Env.ask
tell s = lift1 <span style="color: green;">&#40;</span>tell s<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p><strong>Co-Density?</strong></p>
<p>Co and Codensity are closely related.</p>
<p>Given any Comonad W, it is given rise to by the composition FG for some adjunction <code>F -| G : Hask -> C</code>.</p>
<p>Considering only the case where <code>C = Hask</code> for now, we can find that</p>
<pre class="haskell">&nbsp;
Co w a ~ <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>g <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span>.
&nbsp;</pre>
<p>Since <code>f -| g</code>, we know that <code>g</code> is <code>Representable</code> by <code>f ()</code>, as witnessed by:</p>
<pre class="haskell">&nbsp;
tabulateAdjunction :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f u =&gt; <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; b<span style="color: green;">&#41;</span> -&gt; u b
tabulateAdjunction f = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
&nbsp;
indexAdjunction :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f u =&gt; u b -&gt; f a -&gt; b
indexAdjunction = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a>
&nbsp;</pre>
<p>therefore</p>
<pre class="haskell">&nbsp;
Co w a ~ f <span style="color: green;">&#40;</span>g <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; r ~ f <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; a -&gt; r<span style="color: green;">&#41;</span> -&gt; r
&nbsp;</pre>
<p>Since <em>f</em> is a left adjoint functor, <code>f a ~ (a, f ())</code> by Sjoerd Visscher's elegant little <code>split</code> combinator:</p>
<pre class="haskell">&nbsp;
split :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f u =&gt; f a -&gt; <span style="color: green;">&#40;</span>a, f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
split = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> . <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>which has the simple inverse</p>
<pre class="haskell">&nbsp;
unsplit :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g =&gt; a -&gt; f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; f a
unsplit a = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>so we can apply that to our argument:</p>
<pre class="haskell">&nbsp;
Co w a ~ <span style="color: #06c; font-weight: bold;">forall</span> r. f <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; a -&gt; r<span style="color: green;">&#41;</span> -&gt; r ~
         <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; a -&gt; r, f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; r
&nbsp;</pre>
<p>and curry to obtain</p>
<pre class="haskell">&nbsp;
Co w a ~ <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; a -&gt; r<span style="color: green;">&#41;</span> -&gt; f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; r
&nbsp;</pre>
<p>and swap the arguments</p>
<pre class="haskell">&nbsp;
Co w a ~ <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; f <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; r
&nbsp;</pre>
<p>then we can tabulate the two subtypes of the form (f () -> r)</p>
<pre class="haskell">&nbsp;
Co w a ~ <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; g r<span style="color: green;">&#41;</span> -&gt; g r
&nbsp;</pre>
<p>and so we find that</p>
<pre class="haskell">&nbsp;
Co w a ~ Codensity g a
&nbsp;</pre>
<p>Finally, </p>
<pre class="haskell">&nbsp;
Codensity g a ~ <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> g g a
&nbsp;</pre>
<p>but we showed back in my second article on Kan extensions that given f -| g that</p>
<pre class="haskell">&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> g g a ~ g <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>So <code>Co w ~ Co (f . g) ~ (g . f)</code>, the monad given rise to by composing our adjunction the other way!</p>
<p><strong>Comonads from Monads?</strong></p>
<p>Now, given all this you might ask </p>
<blockquote><p>Is there is a similar construction that lets you build a comonad out of a monad?</p></blockquote>
<p>Sadly, it seems the answer <strong>in Haskell</strong> is no.</p>
<p>Any adjunction from <code>Hask -> Hask^op</code> would require two functions</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span>Contravariant f, Contravariant g<span style="color: green;">&#41;</span> =&gt; DualContravariantAdjunction f g <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> :: <span style="color: green;">&#40;</span>f a -&gt; b<span style="color: green;">&#41;</span> -&gt; g b -&gt; a
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> :: <span style="color: green;">&#40;</span>g b -&gt; a<span style="color: green;">&#41;</span> -&gt; f a -&gt; b
&nbsp;</pre>
<p>where <strong>both functors are contravariant</strong>. </p>
<p>Surmounting the intuitionistic impossibility of this, then given any such adjunction, there would be a nice coend we could take, letting us sandwich any <code>Monad</code> in the middle as we did above.</p>
<p>There does exist one such very boring Contravariant Functor.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Absurd a = Absurd <span style="color: green;">&#40;</span>Absurd a<span style="color: green;">&#41;</span>
&nbsp;
absurdity :: Absurd a -&gt; b
absurdity <span style="color: green;">&#40;</span>Absurd a<span style="color: green;">&#41;</span> = absurdity a
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Contravariant Absurd <span style="color: #06c; font-weight: bold;">where</span>
   contramap f <span style="color: green;">&#40;</span>Absurd <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span> = Absurd <span style="color: green;">&#40;</span>contramap f <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> DualContravariantAdjunction Absurd Absurd <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> _ = absurdity
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> _ = absurdity
&nbsp;</pre>
<p>We can safely sandwich IO within this adjunction from <code>Hask -> Hask^op</code> to obtain a comonad.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Silly m a = Silly <span style="color: green;">&#123;</span> runSilly :: Absurd <span style="color: green;">&#40;</span>m <span style="color: green;">&#40;</span>Absurd a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; Extend <span style="color: green;">&#40;</span>Silly m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> f <span style="color: green;">&#40;</span>Silly m<span style="color: green;">&#41;</span> = absurdity m
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> <span style="color: green;">&#40;</span>Silly m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> <span style="color: green;">&#40;</span>Silly m<span style="color: green;">&#41;</span> = absurdity m
&nbsp;</pre>
<p>But for any more interesting such type that actually lets us get at its contents, we would be able to derive a circuitous path to <code>unsafePerformIO</code>!</p>
<p>Since <code>unsafePerformIO</code> should not be constructible without knowing <code>IO</code> specifics, no <strong>useful</strong> <code>DualContravariantAdjunction</code>s should exist.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/monads-from-comonads/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Free Monads for Less (Part 3 of 3): Yielding IO</title>
		<link>http://comonad.com/reader/2011/free-monads-for-less-3/</link>
		<comments>http://comonad.com/reader/2011/free-monads-for-less-3/#comments</comments>
		<pubDate>Fri, 24 Jun 2011 06:41:06 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Monads]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=251</guid>
		<description><![CDATA[<a href="http://comonad.com/reader/2011/free-monads-for-less-2/">Last time</a>, I said that I was going to put our cheap new free monad to work, so let's give it a shot. ]]></description>
			<content:encoded><![CDATA[<p><a href="http://comonad.com/reader/2011/free-monads-for-less-2/">Last time</a>, I said that I was going to put our cheap new free monad to work, so let's give it a shot. </p>
<p><span id="more-251"></span></p>
<p><strong>Yield for Less</strong></p>
<p>Last month at <a href="http://www.pps.jussieu.fr/~saurin/tpdc2011/">TPDC 2011</a>, Roshan James and Amr Sabry presented <a href="http://parametricity.net/dropbox/yield.subc.pdf">Yield: Mainstream Delimited Continuations</a>.</p>
<p>Without calling it such they worked with the free monad of the indexed store comonad. Ignoring the comonad, and just looking at the functor we can see that</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Store i o r = Store <span style="color: green;">&#40;</span>i -&gt; r<span style="color: green;">&#41;</span> o
    <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>admits the operation</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> y =&gt; Yieldable y i o | y -&gt; i o <span style="color: #06c; font-weight: bold;">where</span>
   yield :: o -&gt; y i
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Yieldable <span style="color: green;">&#40;</span>Store i o<span style="color: green;">&#41;</span> i o <span style="color: #06c; font-weight: bold;">where</span>
   yield = Store <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
&nbsp;</pre>
<p>The free monad of <code>Store i o</code> is a nice model for asymmetric coroutines.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Yield i o = Free <span style="color: green;">&#40;</span>Store i o<span style="color: green;">&#41;</span>
&nbsp;
liftFree :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; f a -&gt; Free f a
liftFree = Free . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> Pure
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Yieldable y i o =&gt; Yieldable <span style="color: green;">&#40;</span>Free y<span style="color: green;">&#41;</span> i o <span style="color: #06c; font-weight: bold;">where</span>
   yield = liftFree . yield
&nbsp;</pre>
<p>With its <code>Monad</code>, you can write computations like:</p>
<pre class="haskell">&nbsp;
foo :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> o =&gt; Yield <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> o <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
foo = <span style="color: #06c; font-weight: bold;">do</span>
   yield <span style="color: red;">1</span>
   yield <span style="color: red;">2</span>
   yield <span style="color: red;">3</span>
&nbsp;</pre>
<p>or to streamline one of James and Sabry's examples</p>
<pre class="haskell">&nbsp;
walk :: Traversable f =&gt; f o -&gt; Yield i o <span style="color: green;">&#40;</span>f i<span style="color: green;">&#41;</span>
walk = traverse yield
&nbsp;</pre>
<p>is an asymmetric coroutine that yields each of the elements in a traversable container in turn, replacing them with the responses from whatever is driving the coroutine.</p>
<p>James and Sabry called this the naive frame grabbing implementation. It is inefficient for the same reasons that we discussed before about retraversing the common trunk in free monads in general. Note that the unchanging trunk here isn't the data structure that we're traversing, but instead the chain of <code>Store i o</code> actions we took to get to the current instruction.</p>
<p>James and Sabry then proceeded to optimize it by hitting it with <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/Control-Monad-Codensity.html">Codensity</a>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Iterator i o = Codensity <span style="color: green;">&#40;</span>Yield i o<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> y, Yieldable y i o<span style="color: green;">&#41;</span> =&gt; Yieldable <span style="color: green;">&#40;</span>Codensity y<span style="color: green;">&#41;</span> i o <span style="color: #06c; font-weight: bold;">where</span>
   yield = liftCodensity . yield
&nbsp;</pre>
<p>But we've now seen that we can get away with something smaller and get the same benefits.</p>
<pre class="haskell">&nbsp;
liftF :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; f a -&gt; F f a
liftF f = F <span style="color: green;">&#40;</span>\kp kf -&gt; kf <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> kp f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Yieldable y i o =&gt; Yieldable <span style="color: green;">&#40;</span>F y<span style="color: green;">&#41;</span> i o <span style="color: #06c; font-weight: bold;">where</span>
   yield = liftF . yield
&nbsp;</pre>
<p>Flattened, and with the store untupled the new optimized representation looks like:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Iterator i o a = Iterator
  <span style="color: green;">&#123;</span> runIterator ::
    <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>o -&gt; <span style="color: green;">&#40;</span>i -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span>
  <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>and provides the same performance improvements for asymmetric coroutines as the <code>Codensity</code> version, used by James and Sabry, which would flatten to the much larger and less satisfying:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> RSIterator i o a = RSIterator
    <span style="color: green;">&#123;</span> runRSIterator :: <span style="color: #06c; font-weight: bold;">forall</span> r.
          <span style="color: green;">&#40;</span>a -&gt; <span style="color: green;">&#40;</span>o -&gt; <span style="color: green;">&#40;</span>i -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span>
             -&gt; <span style="color: green;">&#40;</span>o -&gt; <span style="color: green;">&#40;</span>i -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; r
    <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>They proceed to give an encoding of delimited continuations into this type and vice versa, but the rest of their material is of no further use to us here.</p>
<p>As an aside the performance benefits of encoding Oleg's <a href="http://okmij.org/ftp/Streams.html">iteratees</a> in <a href="http://hackage.haskell.org/packages/archive/iteratee/0.8.5.0/doc/html/Data-Iteratee-Base.html">continuation passing style</a> arise for much the same reason. The resuting encoding is a right Kan extension!</p>
<p><strong>Who Needs the RealWorld?</strong></p>
<p>As <a href="http://twitter.com/#!/runarorama/status/83570792704638976">Runar recently tweeted</a>, we have put this to good use here at <a href="https://www.capitaliq.com/home/what-we-offer/how-you-can-get-it/clarifi.aspx">ClariFI</a>. (<strong>Yes</strong>, we are hiring! If the contents of my blog make sense to you then <a href="mailto:ekmett@gmail.com">email me</a> and let's talk.)</p>
<p>At ClariFI have a strongly typed functional language that bears a strong resemblance to Haskell with <a href="http://www.haskell.org/haskellwiki/Rank-N_types">rank-n types</a> and a number of other interesting type system features that are particularly suited to our problem domain.</p>
<p>However, as with Haskell, we needed a story for how to deal with <code>IO</code>. </p>
<p>Now, <a href="http://www.haskell.org/ghc/">GHC</a> models <a href="http://www.haskell.org/ghc/docs/6.2/html/libraries/base/GHC.IOBase.html">IO</a> with the type</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a> a =
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a> <span style="color: green;">&#40;</span>State# RealWorld -&gt; <span style="color: green;">&#40;</span># a, State# RealWorld #<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>where they model <code>IO</code> by working in a strict state monad, passing around a real world that they promise not to mutate or copy. (In practice, the world is passed around as a 0-byte token.</p>
<p>This is somewhat problematic semantically, for a number of reasons.</p>
<p>First, There is always the risk of copying it or plumbing it through backwards, so we carefully hide the <code>State# RealWorld</code> from the end user. So this model really wants some notion of uniqueness or linear typing to render it perfectly safe. Heck, the entire <a href="http://en.wikipedia.org/wiki/Clean_(programming_language)">Clean</a> language arose from just trying to address this concern.</p>
<p>Second, you don't <strong>really</strong> get to pass the real world around!  We have multiple cores working these days. Stuff is happening in the back end, and as much as you might want it to be, your program isn't responsible for everything that happens in the <code>RealWorld</code>!.</p>
<p>Third, if in some sense all bottoms are the same, then <code>forever (putStrLn "Hello World")</code> and <code>undefined</code> are the same in that sense, despite the slew of side-effects that arise from the first one. Now, in Haskell you are allowed to catch some bottoms in the IO monad, and thereby escape from certain doom, but it is still a reasonable objection.</p>
<p>One alternate model for talking about <code>IO</code> is to view it as a free monad of some set of operations. This approach was taken by Wouter Swierstra's Functional Pearl: <a href="http://www.cs.nott.ac.uk/~wss/Publications/DataTypesALaCarte.pdf">Data Types a la Carte</a>.</p>
<p>You can then supply some sort of external interpreter that pumps that tree structure, performing the individual actions.</p>
<p>This is unsatisfying because of two things:</p>
<p>First, the performance is abysmal using the common ADT encoding of a free monad. Janis Voigtländer of course showed, that this can be rectified by using the <code>Codensity</code> monad.</p>
<p>Second, the set of <code>FFI</code> operations is closed.</p>
<p>What we've done instead is to define our primitive <code>IO</code> actions externally as some <code>FFI</code> type:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> FFI o i <span style="color: #5d478b; font-style: italic;">-- external, side-effecting computation taking o, returning i</span>
&nbsp;</pre>
<p>In practice, these are obtained by reflection by our <code>foreign import</code> statements since we run in the JVM.</p>
<p>Then we looked at the free monad of</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> OI a = <span style="color: #06c; font-weight: bold;">forall</span> o i. OI <span style="color: green;">&#40;</span>FFI o i<span style="color: green;">&#41;</span> o <span style="color: green;">&#40;</span>i -&gt; a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">deriving</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>
&nbsp;</pre>
<p>where <code>OI</code> is the indexed store comonad used as the building block above, yielding arguments to <code>FFI</code> of type <em>o</em>, and representing a computation that would resume with a value of type <em>i</em> to obtain a result of type <em>a</em>.<code></p>
<p>In some sense this yields a more useful notion than Richard Kieburtz's novel, but largely unimplementable, </code><code>OI</code> comonad from <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.45.4741&rep=rep1&type=ps">Codata and Comonads in Haskell</a>.</p>
<p>Flattening <code>Free OI</code> would yield the naive</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- data FIO a where</span>
<span style="color: #5d478b; font-style: italic;">--    Return :: a -&gt; FIO a</span>
<span style="color: #5d478b; font-style: italic;">--    FIO :: FFI o i -&gt; o -&gt; (i -&gt; FIO a) -&gt; FIO a</span>
&nbsp;</pre>
<p>which would be interpreted by the runtime system.</p>
<p>But once we've converted to our Church-encoded Free monad and flattened we obtain:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a> a = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a>
    <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt;
                 <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> i o. FFI o i -&gt; o -&gt; <span style="color: green;">&#40;</span>i -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt;
                 r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>with the <code>Functor</code> and <code>Monad</code> instances defined above.</p>
<p>This then gives us a number of choices on how we implement the runtime system:</p>
<p>We can use the machinery described earlier to convert from <code>IO a</code> to <code>Free OI a</code> or <code>FIO a</code>, and then have the runtime system pattern match on that structure on our main method, taking the <code>FFI</code> actions and their arguments and passing the results in to the language, or we can invert control, and implement things more directly by just defining </p>
<pre class="haskell">&nbsp;
FFI = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>while letting the <code>FFI</code>'d methods have side-effects, and then defining</p>
<pre class="haskell">&nbsp;
unsafePerformIO :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a> a -&gt; a
unsafePerformIO <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:IO"><span style="background-color: #efefbf; font-weight: bold;">IO</span></a> m<span style="color: green;">&#41;</span> = m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> <span style="color: green;">&#40;</span>\ oi o ir -&gt; ir <span style="color: green;">&#40;</span>oi o<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>But regardless of how <code>FFI</code> is implemented,  this model provides a clear structural difference between <code>forever (putStrLn "Hello")</code> and <code>undefined</code> and does not require us to believe the pleasant fiction that we can get our hands on the real world and pass it around.</p>
<p>Our actual <code>IO</code> representation is only slightly more complicated than the one presented here in order to deal with the plumbing of an extra continuation to deal with Java exceptions, but the substance of this approach isn't changed by this addition.</p>
<p>[Edit: incorporated a minor typographical fix into Iterator from Max Bolingbroke]<br />
[Edit: fixed Store to be data, an liftM that should have been an fmap and added the missing Functor constraint that was present in my actual implementation but didn't make it to the web, and a couple of typos in the implementation of RSIterator, all noted by Clumsy.]</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/free-monads-for-less-3/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Free Monads for Less (Part 2 of 3): Yoneda</title>
		<link>http://comonad.com/reader/2011/free-monads-for-less-2/</link>
		<comments>http://comonad.com/reader/2011/free-monads-for-less-2/#comments</comments>
		<pubDate>Fri, 24 Jun 2011 04:49:46 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=243</guid>
		<description><![CDATA[Last time, I started exploring whether or not Codensity was necessary to improve the asymptotic performance of free monads.
This time I'll show that the answer is no; we can get by with something smaller.

The Yoneda Lemma
Another form of right Kan extension arises from the Yoneda lemma.
I covered it briefly in my initial article on Kan [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://comonad.com/reader/2011/free-monads-for-less/">Last time</a>, I started exploring whether or not <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/Control-Monad-Codensity.html">Codensity</a> was necessary to <a href="http://www.iai.uni-bonn.de/~jv/mpc08.pdf">improve the asymptotic performance of free monads</a>.</p>
<p>This time I'll show that the answer is no; we can get by with something smaller.</p>
<p><span id="more-243"></span></p>
<p><b>The Yoneda Lemma</b></p>
<p>Another form of right Kan extension arises from the <a href="http://en.wikipedia.org/wiki/Yoneda_lemma">Yoneda lemma</a>.</p>
<p>I covered it briefly in <a href="http://comonad.com/reader/2008/kan-extensions/">my initial article on Kan extensions</a>, but the inestimable Dan Piponi wrote a <a href="http://blog.sigfpe.com/2006/11/yoneda-lemma.html">much nicer article</a> on how it implies in Haskell that given a <code>Functor</code> instance on <em>f</em>, this type</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Yoneda f a = Yoneda <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; f r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>is isomorphic to <code>f a</code>, witnessed by these natural transformations:</p>
<pre class="haskell">&nbsp;
liftYoneda :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; f a -&gt; Yoneda f a
liftYoneda a = Yoneda <span style="color: green;">&#40;</span>\f -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f a<span style="color: green;">&#41;</span>
&nbsp;
lowerYoneda :: Yoneda f a -&gt; f a
lowerYoneda <span style="color: green;">&#40;</span>Yoneda f<span style="color: green;">&#41;</span> = f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
&nbsp;</pre>
<p>That said, <em>you are not limited to applying <code>Yoneda</code> to types that have <code>Functor</code> instances</em>.</p>
<p>This type and these functions are provided by <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/Data-Functor-Yoneda.html">Data.Functor.Yoneda</a> from the <a href="http://hackage.haskell.org/package/kan-extensions">kan-extensions</a> package.</p>
<p><b>Codensity vs. Yoneda</b></p>
<p>Note, <code>Yoneda f</code> is in some sense smaller than <code>Codensity f</code>, as <code>Codensity f a</code> is somewhat 'bigger' than <code>f a</code>, despite providing an embedding, while <code>Yoneda f a</code> is isomorphic.</p>
<p>For example, <code>Codensity ((->) s) a</code> is isomorphic to <code>State s a</code>, not to <code>s -&gt; a</code> as shown by: </p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadState s <span style="color: green;">&#40;</span>Codensity <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span> s<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   get = Codensity <span style="color: green;">&#40;</span>\k s -&gt; k s s<span style="color: green;">&#41;</span>
   put s = Codensity <span style="color: green;">&#40;</span>\k _ -&gt; k <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> s<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Now, <code>Codensity</code> is a particular form of right Kan extension, which always yields a <code>Monad</code>, <b>without needing anything from <em>f</em></b>.</p>
<p>Here we aren't so fortunate, but we do have the fact that <code>Yoneda f</code> is always a <code>Functor</code>, regardless of what <em>f</em> is, as shown by:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Yoneda f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Yoneda m<span style="color: green;">&#41;</span> = Yoneda <span style="color: green;">&#40;</span>\k -&gt; m <span style="color: green;">&#40;</span>k . f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>which was obtained just by cutting and pasting the appropriate definition from <code>Codensity</code> or <code>ContT</code>, and comes about because <code>Yoneda</code> is a right Kan extension, like all of those. </p>
<p>To get a <code>Monad</code> instance for <code>Yoneda f</code> we need to lean on <em>f</em> somehow.</p>
<p>One way is to just borrow a <code>Monad</code> instance from <em>f</em>, since <code>f a</code> is isomorphic to <code>Yoneda f a</code>, if we have a <code>Functor</code> for <em>f</em>, and if we have a <code>Monad</code>, we can definitely have a <code>Functor</code>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>Yoneda m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = Yoneda <span style="color: green;">&#40;</span>\f -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  Yoneda m &gt;&gt;= k = Yoneda <span style="color: green;">&#40;</span>\f -&gt; m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> &gt;&gt;= \a -&gt; runYoneda <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> f<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p><strong>Map Fusion and Reassociating Binds</strong></p>
<p>Unlike <code>Codensity</code> the monad instance above isn't very satisfying, because it uses the <code>>>=</code> of the underlying monad, and as a result the <code>>>=</code>s will wind up in the same order they started.</p>
<p>On the other hand, the <code>Functor</code> instance for <code>Yoneda f</code> is still pretty nice because the <code>(a -&gt; r)</code> part of the type acts as an accumulating parameter fusing together uses of <code>fmap</code>.</p>
<p>This is apparent if you expand <code>lowerYoneda . fmap f . fmap g . liftYoneda </code>, whereupon you can see we only call <code>fmap</code> on the underlying <code>Functor</code> once.</p>
<p>Intuitively, you can view <code>Yoneda</code> as a type level construction that ensures that you get <code>fmap</code> fusion, while <code>Codensity</code> is a type level construction that ensures that you right associate binds. It is important to note that <code>Codensity</code> also effectively accumulates <code>fmap</code>s, as it uses the same definition for <code>fmap</code> as <code>Yoneda</code>!</p>
<p>With this in mind, it doesn't usually make much sense to use <code>Codensity (Codensity m)</code> or <code>Yoneda (Yoneda m)</code> because the purpose being served is redundant.</p>
<p>Less obviously, <code>Codensity (Yoneda m)</code> is also redundant, because as noted above, <code>Codensity</code> also does <code>fmap</code> accumulation.</p>
<p><strong>Other Yoneda-transformed Monads</strong></p>
<p>Now, I said one way to define a <code>Monad</code> for <code>Yoneda f</code> was to borrow an underlying <code>Monad</code> instance for <em>f</em>, but this isn't the only way.</p>
<p>Consider <code>Yoneda Endo</code>. Recall that <code>Endo</code> from <a href="http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Monoid.html">Data.Monoid</a> is given by</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Endo a = Endo <span style="color: green;">&#123;</span> appEndo :: a -&gt; a <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>Clearly <code>Endo</code> is not a <code>Monad</code>, it can't even be a <code>Functor</code>, because <em>a</em> occurs in both positive and negative position.</p>
<p>Nevertheless <code>Yoneda Endo</code> <strong>can</strong> be made into a monad -- the continuation passing style version of the <code>Maybe</code> monad!</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> YMaybe a = YMaybe <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; r -&gt; r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>I leave the rather straightforward derivation of this <code>Monad</code> for the reader. A version of it is present in <a href="http://comonad.com/haskell/monad-ran/dist/doc/html/monad-ran/Control-Monad-Ran.html">monad-ran</a>.</p>
<p>This lack of care for capital-F <code>Functor</code>iality also holds for <code>Codensity</code>, <code>Codensity Endo</code> can be used as a two-continuation list monad. It is isomorphic to the non-transformer version of <a href="http://okmij.org/ftp/papers/LogicT.pdf">Oleg et al.'s LogicT</a>, which is available on hackage as <a href="http://hackage.haskell.org/packages/archive/logict/0.4.2/doc/html/Control-Monad-Logic.html">logict</a> from my coworker, Dan Doel.</p>
<p>The <code>Functor</code>, <code>Applicative</code>, <code>Monad</code>, <code>MonadPlus</code> and many other instances for <code>LogicT</code> can be rederived in their full glory from <code>Codensity (GEndo m)</code> automatically, where</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> GEndo m r = GEndo <span style="color: green;">&#40;</span>m r -&gt; m r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>without any need for conscious thought about how the continuations are plumbed through in the <code>Monad</code>.</p>
<p><strong>Bananas in Space</strong></p>
<p>One last digression,</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Rec f r = <span style="color: green;">&#40;</span>f r -&gt; r<span style="color: green;">&#41;</span> -&gt; r
&nbsp;</pre>
<p>came up once previously on this blog in <a href="http://comonad.com/reader/2008/rotten-bananas/">Rotten Bananas</a>. In that post, I talked about how Fegaras and Sheard used a free monad (somewhat obliquely) in "<a href="http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.36.2763">Revisiting catamorphisms over datatypes with embedded functions</a>" to extend catamorphisms to deal with strong HOAS, and then talked further about how Stephanie Weirich and Geoffrey Washburn <a href="http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.80.2219">used Rec</a> to replace the free monad used by Fegaras and Sheard. That said, they did so in a more restricted context, where any mapping was done by giving us both an embedding and a projection pair.</p>
<p><strong>Going to Church</strong></p>
<p>We can't just use <code>Rec f a</code> instead of <code>Free f a</code> here, because <code>Free f a</code> is a functor, while <code>Rec f a</code> is emphatically not. </p>
<p>However, if we apply <code>Yoneda</code> to <code>Rec f</code>, we obtain a Church-encoded continuation-passing-style version of <code>Free</code>!</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> F f a = F <span style="color: green;">&#123;</span> runF :: <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f r -&gt; r<span style="color: green;">&#41;</span> -&gt; r <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>Since this is of the form of <code>Yoneda (Rec f)</code>, it is clearly a <code>Functor</code>:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>F f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>F g<span style="color: green;">&#41;</span> = F <span style="color: green;">&#40;</span>\kp -&gt; g <span style="color: green;">&#40;</span>kp . f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>And nicely, <strong>without knowing anything about <em>f</em></strong>, we also get a <code>Monad</code>!</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>F f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = F <span style="color: green;">&#40;</span>\kp _ -&gt; kp a<span style="color: green;">&#41;</span>
   F m &gt;&gt;= f = F <span style="color: green;">&#40;</span>\kp kf -&gt; m <span style="color: green;">&#40;</span>\a -&gt; runF <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> kp kf<span style="color: green;">&#41;</span> kf<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>But when we <code>>>=</code> all we do is change the continuation for <code>(a -&gt; r)</code>, leaving the <em>f</em>-algebra, <code>(f r -&gt; r)</code>, untouched.</p>
<p>Now, <code>F</code> is a monad transformer:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadTrans F <span style="color: #06c; font-weight: bold;">where</span>
   lift f = F <span style="color: green;">&#40;</span>\kp kf -&gt; kf <span style="color: green;">&#40;</span>liftM kp f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>which is unsurprisingly, effectively performing the same operation as lifting did in <code>Free</code>.</p>
<p>Heretofore, we've ignored everything about <em>f</em> entirely. </p>
<p>This has pushed the need for the <code>Functor</code> on <em>f</em> into the wrapping operation:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; MonadFree f <span style="color: green;">&#40;</span>F f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   wrap f = F <span style="color: green;">&#40;</span>\kp kf -&gt; kf <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>\ <span style="color: green;">&#40;</span>F m<span style="color: green;">&#41;</span> -&gt; m kp kf<span style="color: green;">&#41;</span> f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Now, we can clearly transform from our representation to any other free monad representation:</p>
<pre class="haskell">&nbsp;
fromF :: MonadFree f m =&gt; F f a -&gt; m a
fromF <span style="color: green;">&#40;</span>F m<span style="color: green;">&#41;</span> = m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> wrap
&nbsp;</pre>
<p>or to it from our original canonical ADT-based free monad representation:</p>
<pre class="haskell">&nbsp;
toF :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; Free f a -&gt; F f a
toF xs = F <span style="color: green;">&#40;</span>\kp kf -&gt; go kp kf xs<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  go kp _  <span style="color: green;">&#40;</span>Pure a<span style="color: green;">&#41;</span> = kp a
  go kp kf <span style="color: green;">&#40;</span>Free fma<span style="color: green;">&#41;</span> = kf <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>go kp kf<span style="color: green;">&#41;</span> fma<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>So, <code>F f a</code> is isomorphic to <code>Free f a</code>.</p>
<p>So, looking at <code>Codensity (F f) a</code> as <code>Codensity (Yoneda (Rec f))</code>, it just seems silly. </p>
<p>As we mentioned before, we should be able to go from <code>Codensity (Yoneda (Rec f)) a</code> to <code>Codensity (Rec f) a</code>, since <code>Yoneda</code> was just fusing uses of <code>fmap</code>, while <code>Codensity</code> was fusing <code>fmap</code> while right-associating <code>(>>=)</code>'s.</p>
<p><strong>Swallowing the Bigger Fish</strong></p>
<p>So, the obvious choice is to try to optimize to <code>Codensity (Rec f) a</code>. If you go through the motions of encoding that you get:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> CF f a = CF <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; <span style="color: green;">&#40;</span>f r -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f r -&gt; r<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>which is in some sense larger than <code>F f a</code>, because the first continuation gets both an <em>a</em> and an <em>f</em>-algebra <code>(f r -&gt; r)</code>.</p>
<p>But tellingly, once you write the code, the first continuation <strong>never uses the extra <em>f</em>-algebra you supplied it!</strong></p>
<p>So <code>Codensity (Yoneda (Rec f)) a</code> gives us nothing of interest that we don't already have in <code>Yoneda (Rec f) a</code>.</p>
<p>Consequently, in this special case rather than letting <code>Codensity (Yoneda x) a</code> swallow the <code>Yoneda</code> to get <code>Codensity x a</code> we can actually let the <code>Yoneda</code> swallow the surrounding <code>Codensity</code> obtaining <code>Yoneda (Rec f) a</code>, the representation we started with.</p>
<p><strong>Scott Free</strong></p>
<p>Finally, you might ask if a Church encoding is as simple as we could go. After all a Scott encoding</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> ScottFree f a = ScottFree
    <span style="color: green;">&#123;</span> runScottFree :: <span style="color: #06c; font-weight: bold;">forall</span> r.
       <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>ScottFree f a<span style="color: green;">&#41;</span> -&gt; r<span style="color: green;">&#41;</span> -&gt; r
    <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>would admit easier pattern matching, and a nice pun, and seems somewhat conceptually simpler, while remaining isomorphic.</p>
<p>But the <code>Monad</code> instance:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>ScottFree f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = ScottFree <span style="color: green;">&#40;</span>\kp _ -&gt; kp a<span style="color: green;">&#41;</span>
   ScottFree m &gt;&gt;= f = ScottFree
       <span style="color: green;">&#40;</span>\kb kf -&gt; m <span style="color: green;">&#40;</span>\a -&gt; runScottFree <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> kb kf<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>kf . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>&gt;&gt;= f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>needs to rely on the underlying bind, and you can show that it won't do the right thing with regards to reassociating.</p>
<p>So, alas, we cannot get away with <code>ScottFree</code>.</p>
<p><strong>Nobody Sells for Less</strong></p>
<p>So, now we can rebuild Voigtländer's <code>improve</code> using our Church-encoded / Yoneda-based free monad <code>F</code>, which is precisely isomorphic to <code>Free</code>, by using</p>
<pre class="haskell">&nbsp;
lowerF :: F f a -&gt; Free f a
lowerF <span style="color: green;">&#40;</span>F f<span style="color: green;">&#41;</span> = f Pure Free
&nbsp;</pre>
<p>to obtain</p>
<pre class="haskell">&nbsp;
improve :: <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> a. MonadFree f m =&gt; m a<span style="color: green;">&#41;</span> -&gt; Free f a
improve m = lowerF m
&nbsp;</pre>
<p>And since our Church-encoded free monad is isomorphic to the simple ADT encoding, our new solution is as small as it can get.</p>
<p>Next time, we'll see this construction in action!</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/free-monads-for-less-2/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Free Monads for Less (Part 1 of 3): Codensity</title>
		<link>http://comonad.com/reader/2011/free-monads-for-less/</link>
		<comments>http://comonad.com/reader/2011/free-monads-for-less/#comments</comments>
		<pubDate>Fri, 24 Jun 2011 03:59:58 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[free monads]]></category>
		<category><![CDATA[io]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=218</guid>
		<description><![CDATA[A couple of years back <a href="http://www.iai.uni-bonn.de/~jv/">Janis Voigtländer</a> wrote <a href="http://www.iai.uni-bonn.de/~jv/mpc08.pdf">a nice paper</a> on how one can use the codensity monad to improve the asymptotic complexity of algorithms using the free monads. This has been shown to be a sufficient tool for this task, but is it necessary?]]></description>
			<content:encoded><![CDATA[<p>A couple of years back <a href="http://www.iai.uni-bonn.de/~jv/">Janis Voigtländer</a> wrote <a href="http://www.iai.uni-bonn.de/~jv/mpc08.pdf">a nice paper</a> on how one can use the codensity monad to improve the asymptotic complexity of algorithms using the free monads. He didn't use the name <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/Control-Monad-Codensity.html">Codensity</a> in the paper, but this is essentially the meaning of his type <code>C</code>. </p>
<p>I just returned from <a href="http://www.cas.mcmaster.ca/~anand/DSL2011.html">running a workshop on domain-specific languages at McMaster University</a> with the more than able assistance of <a href="http://llama.freegeek.org/~wren/thornton_cv.pdf">Wren Ng Thornton</a>. Among the many topics covered, I spent a lot of time talking about how to use free monads to build up term languages for various DSLs with simple evaluators, and then made them efficient by using <code>Codensity</code>.</p>
<p>This has been shown to be a sufficient tool for this task, but is it necessary?</p>
<p><span id="more-218"></span></p>
<p>First, some context:</p>
<p><strong>Monads for Free</strong></p>
<p>Given that <em>f</em> is a <code>Functor</code>, we get that </p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Free f a = Pure a | Free <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>Free f a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>is a <code>Monad</code> for free:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Free f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Pure a<span style="color: green;">&#41;</span> = Pure <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Free <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span> = Free <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>Free f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> = Pure
   Pure a &gt;&gt;= f = f a <span style="color: #5d478b; font-style: italic;">-- the first monad law!</span>
   Free <span style="color: #06c; font-weight: bold;">as</span> &gt;&gt;= f = Free <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>&gt;&gt;= f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>The definition is also free in a particular categorical sense, that if <em>f</em> is a monad, then, and you have a forgetful functor that forgets that it is a monad and just yields the functor, then the the free construction above is left adjoint to it.</p>
<p>This type and much of the code below is actually provided by <a href="http://hackage.haskell.org/packages/archive/comonad-transformers/1.7/doc/html/Control-Monad-Trans-Free.html">Control.Monad.Trans.Free</a> in the <a href="http://hackage.haskell.org/package/comonad-transformers">comonad-transformers</a> package on hackage. </p>
<p>For a while, Free lived in a separate, now defunct, package named <code>free</code> with its dual <a href="http://hackage.haskell.org/packages/archive/comonad-transformers/1.7/doc/html/Control-Comonad-Trans-Cofree.html">Cofree</a>, but it was merged into comonad-transformers due to complications involving <a href="http://hackage.haskell.org/package/comonads-fd">comonads-fd</a>, the comonadic equivalent of the mtl.  Arguably, a better home would be transformers, to keep symmetry.</p>
<p><strong>Free is a Monad Transformer</strong></p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadTrans Free <span style="color: #06c; font-weight: bold;">where</span>
    lift = Free . liftM Pure
&nbsp;</pre>
<p>and there exists a <a href="http://en.wikipedia.org/wiki/Retract_(category_theory)">retraction</a> for lift</p>
<pre class="haskell">&nbsp;
retract :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> f =&gt; Free f a -&gt; f a
retract <span style="color: green;">&#40;</span>Pure a<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a
retract <span style="color: green;">&#40;</span>Free <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span> = <span style="color: #06c; font-weight: bold;">as</span> &gt;&gt;= retract
&nbsp;</pre>
<p>such that <code>retract . lift = id</code>. I've <a href="http://stackoverflow.com/questions/6221531/how-to-convert-a-free-monad-into-a-functor/6231795#6231795">spoken about this on Stack Overflow</a>, including the rather trivial proof, previously.</p>
<p>This lets us work in <code>Free m a</code>, then flatten back down to a single layer of <em>m</em>. </p>
<p>This digression will be useful in a subsequent post.</p>
<p><strong>MonadFree</strong></p>
<p>What Janis encapsulated in his paper is the notion that we can abstract out the extra power granted by a free monad to add layers of <em>f</em> to some monad <em>m</em>, and then use a better representation to improve the asymptotic performance of the monad. </p>
<p>The names below have been changed slightly from his presentation.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> MonadFree f m | m -&gt; f <span style="color: #06c; font-weight: bold;">where</span>
    wrap :: f <span style="color: green;">&#40;</span>m a<span style="color: green;">&#41;</span> -&gt; m a
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadFree f <span style="color: green;">&#40;</span>Free f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    wrap = Free
&nbsp;</pre>
<p>instances can easily be supplied to lift <code>MonadFree</code> over the common monad transformers. For instance:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, MonadFree f m<span style="color: green;">&#41;</span> =&gt; MonadFree f <span style="color: green;">&#40;</span>ReaderT e m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    wrap fs = ReaderT $ \e -&gt; wrap $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>`runReaderT` e<span style="color: green;">&#41;</span> fs
&nbsp;</pre>
<p>This functionality is provided by <a href="http://hackage.haskell.org/packages/archive/comonads-fd/1.7/doc/html/Control-Monad-Free-Class.html">Control.Monad.Free.Class</a>.</p>
<p>Janis then proceeded to define the aforementioned type <code>C</code>, which is effectively identical to</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Codensity f a = Codensity <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; f r<span style="color: green;">&#41;</span> -&gt; f r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>This type is supplied by <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/Control-Monad-Codensity.html">Control.Monad.Codensity</a> from my <a href="http://hackage.haskell.org/package/kan-extensions">kan-extensions</a> package on hackage.</p>
<p>I have spoken about this type (and another that will arise in a subsequent post) on this blog previously, in a series of posts on Kan Extensions.  [ <a href="http://comonad.com/reader/2008/kan-extensions/">1</a>, <a href="http://comonad.com/reader/2008/kan-extensions-ii/">2</a>, <a href="http://comonad.com/reader/2008/kan-extension-iii/">3</a>]</p>
<p><code>Codensity f</code> is a <code>Monad</code>, <strong>regardless</strong> of what <em>f</em> is!</p>
<p>In fact, you can quite literally cut and paste much of the definitions for <code>return</code>, <code>fmap</code>, and <code>(>>=)</code> from the code for the <code>ContT</code> monad transformer! Compare</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Codensity k<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Codensity m<span style="color: green;">&#41;</span> = Codensity <span style="color: green;">&#40;</span>\k -&gt; m <span style="color: green;">&#40;</span>k . f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>Codensity f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> x = Codensity <span style="color: green;">&#40;</span>\k -&gt; k x<span style="color: green;">&#41;</span>
  m &gt;&gt;= k = Codensity <span style="color: green;">&#40;</span>\c -&gt; runCodensity m <span style="color: green;">&#40;</span>\a -&gt; runCodensity <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> c<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadTrans Codensity <span style="color: #06c; font-weight: bold;">where</span>
   lift m = Codensity <span style="color: green;">&#40;</span>m &gt;&gt;=<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>from <a href="http://hackage.haskell.org/packages/archive/kan-extensions/0.5.0/doc/html/src/Control-Monad-Codensity.html">Control.Monad.Codensity</a> in <a href="http://hackage.haskell.org/package/kan-extensions">kan-extensions</a> with</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>ContT r m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f m = ContT $ \c -&gt; runContT m <span style="color: green;">&#40;</span>c . f<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>ContT r m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> a = ContT <span style="color: green;">&#40;</span>$ a<span style="color: green;">&#41;</span>
    m &gt;&gt;= k  = ContT $ \c -&gt; runContT m <span style="color: green;">&#40;</span>\a -&gt; runContT <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> c<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadTrans <span style="color: green;">&#40;</span>ContT r<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    lift m = ContT <span style="color: green;">&#40;</span>m &gt;&gt;=<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>from the <a href="http://hackage.haskell.org/packages/archive/transformers/0.2.2.0/doc/html/src/Control-Monad-Trans-Cont.html">Control.Monad.Trans.Cont</a> in <a href="http://hackage.haskell.org/package/transformers-0.2.2.0">transformers</a>.</p>
<p><code>Codensity m a</code> is effectively <code>forall r. ContT r m a</code>. This turns out to be just enough of a restriction to rule out the use of <a href="http://hackage.haskell.org/packages/archive/transformers/0.2.2.0/doc/html/Control-Monad-Trans-Cont.html#v:callCC">callCC</a>, while leaving the very powerful fact that when you lower them back down using</p>
<pre class="haskell">&nbsp;
lowerCodensity :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; Codensity m a -&gt; m a
lowerCodensity <span style="color: green;">&#40;</span>Codensity m<span style="color: green;">&#41;</span> = m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a>
&nbsp;</pre>
<p>or</p>
<pre class="haskell">&nbsp;
runContT :: ContT r m a -&gt; m r
runContT <span style="color: green;">&#40;</span>ContT m<span style="color: green;">&#41;</span> = m <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a>
&nbsp;</pre>
<p><code>ContT</code> and <code>Codensity</code> both yield a result in which all of the uses of the underlying monad's <code>(>>=)</code> are right associated.</p>
<p>This can be convenient for two reasons:</p>
<p>First, some almost-monads are not associative, and converting to ContT or Codensity can be used to fix this fact. </p>
<p>Second, in many monads, when you build a big structure using left associated binds, like:</p>
<pre class="haskell">&nbsp;
    <span style="color: green;">&#40;</span>f &gt;&gt;= g<span style="color: green;">&#41;</span> &gt;&gt;= h
&nbsp;</pre>
<p>rather than use right associated binds like</p>
<pre class="haskell">&nbsp;
   f &gt;&gt;= \x -&gt; g x &gt;&gt;= h
&nbsp;</pre>
<p>then you wind up building a structure, then tearing it down and building up a whole new structure. This can compromise the productivity of the result, and it can also affect the asymptotic performance of your code. </p>
<p>Even though the monad laws say these two yield the same answer.</p>
<p><strong>The dual of substitution is redecoration</strong></p>
<p>To see that, first, it is worth noting that about ten years back, Tarmo Uustalu and Varmo Vene wrote "<a href="http://www.ioc.ee/~tarmo/papers/sfp01-book.pdf">The dual of substitition is redecoration</a>", which among other things quite eloquently described how monads are effectively about substituting new tree-like structures, and then renormalizing.</p>
<p>This can be seen in terms of the more categorical viewpoint, where we define a monad in terms of <code>return</code>, <code>fmap</code> and <code>join</code>, rather than <code>return</code> and <code>(>>=)</code>. In that presentation:</p>
<pre class="haskell">&nbsp;
m &gt;&gt;= f = join <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f m<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p><code>fmap</code> is performing substitution. and <code>join</code> is dealing with any renormalization.</p>
<p>Done this way, <code>(m >>= f)</code> on the <code>Maybe</code> monad would first <code>fmap</code> to obtain <code>Just (Just a)</code>, <code>Just Nothing</code> or <code>Nothing</code> before flattening.</p>
<p>In the Maybe a case, the association of your binds is largely immaterial, the normalization pass fixes things up to basically the same size, but in the special case of a free monad the monad is <strong>purely defined in terms of substitution</strong>, since:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- join :: Functor f =&gt; Free f (Free f a) -&gt; Free f a</span>
<span style="color: #5d478b; font-style: italic;">-- join (Pure a) = a</span>
<span style="color: #5d478b; font-style: italic;">-- join (Free as) = Free (fmap join as)</span>
&nbsp;</pre>
<p>This means that every time you <code>>>=</code> a free monad you are accumulating structure -- structure that you have traverse past to deal with subsequent left-associated invocations of <code>>>=</code>! Free monads never shrink after a bind and the main body of the tree never changes.</p>
<p>More concretely, you could build a binary tree with</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- data Tree a = Tip a | Bin (Tree a) (Tree a)</span>
&nbsp;</pre>
<p>and make a monad out of it, writing out your <code>return</code> and <code>(>>=)</code>, etc. by hand</p>
<p>The same monad could be had 'for free' by taking the free monad of</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Bin a = Bin a a
    <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>, Foldable, Traversable<span style="color: green;">&#41;</span>
    <span style="color: #5d478b; font-style: italic;">-- using LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable</span>
&nbsp;</pre>
<p>yielding the admittedly slightly less convenient type signature</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Tree = Free Bin
&nbsp;</pre>
<p>Now you can use <code>return</code> for <code>Tip</code>, and </p>
<pre class="haskell">&nbsp;
bin :: MonadFree Bin m =&gt; m a -&gt; m a -&gt; m a
bin l r = wrap <span style="color: green;">&#40;</span>Bin l r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>to construct a binary tree node, using any free monad representation.</p>
<p>Now, if that representation is <code>Free Bin</code> (or the original more direct <code>Tree</code> type above) then code that looks like <code>f >>= \x -> g x >>= h</code> performs fine, but <code>(f >>= g) >>= h</code> will retraverse the unchanging 'trunk' of the tree structure twice. That isn't so bad, but given n uses of >>= we'll traverse an ever-growing trunk over and over <em>n</em> times!</p>
<p><strong>Putting Codensity to Work</strong></p>
<p>But, we have a tool that can fix this, <code>Codensity</code>! </p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadFree f m =&gt; MonadFree f <span style="color: green;">&#40;</span>Codensity m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  wrap t = Codensity <span style="color: green;">&#40;</span>\h -&gt; wrap <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>\p -&gt; runCodensity p h<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Janis packaged up the use of <code>Codensity</code> into a nice combinator that you can sprinkle through your code, so that your users never need know it exists. Moreover, it prevents them from accidentally using any of the extra power of the intermediate representation. If your code typechecks before you use improve somewhere within it, and it type checks after, then it will yield the same answer.</p>
<pre class="haskell">&nbsp;
improve :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> m. MonadFree f m =&gt; m a<span style="color: green;">&#41;</span> -&gt; Free f a
improve m = lowerCodensity m
&nbsp;</pre>
<p>By now, it should be clear that the power of <code>Codensity</code> is sufficient to the task, but is it necessary?</p>
<p>More Soon.</p>
<p>[Edit; Fixed minor typographical errors pointed out by ShinNoNoir, ivanm, and Josef Svenningsson, including a whole bunch of them found by Noah Easterly]</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/free-monads-for-less/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Kan Extensions III: As Ends and Coends</title>
		<link>http://comonad.com/reader/2008/kan-extension-iii/</link>
		<comments>http://comonad.com/reader/2008/kan-extension-iii/#comments</comments>
		<pubDate>Tue, 27 May 2008 00:22:07 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Mathematics]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/2008/kan-extension-iii/</guid>
		<description><![CDATA[Grant B. asked me to post the derivation for the right and left Kan extension formula used in previous Kan Extension posts (1,2). For that we can turn to the definition of Kan extensions in terms of ends, but first we need to take a couple of steps back to find a way to represent [...]]]></description>
			<content:encoded><![CDATA[<p>Grant B. <a href="http://comonad.com/reader/2008/kan-extensions/#comment-1412">asked me</a> to post the derivation for the right and left Kan extension formula used in previous Kan Extension posts (<a href="http://comonad.com/reader/2008/kan-extensions/">1</a>,<a href="http://comonad.com/reader/2008/kan-extensions-ii/">2</a>). For that we can turn to the definition of Kan extensions in terms of ends, but first we need to take a couple of steps back to find a way to represent (co)ends in Haskell.</p>
<p><span id="more-65"></span></p>
<p><b>Dinatural Transformations</b></p>
<p>Rather than repeat the <a href="http://en.wikipedia.org/wiki/Dinatural_transformation">definition</a> here, we'll just note we can define a dinatural transformation in Haskell letting polymorphism represent the family of morphisms.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Dinatural f g = <span style="color: #06c; font-weight: bold;">forall</span> a. f a a -&gt; g a a
&nbsp;</pre>
<p><b>Ends</b></p>
<p>So what is an end?</p>
<p>An end is a universal dinatural transformation from some object e to some functor s.</p>
<p>Diving into the formal definition:</p>
<p>Given a functor <img src='http://comonad.com/latex/b35dfd1bbc05f7e719f05a2175be3373.png' title='$F : \mathcal{C}^{op} \times \mathcal{C} -&gt; \mathcal{D}$' alt='$F : \mathcal{C}^{op} \times \mathcal{C} -&gt; \mathcal{D}$' align=absmiddle>, and end of <img src='http://comonad.com/latex/b8bc815b5e9d5177af01fd4d3d3c2f10.png' title='$F$' alt='$F$' align=absmiddle> is a pair <img src='http://comonad.com/latex/763a93bddd524facef7935b3d88a7ffa.png' title='$(e,\omega)$' alt='$(e,\omega)$' align=absmiddle> where <img src='http://comonad.com/latex/8cd34385ed61aca950a6b06d09fb50ac.png' title='$e$' alt='$e$' align=absmiddle> is an object of <img src='http://comonad.com/latex/eaf85f2b753a4c7585def4cc7ecade43.png' title='$\mathcal{D}$' alt='$\mathcal{D}$' align=absmiddle> and omega is a dinatural transformation from e to S such that given any other dinatural transformation <img src='http://comonad.com/latex/8217ed3c32a785f0b5aad4055f432ad8.png' title='$\beta$' alt='$\beta$' align=absmiddle> to S from another object x in <img src='http://comonad.com/latex/eaf85f2b753a4c7585def4cc7ecade43.png' title='$\mathcal{D}$' alt='$\mathcal{D}$' align=absmiddle>, there exists a unique morphism <img src='http://comonad.com/latex/a055131dbf96d032acc4a3cb6b0d026c.png' title='$h : x -&gt; e$' alt='$h : x -&gt; e$' align=absmiddle>, such that <img src='http://comonad.com/latex/b939ce746b7bc891ee36616d56a98750.png' title='$\beta_a = \omega_a \cdot h$' alt='$\beta_a = \omega_a \cdot h$' align=absmiddle> for every <img src='http://comonad.com/latex/44bc9d542a92714cac84e01cbbb7fd61.png' title='$a$' alt='$a$' align=absmiddle> in <img src='http://comonad.com/latex/db5f7b3e9934fbc5a2859d88c4ba84a3.png' title='$\mathcal{C}$' alt='$\mathcal{C}$' align=absmiddle>. </p>
<p>We usually choose to write ends as <img src='http://comonad.com/latex/d19bfb8af65a4892a19718fee54deacf.png' title='$e = \int_c S(c,c)$' alt='$e = \int_c S(c,c)$' align=absmiddle>, and abuse terminology calling <img src='http://comonad.com/latex/8cd34385ed61aca950a6b06d09fb50ac.png' title='$e$' alt='$e$' align=absmiddle> the end of <img src='http://comonad.com/latex/e257acd1ccbe7fcb654708f1a866bfe9.png' title='$S$' alt='$S$' align=absmiddle>.</p>
<p>Note this uses a dinatural transformation from an object <img src='http://comonad.com/latex/332cc365a4987aacce0ead01b8bdcc0b.png' title='$x$' alt='$x$' align=absmiddle> in <img src='http://comonad.com/latex/eaf85f2b753a4c7585def4cc7ecade43.png' title='$\mathcal{D}$' alt='$\mathcal{D}$' align=absmiddle>, which we can choose to represent an arbitrary dinatural transformation from an object <img src='http://comonad.com/latex/332cc365a4987aacce0ead01b8bdcc0b.png' title='$x$' alt='$x$' align=absmiddle> to a functor <img src='http://comonad.com/latex/e257acd1ccbe7fcb654708f1a866bfe9.png' title='$S$' alt='$S$' align=absmiddle> in terms of a dinatural transformation from the constant bifunctor:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Const x a b = Const <span style="color: green;">&#123;</span> runConst :: x <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>This leaves us with the definition of a dinatural transformation from an object as:</p>
<pre class="haskell">&nbsp;
Dinatural <span style="color: green;">&#40;</span>Const x<span style="color: green;">&#41;</span> s ~ <span style="color: #06c; font-weight: bold;">forall</span> a. Const x a a -&gt; s a a
&nbsp;</pre>
<p>but the universal quantification over the <code>Const</code> term is rather useless and the <code>Const</code> bifunctor is supplying no information so we can just specialize that down to:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> DinaturalFromObject x s = x -&gt; <span style="color: #06c; font-weight: bold;">forall</span> a. s a a
&nbsp;</pre>
<p>Now, clearly for any such transformation, we could rewrite it trivially using the definition:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> End s = <span style="color: #06c; font-weight: bold;">forall</span> a. s a a
&nbsp;</pre>
<p>with <img src='http://comonad.com/latex/ae4fb5973f393577570881fc24fc2054.png' title='$\omega$' alt='$\omega$' align=absmiddle> = id.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> DinaturalFromObject x s = x -&gt; End s
&nbsp;</pre>
<p>And so <code>End</code> above fully complies with the definition for an end, and we just say <code>e = End s</code> abusing the terminology as earlier. The function <img src='http://comonad.com/latex/ae4fb5973f393577570881fc24fc2054.png' title='$\omega$' alt='$\omega$' align=absmiddle> = id is implicit.</p>
<p>For End to be a proper end, we assume that <code>s</code> is contravariant in its first argument and covariant in its second argument. </p>
<p><b>Example: Hom</b></p>
<p>A good example of this is (->) in Haskell, which is as category theory types would call it the Hom functor for Hask. Then <code>End (->) = forall a. a -> a</code> which has just one inhabitant <code>id</code> if you discard cheating inhabitants involving fix or undefined.</p>
<p>We write <img src='http://comonad.com/latex/e543f80f31bc5a83531f2fcdb5060939.png' title='$\mathcal{C}(a,b)$' alt='$\mathcal{C}(a,b)$' align=absmiddle> or <img src='http://comonad.com/latex/7b68f95bd81ad0dc547e30c61e293a2a.png' title='$\mathrm{Hom}_\mathcal{C}(a,b)$' alt='$\mathrm{Hom}_\mathcal{C}(a,b)$' align=absmiddle> to denote <code>a -> b</code>. Similarly we use <img src='http://comonad.com/latex/de56b5a9d12dc80210c09c1ff97b423a.png' title='b^a' alt='b^a' align=absmiddle> to denote an exponential object within a category, and since in Haskell we have first class functions using the same syntax this also translates to <code>a -> b</code>. We'll need these later.</p>
<p><b>Example: Natural Transformations</b></p>
<p>If we define:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> HomFG f g a b =
        HomFG <span style="color: green;">&#123;</span> runHomFG :: f a -&gt; g b <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>then we <em>could</em> of course choose to define natural transformations in terms of <code>End</code> as:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Nat f g = End <span style="color: green;">&#40;</span>HomFG f g<span style="color: green;">&#41;</span> <span style="color: #5d478b; font-style: italic;">-- forall a. f a -&gt; g a</span>
&nbsp;</pre>
<p><b>Right Kan Extension as an End</b></p>
<p>Turning to <a href="http://en.wikipedia.org/wiki/Kan_extension#Kan_extensions_as_coends">Wikipedia</a> or Categories for the Working Mathematician you can find the following definition for right Kan extension of <img src='http://comonad.com/latex/2f118ee06d05f3c2d98361d9c30e38ce.png' title='$T$' alt='$T$' align=absmiddle> along <img src='http://comonad.com/latex/d6328eaebbcd5c358f426dbea4bdbf70.png' title='$K$' alt='$K$' align=absmiddle> in terms of ends.</p>
<p><img src='http://comonad.com/latex/dea76fc481ff2c837e2e80f8a7973197.png' title='$(\mathrm{Ran}_KT)c=\int_m Tm^{\mathbf{C}(c,Km)}$' alt='$(\mathrm{Ran}_KT)c=\int_m Tm^{\mathbf{C}(c,Km)}$' align=absmiddle></p>
<p>Working by rote, we note that <img src='http://comonad.com/latex/51b8b6f515e3601005740530f09382dd.png' title='$\mathbf{C}(c,Km)$' alt='$\mathbf{C}(c,Km)$' align=absmiddle> is just <code>c -> K m</code> as noted above, and that <img src='http://comonad.com/latex/05979bd4b7a87c197852764db8aef119.png' title='$(Tm)^{\mathbf{C}(c,Km)}$' alt='$(Tm)^{\mathbf{C}(c,Km)}$' align=absmiddle> is then just <code>(c -> K m) -> T m'</code>. So now we just have to take the end over that, and read off:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> RanT k t c m m' = <span style="color: green;">&#40;</span>c -&gt; k m<span style="color: green;">&#41;</span> -&gt; t m'
<span style="color: #06c; font-weight: bold;">type</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> k t c = End <span style="color: green;">&#40;</span>RanT k t c<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Which, modulo newtype noise is the same as the type previously supplied type:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> f g c = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#123;</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> :: <span style="color: #06c; font-weight: bold;">forall</span> m. <span style="color: green;">&#40;</span>c -&gt; f m<span style="color: green;">&#41;</span> -&gt; g m <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p><b>Coends</b></p>
<p>The derivation for the left Kan extension follows similarly from defining <a href="http://en.wikipedia.org/wiki/Coend_%28category_theory%29#Coend">coends</a> over <strong>Hask</strong> in terms of existential quantification and copowers as products.</p>
<p>The coend derivation is complicated slightly by Haskell's semantics. Disposing of the constant bifunctor as before we get:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> DinaturalToObject s c = <span style="color: #06c; font-weight: bold;">forall</span> a. <span style="color: green;">&#40;</span>s a a -&gt; c<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Which since we want to be able to box up the s a a term separately, we need to use existential quantification.</p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> a. s a a -&gt; c<span style="color: green;">&#41;</span> ~ <span style="color: green;">&#40;</span>exists a. s a a<span style="color: green;">&#41;</span> -&gt; c
&nbsp;</pre>
<p>We cannot represent this directly in terms of a type annotation in Haskell, but we can do so with a data type: </p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Coend f = <span style="color: #06c; font-weight: bold;">forall</span> a. Coend <span style="color: green;">&#40;</span>f a a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Recall that in Haskell, existential quantification is represented by using universal quantification outside of the type constructor.</p>
<p>The main difference is that in our coend <img src='http://comonad.com/latex/00d7106d8a39b341522cc78f15d1b1bc.png' title='$(e,\zeta)$' alt='$(e,\zeta)$' align=absmiddle> the function <img src='http://comonad.com/latex/e5c0c55191274dbb2a4499ab5c5b8175.png' title='$\zeta$' alt='$\zeta$' align=absmiddle> is now <code>runCoend</code> instead of <code>id</code>, because we have a <code>Coend</code> data constructor around the existential. Technicalities make it a little more complicated than that even, because you can't define a well-typed <code>runCoend</code> and have to use pattern matching on the <code>Coend</code> data constructor to avoid having an existentially quantified type escape the current scope, but the idea is the same.</p>
<p><b>Left Kan Extension as a Coend</b></p>
<p>Then given the definition for the left Kan extension of <img src='http://comonad.com/latex/2f118ee06d05f3c2d98361d9c30e38ce.png' title='$T$' alt='$T$' align=absmiddle> along <img src='http://comonad.com/latex/d6328eaebbcd5c358f426dbea4bdbf70.png' title='$K$' alt='$K$' align=absmiddle> as a coend:</p>
<p><img src='http://comonad.com/latex/a40bec8bbeec6c224b4fb32c1f7c2cda.png' title='$(\mathrm{Lan}_KT)c=\int^m \mathbf{C}(Km,c)\cdot Tm$' alt='$(\mathrm{Lan}_KT)c=\int^m \mathbf{C}(Km,c)\cdot Tm$' align=absmiddle></p>
<p>we can read off:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> LanT k t c m m' = LanT <span style="color: green;">&#40;</span>k m -&gt; c<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>t m'<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">type</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> k t c = Coend <span style="color: green;">&#40;</span>LanT k t c<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Which is <em>almost</em> isomorphic to the previously supplied type:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> k t c = <span style="color: #06c; font-weight: bold;">forall</span> m. <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <span style="color: green;">&#40;</span>k m -&gt; c<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>t m<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>except for the fact that we had to use two layers of data declarations when using the separate <code>Coend</code> data type, so we introduced an extra place for a <img src='http://comonad.com/latex/d1cca51f81e4659e1d2de727392d4476.png' title='$\perp$' alt='$\perp$' align=absmiddle> to hide. </p>
<p>A <code>newtype</code> isn't allowed to use existential quantification in Haskell, so this form forces a spurious case analysis that we'd prefer to do without. This motivates why <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/category-extras">category-extras</a> uses a separate definition for <code>Lan</code> rather than the more elaborate definition in terms of <code>Coend</code>.</p>
<p>[Edit: Fixed a typo in the definition of RanT]</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2008/kan-extension-iii/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Kan Extensions II: Adjunctions, Composition, Lifting</title>
		<link>http://comonad.com/reader/2008/kan-extensions-ii/</link>
		<comments>http://comonad.com/reader/2008/kan-extensions-ii/#comments</comments>
		<pubDate>Fri, 23 May 2008 00:13:13 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Monads]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/2008/kan-extensions-ii/</guid>
		<description><![CDATA[I want to spend some more time talking about Kan extensions, composition of Kan extensions, and the relationship between a monad and the monad generated by a monad.
But first, I want to take a moment to recall adjunctions and show how they relate to some standard (co)monads, before tying them back to Kan extensions.
Adjunctions 101
An [...]]]></description>
			<content:encoded><![CDATA[<p>I want to spend some more time talking about Kan extensions, composition of Kan extensions, and the relationship between a monad and the monad generated by a monad.</p>
<p>But first, I want to take a moment to recall adjunctions and show how they relate to some standard (co)monads, before tying them back to <a href="http://comonad.com/reader/2008/kan-extensions/">Kan extensions</a>.</p>
<p><b>Adjunctions 101</b></p>
<p>An adjunction between categories <img src='http://comonad.com/latex/db5f7b3e9934fbc5a2859d88c4ba84a3.png' title='$\mathcal{C}$' alt='$\mathcal{C}$' align=absmiddle> and <img src='http://comonad.com/latex/eaf85f2b753a4c7585def4cc7ecade43.png' title='$\mathcal{D}$' alt='$\mathcal{D}$' align=absmiddle> consists of a pair of functors <img src='http://comonad.com/latex/643ec496aeec2eb4f7cdeeeab943a717.png' title='$F : \mathcal{C} -&gt; \mathcal{D}$' alt='$F : \mathcal{C} -&gt; \mathcal{D}$' align=absmiddle>, and <img src='http://comonad.com/latex/eaa04d33f0ae2a183ec4b02f98486860.png' title='$G : \mathcal{D} -&gt; \mathcal{C}$' alt='$G : \mathcal{D} -&gt; \mathcal{C}$' align=absmiddle> and a natural isomorphism:</p>
<p><img src='http://comonad.com/latex/84b7d3e3e76f4dbe53fea154dac9b8f8.png' title='$\phi : \mathrm{Hom}_\mathcal{D} (F-, =) -&gt; \mathrm{Hom}_\mathcal{C} (-, G=)$' alt='$\phi : \mathrm{Hom}_\mathcal{D} (F-, =) -&gt; \mathrm{Hom}_\mathcal{C} (-, G=)$' align=absmiddle></p>
<p>We call <img src='http://comonad.com/latex/b8bc815b5e9d5177af01fd4d3d3c2f10.png' title='$F$' alt='$F$' align=absmiddle> the left adjoint functor, and <img src='http://comonad.com/latex/5201385589993766eea584cd3aa6fa13.png' title='$G$' alt='$G$' align=absmiddle> the right adjoint functor and <img src='http://comonad.com/latex/599386ddd45d1479f1992f0f7183ac22.png' title='$(F,G)$' alt='$(F,G)$' align=absmiddle> an adjoint pair, and write this relationship as <img src='http://comonad.com/latex/754907e967821ca061438630f9c72a7d.png' title='$F \dashv G$' alt='$F \dashv G$' align=absmiddle></p>
<p><span id="more-64"></span></p>
<p>Borrowing a Haskell definition from Dave Menendez, an adjunction from the category of Haskell types (<strong>Hask</strong>) to <strong>Hask</strong> given by a pair of Haskell <code>Functor</code> instances can be defined as follows, where phi is witnessed by <img src='http://comonad.com/latex/f50853d41be7d55874e952eb0d80c53e.png' title='$\phi$' alt='$\phi$' align=absmiddle> = <code>leftAdjunct</code> and <img src='http://comonad.com/latex/0f615b0f2c4e9e9f67b2b7d0c33798f2.png' title='$\phi^{-1}$' alt='$\phi^{-1}$' align=absmiddle> = <code>rightAdjunct</code>. [<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html">haddock</a>]</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> g<span style="color: green;">&#41;</span> =&gt;
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g | f -&gt; g, g -&gt; f <span style="color: #06c; font-weight: bold;">where</span>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:unit"><span style="font-weight: bold;">unit</span></a>   :: a -&gt; g <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:counit"><span style="font-weight: bold;">counit</span></a> :: f <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span> -&gt; a
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a>  :: <span style="color: green;">&#40;</span>f a -&gt; b<span style="color: green;">&#41;</span> -&gt; a -&gt; g b
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> :: <span style="color: green;">&#40;</span>a -&gt; g b<span style="color: green;">&#41;</span> -&gt; f a -&gt; b
&nbsp;
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:unit"><span style="font-weight: bold;">unit</span></a> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:counit"><span style="font-weight: bold;">counit</span></a> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> f = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f . <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:unit"><span style="font-weight: bold;">unit</span></a>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> f = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:counit"><span style="font-weight: bold;">counit</span></a> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f
&nbsp;</pre>
<p><b>Currying and Uncurrying</b></p>
<p>The most well known adjunction to a Haskell programmer is between the functors given by <code>((,)e)</code> and <code>((->)e)</code>. (Recall that you can read <code>((,)e)</code> as <code>(e,)</code> and <code>((->)e)</code> as <code>(e->)</code>; however, the latter syntax isn't valid Haskell as you aren't allowed to make <code>(,)</code> and <code>(->)</code> sections. We use this adjunction most every day in the form of the functions <code>curry</code> and <code>uncurry</code>. </p>
<pre class="haskell">&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:curry"><span style="font-weight: bold;">curry</span></a> :: <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a, b<span style="color: green;">&#41;</span> -&gt; c<span style="color: green;">&#41;</span> -&gt; a -&gt; b -&gt; c
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:curry"><span style="font-weight: bold;">curry</span></a> f x y = f <span style="color: green;">&#40;</span>x,y<span style="color: green;">&#41;</span>
&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> :: <span style="color: green;">&#40;</span>a -&gt; b -&gt; c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a, b<span style="color: green;">&#41;</span> -&gt; c
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> f ~<span style="color: green;">&#40;</span>x,y<span style="color: green;">&#41;</span> = f x y
&nbsp;</pre>
<p>However the arguments are unfortunately slightly flipped around when we go to define this as an adjunction.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span>e<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span>e<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> f a e  = f <span style="color: green;">&#40;</span>e,a<span style="color: green;">&#41;</span>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> f ~<span style="color: green;">&#40;</span>e,a<span style="color: green;">&#41;</span> = f a e
&nbsp;</pre>
<p>This adjunction defines the relationship between the anonymous <a href="http://www.haskell.org/all_about_monads/html/readermonad.html">reader monad</a> and the anonymous <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad-Reader.html">reader comonad</a> (aka the product comonad). </p>
<p><b>All Readers are the Same</b></p>
<p>As an aside, if you look at the reader arrow, reader monad and reader comonad all side by side you can see that they are all basically the same thing. Kleisli arrows for the anonymous reader monad have the form <code>a -> e -> b</code>. The Reader arrow takes the form <code>arr (a, e) b</code>, which when <code>arr</code> is <code>(->)</code> this reads as <code>(a,e) -> b</code>, which is just a curried Kleisli arrow for the Reader monad. On the other hand the reader comonad is <code>((,)e)</code>, and its CoKleisli arrows have the form <code>(e,a) -> b</code>. So, putting these side by side: </p>
<pre class="haskell">&nbsp;
a -&gt; e -&gt; b
<span style="color: green;">&#40;</span>a , e<span style="color: green;">&#41;</span> -&gt; b
<span style="color: green;">&#40;</span>e , a<span style="color: green;">&#41;</span> -&gt; b
&nbsp;</pre>
<p>You can clearly see these are all the same thing!</p>
<p><b>State and Composing Adjunctions</b></p>
<p>Once we define functor composition:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> O f g a = Compose <span style="color: green;">&#123;</span> decompose :: f <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> g<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>f `O` g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
        <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f = Compose . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> . decompose
&nbsp;</pre>
<p>We can see that every adjunction gives rise to a monad:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>g `O` f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
        <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> = Compose . <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:unit"><span style="font-weight: bold;">unit</span></a>
        m &gt;&gt;= f =
             Compose .
             <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> <span style="color: green;">&#40;</span>decompose . f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> $
             decompose m
&nbsp;</pre>
<p>and if you happen to have a <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html">Comonad typeclass</a> lying around, a comonad:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w <span style="color: #06c; font-weight: bold;">where</span>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> :: w a -&gt; a
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a> :: w a -&gt; w <span style="color: green;">&#40;</span>w a<span style="color: green;">&#41;</span>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> :: <span style="color: green;">&#40;</span>w a -&gt; b<span style="color: green;">&#41;</span> -&gt; w a -&gt; w b
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> f = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f . <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g =&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> <span style="color: green;">&#40;</span>f `O` g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:counit"><span style="font-weight: bold;">counit</span></a> . decompose
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> f =
                Compose .
                <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> <span style="color: green;">&#40;</span>f . Compose<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> .
                decompose
&nbsp;</pre>
<p>In reality, adjunction composition is of course not the only way you could form a monad by composition, so in practice a single composition constructor leads to ambiguity. Hence why in category-extras there is a base <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Composition.html"><code>CompF</code></a> functor, and <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t%3AACompF">specialized variations</a> for different desired instances. For simplicity, I'll stick to <code>`O`</code> here.</p>
<p>We can compose adjunctions, yielding an adjunction, so long as we are careful to place things in the right order:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f1 g1, <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f2 g2<span style="color: green;">&#41;</span> =&gt;
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> <span style="color: green;">&#40;</span>f2 `O` f1<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>g1 `O` g2<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:counit"><span style="font-weight: bold;">counit</span></a> =
               <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:counit"><span style="font-weight: bold;">counit</span></a> .
               <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:counit"><span style="font-weight: bold;">counit</span></a> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> decompose<span style="color: green;">&#41;</span> .
               decompose
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:unit"><span style="font-weight: bold;">unit</span></a> =
               Compose .
               <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> Compose . <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:unit"><span style="font-weight: bold;">unit</span></a><span style="color: green;">&#41;</span> .
               <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:unit"><span style="font-weight: bold;">unit</span></a>
&nbsp;</pre>
<p>In fact, if we use the adjunction defined above, we can see that its just the <code>State</code> monad!</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadState e <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span>e `O` <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span>e<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
        get = compose $ \s -&gt; <span style="color: green;">&#40;</span>s,s<span style="color: green;">&#41;</span>
        put s = compose $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> <span style="color: green;">&#40;</span>s,<span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Not that I'd be prone to consider using that representation, but we can also see that we get the <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad-Context.html">context comonad</a> this way:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt;
    ComonadContext s w | w -&gt; s <span style="color: #06c; font-weight: bold;">where</span>
        getC :: w a -&gt; s
        modifyC :: <span style="color: green;">&#40;</span>s -&gt; s<span style="color: green;">&#41;</span> -&gt; w a -&gt; a
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> ComonadContext e <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span>e `O` <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span>e<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
        getC = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a> . decompose
        modifyC f = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> . f<span style="color: green;">&#41;</span> . decompose
&nbsp;</pre>
<p><b>Adjunctions as Kan Extensions</b></p>
<p>Unsurprisingly, since pretty much all of category theory comes around to being an observation about Kan extensions in the end, we can find some laws relating left- and right- Kan extensions to adjunctions.</p>
<p>Recall the definitions for right and left Kan extensions over <b>Hask</b>:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> g h a = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a>
        <span style="color: green;">&#123;</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> :: <span style="color: #06c; font-weight: bold;">forall</span> b. <span style="color: green;">&#40;</span>a -&gt; g b<span style="color: green;">&#41;</span> -&gt; h b <span style="color: green;">&#125;</span>
<span style="color: #06c; font-weight: bold;">data</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> g h a = <span style="color: #06c; font-weight: bold;">forall</span> b. <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <span style="color: green;">&#40;</span>g b -&gt; a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>h b<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Formally, <img src='http://comonad.com/latex/5b71d6dacbdcea5e00e534e92b576d55.png' title='F \dashv G' alt='F \dashv G' align=absmiddle> if and only if the right Kan extension <img src='http://comonad.com/latex/775c574bc0cb7d42c94f7417ba8350b4.png' title='$\mathrm{Ran}_G 1$' alt='$\mathrm{Ran}_G 1$' align=absmiddle> exists and is preserved by <img src='http://comonad.com/latex/5201385589993766eea584cd3aa6fa13.png' title='$G$' alt='$G$' align=absmiddle>. (Saunders Mac Lane, Categories for the Working Mathematician p248). We can use this  in Haskell to define a <a href="http://en.wikipedia.org/wiki/Natural_transformation">natural isomorphism</a> between <code>f</code> and <code>Ran g Identity</code> witnessed by <code>adjointToRan</code> and <code>ranToAdjoint</code> below:</p>
<pre class="haskell">&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:adjointToRan"><span style="font-weight: bold;">adjointToRan</span></a> :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g =&gt; f a -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> g Identity a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:adjointToRan"><span style="font-weight: bold;">adjointToRan</span></a> f = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>\a -&gt; Identity $ <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> a f<span style="color: green;">&#41;</span>
&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:ranToAdjoint"><span style="font-weight: bold;">ranToAdjoint</span></a> :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g =&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> g Identity a -&gt; f a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:ranToAdjoint"><span style="font-weight: bold;">ranToAdjoint</span></a> r = runIdentity <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> r <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:unit"><span style="font-weight: bold;">unit</span></a><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>We can construct a similar natural isomorphism for the right adjoint <code>g</code> of a <code>Functor</code> <code>f</code> and <code>Lan f Identity</code>:</p>
<pre class="haskell">&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:adjointToLan"><span style="font-weight: bold;">adjointToLan</span></a> :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g =&gt; g a -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f Identity a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:adjointToLan"><span style="font-weight: bold;">adjointToLan</span></a> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:counit"><span style="font-weight: bold;">counit</span></a> . Identity
&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:lanToAdjoint"><span style="font-weight: bold;">lanToAdjoint</span></a> :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g =&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f Identity a -&gt; g a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:lanToAdjoint"><span style="font-weight: bold;">lanToAdjoint</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f v<span style="color: green;">&#41;</span> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> f <span style="color: green;">&#40;</span>runIdentity v<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>So, with that in hand we can see that <code>Ran f Identity -| f -| Lan f Identity</code>, presuming <code>Ran f Identity</code> and <code>Lan f Identity</code> exist. </p>
<p><b>A More General Connection</b></p>
<p>Now, the first isomorphism above can be seen as a special case of a more general law relating functor composition and Kan extensions, where <code>h = Identity</code> in the composition below:</p>
<pre class="haskell">&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:ranToComposedAdjoint"><span style="font-weight: bold;">ranToComposedAdjoint</span></a> ::
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g =&gt;
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> g h a -&gt; <span style="color: green;">&#40;</span>h `O` f<span style="color: green;">&#41;</span> a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:ranToComposedAdjoint"><span style="font-weight: bold;">ranToComposedAdjoint</span></a> r = Compose <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> r <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:unit"><span style="font-weight: bold;">unit</span></a><span style="color: green;">&#41;</span>
&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:composedAdjointToRan"><span style="font-weight: bold;">composedAdjointToRan</span></a> ::
        <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> h, <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g<span style="color: green;">&#41;</span> =&gt;
        <span style="color: green;">&#40;</span>h `O` f<span style="color: green;">&#41;</span> a -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> g h a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:composedAdjointToRan"><span style="font-weight: bold;">composedAdjointToRan</span></a> f =
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>\a -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:rightAdjunct"><span style="font-weight: bold;">rightAdjunct</span></a> a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>decompose f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Similarly , we get the more generalize relationship for <code>Lan</code>:</p>
<pre class="haskell">&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:lanToComposedAdjoint"><span style="font-weight: bold;">lanToComposedAdjoint</span></a> ::
        <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> h, <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g<span style="color: green;">&#41;</span> =&gt;
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f h a -&gt; <span style="color: green;">&#40;</span>h `o` g<span style="color: green;">&#41;</span> a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:lanToComposedAdjoint"><span style="font-weight: bold;">lanToComposedAdjoint</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f v<span style="color: green;">&#41;</span> =
        Compose <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:leftAdjunct"><span style="font-weight: bold;">leftAdjunct</span></a> f<span style="color: green;">&#41;</span> v<span style="color: green;">&#41;</span>
&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:composedAdjointToLan"><span style="font-weight: bold;">composedAdjointToLan</span></a> ::
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#t:Adjunction"><span style="background-color: #efefbf; font-weight: bold;">Adjunction</span></a> f g =&gt;
        <span style="color: green;">&#40;</span>h `o` g<span style="color: green;">&#41;</span> a -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f h a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:composedAdjointToLan"><span style="font-weight: bold;">composedAdjointToLan</span></a> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Adjunction.html#v:counit"><span style="font-weight: bold;">counit</span></a> . decompose
&nbsp;</pre>
<p><b>Composing Kan Extensions</b></p>
<p>Using the above with the laws for composing right Kan extensions:</p>
<pre class="haskell">&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:composeRan"><span style="font-weight: bold;">composeRan</span></a> :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> f <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> g h<span style="color: green;">&#41;</span> a -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>f `O` g<span style="color: green;">&#41;</span> h a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:composeRan"><span style="font-weight: bold;">composeRan</span></a> r =
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>\f -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> r <span style="color: green;">&#40;</span>decompose . f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a><span style="color: green;">&#41;</span>
&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:decomposeRan"><span style="font-weight: bold;">decomposeRan</span></a> ::
        <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt;
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>f `O` g<span style="color: green;">&#41;</span> h a -&gt;  <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> f <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> g h<span style="color: green;">&#41;</span> a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:decomposeRan"><span style="font-weight: bold;">decomposeRan</span></a> r =
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>\f -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>\g -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> r <span style="color: green;">&#40;</span>Compose . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> g . f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>or the laws for composing left Kan extensions: </p>
<pre class="haskell">&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:composeLan"><span style="font-weight: bold;">composeLan</span></a> ::
        <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt;
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> g h<span style="color: green;">&#41;</span> a -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <span style="color: green;">&#40;</span>f `O` g<span style="color: green;">&#41;</span> h a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:composeLan"><span style="font-weight: bold;">composeLan</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> g h<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> =
        <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <span style="color: green;">&#40;</span>f . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> g . decompose<span style="color: green;">&#41;</span> h
&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:decomposeLan"><span style="font-weight: bold;">decomposeLan</span></a> :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <span style="color: green;">&#40;</span>f `O` g<span style="color: green;">&#41;</span> h a -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> g h<span style="color: green;">&#41;</span> a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:decomposeLan"><span style="font-weight: bold;">decomposeLan</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f h<span style="color: green;">&#41;</span> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <span style="color: green;">&#40;</span>f . compose<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> h<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>can give you a lot of ways to construct monads:</p>
<p><b>Right Kan Extension as (almost) a Monad Transformer</b></p>
<p>You can lift many of operations from a monad m to the codensity monad of <code>m</code>. Unfortunately, we don't have quite the right type signature for an instance of <code>MonadTrans</code>, so we'll have to make do with our own methods:</p>
<p>[Edit: this has been since factored out into <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Monad-Codensity.html">Control.Monad.Codensity</a> to allow <code>Codensity</code> to actually be an instance of <code>MonadTrans</code>]</p>
<pre class="haskell">&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:liftRan"><span style="font-weight: bold;">liftRan</span></a> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; m a -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> m m a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:liftRan"><span style="font-weight: bold;">liftRan</span></a> m = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>m &gt;&gt;=<span style="color: green;">&#41;</span>
&nbsp;
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:lowerRan"><span style="font-weight: bold;">lowerRan</span></a> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> m m a -&gt; m a
<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:lowerRan"><span style="font-weight: bold;">lowerRan</span></a> a = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> a <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadReader r m =&gt;
    MonadReader r <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> m m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
        ask = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:liftRan"><span style="font-weight: bold;">liftRan</span></a> ask
        local f m = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>\c -&gt; ask &gt;&gt;=
              \r -&gt; local f <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> m <span style="color: green;">&#40;</span>local <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> r<span style="color: green;">&#41;</span> . c<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadIO m =&gt;
    MonadIO <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> m m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
        liftIO = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:liftRan"><span style="font-weight: bold;">liftRan</span></a> . liftIO
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadState s m =&gt;
    MonadState s <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> m m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
        get = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:liftRan"><span style="font-weight: bold;">liftRan</span></a> get
        put = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:liftRan"><span style="font-weight: bold;">liftRan</span></a> . put
&nbsp;</pre>
<p>In fact the list of things you can lift is pretty much the same as what you can lift over the <code>ContT</code> monad transformer due to the similarity in the types. However, just because you lifted the operation into the right or left Kan extension, doesn't mean that it has the same asymptotic performance.</p>
<p>Similarly we can lift many comonadic operations to the <code>Density</code> comonad of a comonad using <code>Lan</code>.</p>
<p>[Edit: Refactored out into <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad-Density.html">Control.Comonad.Density</a>]</p>
<p><b>Changing Representation</b></p>
<p>Given a <code>f -| g</code>, <code>g `O` f</code> is a monad, and <code>Ran (g `O` f) (g `O` f)</code> is the monad generated by <code>(g `O` f)</code>, described in the previous post. We showed above that this monad can do many of the same things that the original monad could do. From there you can <code>decomposeRan</code> to get <code>Ran g (Ran f (g `O` f))</code>, which you can show to be yet another monad, and you can continue on from there. </p>
<p>Each of these monads may have different operational characteristics and performance tradeoffs. For instance the codensity monad of a monad can offer <a href="http://wwwtcs.inf.tu-dresden.de/~voigt/mpc08.pdf">better asymptotic performance</a> in some usage scenarios.</p>
<p>Similarly the left Kan extension can be used to manipulate the representation of a comonad.</p>
<p>All of this code is encapsulated in <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/category-extras">category-extras</a> [<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/">docs</a>] [<a href="http://comonad.com/haskell/category-extras">darcs</a>] as of release 0.51.0</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2008/kan-extensions-ii/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

