<?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; Mathematics</title>
	<atom:link href="http://comonad.com/reader/category/mathematics/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>Free Modules and Functional Linear Functionals</title>
		<link>http://comonad.com/reader/2011/free-modules-and-functional-linear-functionals/</link>
		<comments>http://comonad.com/reader/2011/free-modules-and-functional-linear-functionals/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 20:58:04 +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[Linear Algebra]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Monoids]]></category>
		<category><![CDATA[Type Hackery]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=356</guid>
		<description><![CDATA[Today I hope to start a new series of posts exploring constructive abstract algebra in Haskell.  
In particular, I want to talk about a novel encoding of linear functionals, polynomials and linear maps in Haskell, but first we're going to have to build up some common terminology.
Having obtained the blessing of Wolfgang Jeltsch, I [...]]]></description>
			<content:encoded><![CDATA[<p>Today I hope to start a new series of posts exploring constructive abstract algebra in Haskell.  </p>
<p>In particular, I want to talk about a novel encoding of linear functionals, polynomials and linear maps in Haskell, but first we're going to have to build up some common terminology.</p>
<p>Having obtained the blessing of Wolfgang Jeltsch, I replaced the <a href="http://hackage.haskell.org/package/algebra">algebra</a> package on hackage with something... bigger, although still very much a work in progress.</p>
<p><span id="more-356"></span></p>
<p><strong>(Infinite) Modules over Semirings</strong></p>
<p>Recall that a vector space <strong>V</strong> over a field <strong>F</strong> is given by an additive Abelian group on <strong>V</strong>, and a scalar multiplication operator<br />
   <code>(.*) :: F -> V -> V</code> subject to distributivity laws</p>
<pre class="haskell">&nbsp;
s .* <span style="color: green;">&#40;</span>u + v<span style="color: green;">&#41;</span> = s .* u + s .* v
<span style="color: green;">&#40;</span>s + t<span style="color: green;">&#41;</span> .* v = s .* v + t .* v
&nbsp;</pre>
<p>and associativity laws</p>
<pre class="haskell">&nbsp;
   <span style="color: green;">&#40;</span>s * t<span style="color: green;">&#41;</span> .* v = s .* <span style="color: green;">&#40;</span>t .* v<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and respect of the unit of the field.</p>
<pre class="haskell">&nbsp;
   <span style="color: red;">1</span> .* v = v
&nbsp;</pre>
<p>Since multiplication on a field is commutative, we can also add</p>
<pre class="haskell">&nbsp;
  <span style="color: green;">&#40;</span>*.<span style="color: green;">&#41;</span> :: V -&gt; F -&gt; V
  v *. f = f .* v
&nbsp;</pre>
<p>with analogous rules.</p>
<p>But when F is only a <a href="http://en.wikipedia.org/wiki/Ring_(mathematics)">Ring</a>, we call the analogous structure a module, and in a ring, we can't rely on the commutativity of multiplication, so we may have to deal left-modules and right-modules, where only one of those products is available.</p>
<p>We can weaken the structure still further. If we lose the negation in our Ring we and go to a <a href="http://en.wikipedia.org/wiki/Semiring">Rig</a> (often called a Semiring), now our module is an additive moniod.</p>
<p>If we get rid of the additive and multiplicative unit on our Rig we get down to what some authors call a Ringoid, but which we'll call a <a href="http://hackage.haskell.org/packages/archive/algebra/0.3.0/doc/html/Numeric-Semiring-Class.html">Semiring</a> here, because it makes the connection between semiring and semigroup clearer, and the <em>-oid</em> suffix is dangerously overloaded due to category theory.</p>
<p>First we'll define additive semigroups, because I'm going to need both additive and multiplicative monoids over the same types, and Data.Monoid has simultaneously too much and too little structure.</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- (a + b) + c = a + (b + c)</span>
<span style="color: #06c; font-weight: bold;">class</span> Additive m <span style="color: #06c; font-weight: bold;">where</span>
  <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> :: m -&gt; m -&gt; m
  replicate1p :: Whole n =&gt; n -&gt; m -&gt; m <span style="color: #5d478b; font-style: italic;">-- (ignore this for now)</span>
  <span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;</pre>
<p>their Abelian cousins</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- a + b = b + a</span>
<span style="color: #06c; font-weight: bold;">class</span> Additive m =&gt; Abelian m
&nbsp;</pre>
<p>and Multiplicative semigroups</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- (a * b) * c = a * (b * c)</span>
<span style="color: #06c; font-weight: bold;">class</span> Multiplicative m <span style="color: #06c; font-weight: bold;">where</span>
  <span style="color: green;">&#40;</span>*<span style="color: green;">&#41;</span> :: m -&gt; m -&gt; m
  pow1p :: Whole n =&gt; m -&gt; n -&gt; m
  <span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;</pre>
<p>Then we can define a semirings</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- a*(b + c) = a*b + a*c</span>
<span style="color: #5d478b; font-style: italic;">-- (a + b)*c = a*c + b*c</span>
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span>Additive m, Abelian m, Multiplicative m<span style="color: green;">&#41;</span> =&gt; Semiring
&nbsp;</pre>
<p>With that we can define modules over a semiring:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- r .* (x + y) = r .* x + r .* y</span>
<span style="color: #5d478b; font-style: italic;">-- (r + s) .* x = r .* x + s .* x</span>
<span style="color: #5d478b; font-style: italic;">-- (r * s) .* x = r .* (s .* x)</span>
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span>Semiring r, Additive m<span style="color: green;">&#41;</span> =&gt; LeftModule r m
   <span style="color: green;">&#40;</span>.*<span style="color: green;">&#41;</span> :: r -&gt; m -&gt; m
&nbsp;</pre>
<p>and analogously:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span>Semiring r, Additive m<span style="color: green;">&#41;</span> =&gt; RightModule r m
   <span style="color: green;">&#40;</span>*.<span style="color: green;">&#41;</span> :: m -&gt; r -&gt; m
&nbsp;</pre>
<p>For instance every additive semigroup forms a semiring module over the positive natural numbers (1,2..) using replicate1p.</p>
<p>If we know that our addition forms a monoid, then we can form a module over the naturals as well</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- | zero + a = a = a + zero</span>
<span style="color: #06c; font-weight: bold;">class</span>
    <span style="color: green;">&#40;</span>LeftModule Natural m,
    RightModule Natural m
    <span style="color: green;">&#41;</span> =&gt; AdditiveMonoid m <span style="color: #06c; font-weight: bold;">where</span>
   zero :: m
   replicate :: Whole n =&gt; n -&gt; m -&gt; m
&nbsp;</pre>
<p>and if our addition forms a group, then we can form a module over the integers</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- | a + negate a = zero = negate a + a</span>
<span style="color: #06c; font-weight: bold;">class</span>
    <span style="color: green;">&#40;</span>LeftModule <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> m
    , RightModule <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> m
    <span style="color: green;">&#41;</span> =&gt; AdditiveGroup m <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:negate"><span style="font-weight: bold;">negate</span></a> :: m -&gt; m
  times :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integral"><span style="background-color: #efefbf; font-weight: bold;">Integral</span></a> n =&gt; n -&gt; m -&gt; m
  <span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;</pre>
<p><strong>Free Modules over Semirings</strong></p>
<p>A free module on a set E, is a module where the basis vectors are elements of E. Basically it is |E| copies of some (semi)ring.</p>
<p>In Haskell we can represent the free module of a ring directly by defining the action of the (semi)group pointwise.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Additive m =&gt; Additive <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   f + g = \x -&gt; f x + g x
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Abelian m =&gt; Abelian <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> AdditiveMonoid m =&gt; AdditiveMonoid <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   zero = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> zero
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> AdditiveGroup m =&gt; AdditveGroup <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   f - g = \x -&gt; f x - g x
&nbsp;</pre>
<p>We could define the following</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Semiring r =&gt; LeftModule r <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   r .* f = \x -&gt; r * f x
&nbsp;</pre>
<p>but then we'd have trouble dealing with the Natural and Integer constraints above, so instead we lift modules</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> LeftModule r m =&gt; LeftModule r <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <span style="color: green;">&#40;</span>.*<span style="color: green;">&#41;</span> m f e = m .* f e
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> RightModule r m =&gt; RightModule r <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
   <span style="color: green;">&#40;</span>*.<span style="color: green;">&#41;</span> f m e = f e *. m
&nbsp;</pre>
<p>We <strong>could</strong> go one step further and define multiplication pointwise, but while the direct product of |e| copies of a ring _does_ define a ring, and this ring is the one provided by the Conal Elliot's <a href="http://code.haskell.org/vector-space/"><code>vector-space</code></a> package, it isn't the most general ring we could construct. But we'll need to take a detour first.</p>
<p><strong>Linear Functionals</strong></p>
<p>A Linear functional f on a module M is a linear function from a M to its scalars R.</p>
<p>That is to say that, f : M -> R such that</p>
<pre class="haskell">&nbsp;
f <span style="color: green;">&#40;</span>a .* x + y<span style="color: green;">&#41;</span> = a * f x + f y
&nbsp;</pre>
<p>Consequently linear functionals also form a module over R. We call this module the dual module M*.</p>
<p>Dan Piponi has blogged about these dual vectors (or covectors) in the context of trace diagrams.</p>
<p>If we limit our discussion to free modules, then M = E -> R, so a linear functional on M looks like <code>(E -> R) -> R</code><br />
<em>subject to additional linearity constraints</em> on the result arrow. </p>
<p>The main thing we're not allowed to do in our function is apply our function from E -> R to two different E's and then multiply the results together. Our pointwise definitions above satisfy those linearity constraints, but for example:</p>
<pre class="haskell">&nbsp;
bad f = f <span style="color: red;">0</span> * f <span style="color: red;">0</span>
&nbsp;</pre>
<p>does not.</p>
<p>We <em>could</em> capture this invariant in the type by saying that instead we want</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> LinearM r e =
  LinearM <span style="color: green;">&#123;</span>
    runLinearM :: <span style="color: #06c; font-weight: bold;">forall</span> r. LeftModule r m =&gt; <span style="color: green;">&#40;</span>e -&gt; m<span style="color: green;">&#41;</span> -&gt; m
  <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>we'd have to make a new such type every time we subclassed Semiring. I'll leave further exploration of this more exotic type to another time. (Using some technically illegal module instances we can recover more structure that you'd expect.)</p>
<p>Now we can package up the type of covectors/linear functionals:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixr</span> <span style="color: red;">0</span> $*
<span style="color: #06c; font-weight: bold;">newtype</span> Linear r a = Linear <span style="color: green;">&#123;</span> <span style="color: green;">&#40;</span>$*<span style="color: green;">&#41;</span> :: <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>The sufficiently observant may have already noticed that this type is the same as the Cont monad (subject to the linearity restriction on the result arrow).</p>
<p>In fact the <code>Functor</code>, <code>Monad</code>, <code>Applicative</code> instances for <code>Cont</code> all carry over, and <strong>preserve linearity</strong>. </p>
<p>(We lose <code>callCC</code>, but that is at least partially due to the fact that <code>callCC</code> has a less than ideal type signature.)</p>
<p>In addition we get a number of additional instances for <code>Alternative</code>, <code>MonadPlus</code>, by exploiting the knowledge that r is ring-like:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> AdditiveMonoid r =&gt; Alternative <span style="color: green;">&#40;</span>Linear r a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  Linear f &lt; |&gt; Linear g = Linear <span style="color: green;">&#40;</span>f + g<span style="color: green;">&#41;</span>
  empty = Linear zero
&nbsp;</pre>
<p>Note that the <code>(+)</code> and <code>zero</code> there are the ones defined on functions from our earlier free module construction!</p>
<p><strong>Linear Maps</strong></p>
<p>Since <code>Linear r</code> is a monad, <code>Kleisli (Linear r)</code> forms an <code>Arrow</code>:</p>
<pre class="haskell">&nbsp;
b -&gt; <span style="color: green;">&#40;</span><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>where the ~> denotes the arrow that is constrained to be linear.</p>
<p>If we swap the order of the arguments so that</p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> ~&gt; <span style="color: green;">&#40;</span>b -&gt; r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>this arrow has a very nice meaning! (See <a href="http://hackage.haskell.org/packages/archive/algebra/0.4.0/doc/html/Numeric-Map-Linear.html">Numeric.Map.Linear</a>)</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixr</span> <span style="color: red;">0</span> $#
<span style="color: #06c; font-weight: bold;">newtype</span> Map r b a = Map <span style="color: green;">&#123;</span> <span style="color: green;">&#40;</span>$#<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>b -&gt; r<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p><code>Map r b a</code> represents the type of <a href="http://en.wikipedia.org/wiki/Linear_map">linear maps</a> from <code>a -> b</code>. Unfortunately due to contravariance the arguments wind up in the "wrong" order.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Category <span style="color: green;">&#40;</span>Map r<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  Map f . Map g = Map <span style="color: green;">&#40;</span>g . f<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> = Map <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>So we can see that a linear map from a module A with basis <code>a</code> to a vector space with basis <code>b</code> effectively consists of |b| linear functionals on A.</p>
<p><code>Map r b a</code> provides a lot of structure. It is a valid instance of <a href="https://github.com/ekmett/algebra/blob/master/Numeric/Map/Linear.hs">an insanely large number of classes</a>.</p>
<p><strong>Vectors and Covectors</strong></p>
<p>In physics, we sometimes call linear functionals <a href="http://www.euclideanspace.com/maths/algebra/vectors/related/covector/index.htm">covectors</a> or covariant vectors, and if we're feeling particularly loquacious, we'll refer to vectors as contravariant vectors.</p>
<p>This has to do with the fact that when you change basis, you change map the change over covariant vectors covariantly, and map the change over vectors contravariantly. (This distinction is beautifully captured by <a href="http://en.wikipedia.org/wiki/Einstein_notation">Einstein's summation notation</a>.)</p>
<p>We also have a notion of <a href="http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)">covariance and contravariance in computer science</a>! </p>
<p>Functions vary covariantly in their result, and contravariant in their argument. <code>E -> R</code> is contravariant in E. But we chose this representation for our free modules, so the vectors in our free vector space (or module) are contravariant in E.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Contravariant f <span style="color: #06c; font-weight: bold;">where</span>
  contramap :: <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt; f a -&gt; f b
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- | Dual function arrows.</span>
<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>On the other hand <code>(E -> R) ~> R</code> varies covariantly with the change of <code>E</code>.</p>
<p>as witnessed by the fact that it is 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>Linear r<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 = Linear $ \k -&gt; m $* k . f
&nbsp;</pre>
<p>We have lots of classes for manipulating covariant structures, and most of them apply to both (Linear r) and (Map r b).</p>
<p><strong>Other Representations and Design Trade-offs</strong></p>
<p>One common representation of vectors in a free vector space is as some kind of normalized list of scalars and basis vectors. In particular, David Amos's wonderful <a href="http://www.polyomino.f2s.com/david/haskell/main.html">HaskellForMaths</a> uses</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Vect r a = Vect <span style="color: green;">&#123;</span> runVect :: <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span>r,a<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span> <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>for free vector spaces, only considering them up to linearity, paying for normalization as it goes.</p>
<p>Given the insight above we can see that Vect isn't a representation of vectors in the free vector space, but instead represents the covectors of that space, quite simply because Vect r a varies covariantly with change of basis!</p>
<p>Now the price of using the <code>Monad</code> on <code>Vect r</code> is that the monad denormalizes the representation. In particular, you can have multiple copies of the same basis vector., so any function that uses <code>Vect r a</code> has to merge them together.</p>
<p>On the other hand with the directly encoded linear functionals we've described here, we've placed no obligations on the consumer of a linear functional. They can feed the directly encoded linear functional <strong>any vector</strong> they want! </p>
<p>In fact, it'll even be quite a bit more efficient to compute, </p>
<p>To see this, just consider:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MultiplicativeMonoid r =&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>Vect r<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 = Vect <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: red;">1</span>,a<span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
   Vect <span style="color: #06c; font-weight: bold;">as</span> &gt;&gt;= f = Vect
       <span style="color: green;">&#91;</span> <span style="color: green;">&#40;</span>p*q, b<span style="color: green;">&#41;</span> | <span style="color: green;">&#40;</span>p,a<span style="color: green;">&#41;</span> &lt; - <span style="color: #06c; font-weight: bold;">as</span>, <span style="color: green;">&#40;</span>q,b<span style="color: green;">&#41;</span> &lt;- runVect <span style="color: green;">&#40;</span>f b<span style="color: green;">&#41;</span> <span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>Every >>= must pay for multiplication. Every return will multiply the element by one. On the other hand, the price of return and bind in Linear r is function application.</p>
</pre>
<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>Linear r<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 = Linear $ \k -&gt; k a
  m &gt;&gt;= f = Linear $ \k -&gt; m $* \a -&gt; f a $* k
&nbsp;</pre>
<p><strong>A Digression on Free Linear Functionals</strong></p>
<p>To wax categorical for a moment, we can construct a forgetful functor <code>U : Vect_F -> Set</code> that takes a vector space over F to just its set of covectors.</p>
<pre lang="haskell>
U (V,F,+,.*) = V ~> F
</pre>
<p>Then we can construct <code>F : Set -> Vect_F</code> which takes a set E and gives the vector space</p>
<pre class="haskell">&nbsp;
F E = <span style="color: green;">&#40;</span>E -&gt; F, F,\f g x -&gt; f x + g x ,\r f x -&gt; r * f x<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>using the pointwise constructions we built earlier.</p>
<p>Then in a classical setting, you can show that F is left adjoint to U.</p>
<p>In particular the witnesses of this adjunction provide the linear map from (E -> F) to V and the function E -> (V ~> F) giving a linear functional on V for each element of E.</p>
<p>In a classical setting you can go a lot farther, and show that all vector spaces (but not all modules) are free.</p>
<p>But in a constructive setting, such as Haskell, we need a fair bit to go back and forth, in particular we wind up need E to be finitely enumerable to go one way, and for it to have decidable equality to go in the other. The latter is fairly easy to see, because even going from <code>E -> (E -> F)</code> requires that we can define and partially apply something like <a href="http://en.wikipedia.org/wiki/Kronecker_delta">Kronecker's delta</a>:</p>
<pre class="haskell">&nbsp;
delta :: <span style="color: green;">&#40;</span>Rig r, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Eq"><span style="background-color: #efefbf; font-weight: bold;">Eq</span></a> a<span style="color: green;">&#41;</span> =&gt; e -&gt; e -&gt; r
delta i j | i == j = one
             | <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:otherwise"><span style="font-weight: bold;">otherwise</span></a> = zero
&nbsp;</pre>
<p><strong>The Price of Power</strong></p>
<p>The price we pay is that, given a <code>Rig</code>, we can go from <code>Vect r a</code> to <code>Linear r a</code> but going back requires <code>a</code> to be be finitely enumerable (or for our functional to satisfy other exotic side-conditions).  </p>
<pre class="haskell">&nbsp;
vectMap :: Rig r =&gt; Vect r a -&gt; Linear r a
vectMap <span style="color: green;">&#40;</span>Vect <span style="color: #06c; font-weight: bold;">as</span><span style="color: green;">&#41;</span> = Map $ \k -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:sum"><span style="font-weight: bold;">sum</span></a> <span style="color: green;">&#91;</span> r * k a | <span style="color: green;">&#40;</span>r, a<span style="color: green;">&#41;</span> &lt; - <span style="color: #06c; font-weight: bold;">as</span> <span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>You can still probe <code>Linear r a</code> for individual coefficients, or pass it a vector for polynomial evaluation very easily, but for instance determining a degree of a polynomial efficiently requires attaching more structure to your semiring, because the only value you can get out of <code>Linear r a</code> is an <code>r</code>.</p>
<p><strong>Optimizing Linear Functionals</strong></p>
<p>In both the <code>Vect r</code> and <code>Linear r</code> cases, excessive use of <code>(>>=)</code> without somehow normalizing or tabulating your data will cause a <strong>lot</strong> of repeated work. </p>
<p>This is perhaps easiest to see from the fact that <code>Vect r</code> never used the addition of <code>r</code>, so it distributed everything into a kind of disjunctive normal form. <code>Linear r</code> does the same thing.</p>
<p>If you look at the Kleisli arrows of <code>Vect r</code> or <code>Linear r</code> as linear mappings, then you can see that Kleisli composition is going to explode the number of terms. </p>
<p>So how can we collapse back down?</p>
<p>In the <code>Kleisli (Vect r)</code> case we usually build up a map as we walk through the list then spit the list back out in order having added up like terms.</p>
<p>In the <code>Map r</code> case, we can do better. My <a href="http://hackage.haskell.org/package/representable-tries"><code>representable-tries</code></a> package provides a readily instantiable <code>HasTrie</code> class, and the method:</p>
</pre>
<pre class="haskell">&nbsp;
memo :: HasTrie a =&gt; <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; a -&gt; r
&nbsp;</pre>
<p>which is responsible for providing a memoized version of the function from <code>a -> r</code> in a purely functional way. This is obviously a linear map!</p>
<pre class="haskell">&nbsp;
memoMap :: HasTrie a =&gt; Map r a a
memoMap = Map memo
&nbsp;</pre>
<p>We can also flip memo around and memoize linear functionals.</p>
<pre class="haskell">&nbsp;
memoLinear :: HasTrie a =&gt; a -&gt; Linear r a
memoLinear = Linear . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> memo
&nbsp;</pre>
<p>Next time, (co)associative (co)algebras and the myriad means of multiplying (co)vectors!</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/free-modules-and-functional-linear-functionals/feed/</wfw:commentRss>
		<slash:comments>9</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 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>Reverse-Mode Automatic Differentiation in Haskell</title>
		<link>http://comonad.com/reader/2010/reverse-mode-automatic-differentiation-in-haskell/</link>
		<comments>http://comonad.com/reader/2010/reverse-mode-automatic-differentiation-in-haskell/#comments</comments>
		<pubDate>Sun, 16 May 2010 04:27:12 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Mathematics]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=183</guid>
		<description><![CDATA[I've uploaded a package named rad to Hackage for handling reverse-mode automatic differentiation in Haskell.

Internally, it leverages a trick from Andy Gill's Kansas Lava to observe sharing in the tape it records for back propagation purposes, and uses type level branding to avoid confusing sensitivities.
I've tried to keep the API relatively close to that of [...]]]></description>
			<content:encoded><![CDATA[<p>I've uploaded a package named <a href="http://hackage.haskell.org/package/rad">rad</a> to Hackage for handling reverse-mode <a href="http://en.wikipedia.org/wiki/Automatic_differentiation">automatic differentiation</a> in Haskell.<br />
<span id="more-183"></span></p>
<p>Internally, it leverages a <a href="http://www.ittc.ku.edu/~andygill/papers/reifyGraph.pdf">trick</a> from Andy Gill's Kansas Lava to observe sharing in the tape it records for back propagation purposes, and uses type level branding to avoid confusing sensitivities.</p>
<p>I've tried to keep the API relatively close to that of Barak Pearlmutter and Jeffrey Mark Siskind's <a href="http://hackage.haskell.org/package/fad">fad</a> package, but I couldn't resist making a couple of minor tweaks here and there for generality.</p>
<p>I still need to go through and finish up the remaining unimplemented fad combinators, figure out a nice way to build a reverse-mode AD tower, validate that I didn't screw up my recollection of basic calculus, and provide a nice API for using this approach to get local reverse mode checkpoints in an otherwise forward mode AD program, but I am quite happy with how things have progressed thus far.</p>
<p>[Edit: I've uploaded minor bug fixes for exp and (**)]</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2010/reverse-mode-automatic-differentiation-in-haskell/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Remodeling Precision</title>
		<link>http://comonad.com/reader/2009/remodeling-precision/</link>
		<comments>http://comonad.com/reader/2009/remodeling-precision/#comments</comments>
		<pubDate>Tue, 15 Sep 2009 18:56:05 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Mathematics]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=151</guid>
		<description><![CDATA[Two concepts come up when talking about information retrieval in most standard documentation, Precision and Recall. Precision is a measure that tells you if your result set contains only results that are relevant to the query, and recall tells you if your result set contains everything that is relevant to the query.
The formula for classical [...]]]></description>
			<content:encoded><![CDATA[<p>Two concepts come up when talking about information retrieval in most standard documentation, <a href="http://en.wikipedia.org/wiki/Precision_and_recall">Precision and Recall</a>. Precision is a measure that tells you if your result set contains only results that are relevant to the query, and recall tells you if your result set contains everything that is relevant to the query.</p>
<p>The formula for classical precision is:</p>
<p><img src="http://comonad.com/reader/wp-content/uploads/2009/09/precision_formula.png" alt="Precision Formula" title="Precision Formula" width="514" height="47" class="alignnone size-full wp-image-158" /></p>
<p>However, I would argue that the classical notion of Precision is flawed, in that it doesn't model anything we tend to care about. Rarely are we interested in binary classification, instead we want a ranked classification of relevance.</p>
<p><span id="more-151"></span></p>
<p>When Google tells you that you have a million results, do you care? No, you skim the first few entries for what it is that you are looking for, unless you are particularly desperate for an answer. So really, you want a metric that models the actual behavior of a search engine user and that level of desperation.</p>
<p>There are two issues with classical precision: </p>
<ol>
<li>the denominator of precision goes to infinity as the result set increases in size</li>
<li> each result is worth the same amount no matter where it appears in the list</li>
</ol>
<p>The former ensures that a million answers drowns out any value from the first screen, the latter ensures that it doesn't matter which results are on the first screen. A more accurate notion of precision suitable for modern search interfaces should model the prioritization of the results, and should allow for a long tail of crap if the stuff that people will look at is accurate over all.</p>
<p>So how to model user behavior? We can replace the denominator with a partial sum of a geometric series for probability <em>p</em> &lt; 1, where <em>p</em> models the percentage chance that a user will continue to browse to the next item in the list. Then you can scale the value of the nth summand in the numerator as being worth up to <em>p</em><sup><em>n</em></sup>. If you have a ranked training set it is pretty easy to score precision in this fashion.</p>
<p>You retain all of the desirable properties of precision. It maxes out at 100%, it decreases when you give irrelevant results, but now it effectively models when you return irrelevant results early in your result list. </p>
<p>The result more accurately models user behavior when faced with a search engine than the classical binary precision metric. The parameter <em>p</em> models the desperation of the user and can vary to fit your problem domain. I personally like p=50%, because it makes for nice numbers, but it should proabably be chosen based on sampling based on knowledge of the search domain.</p>
<p>You can of course embellish this model with a stair-step in the cost function on each page boundary, etc. &#8212; any monotone decreasing infinite series that sums to a finite number in the limit should do.</p>
<p>A similar modification can of course be applied to recall.</p>
<p>I used this approach a couple of years ago to help tune a search engine to good effect. I went to refer someone to this post today and I realized I hadn't posted it in the almost two years since it was written, so here it is, warts and all.</p>
<p>If anyone is familiar with similar approaches in the literature, I'd be grateful for references!</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2009/remodeling-precision/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Iteratees, Parsec and Monoids (Slides)</title>
		<link>http://comonad.com/reader/2009/iteratees-parsec-and-monoid/</link>
		<comments>http://comonad.com/reader/2009/iteratees-parsec-and-monoid/#comments</comments>
		<pubDate>Thu, 20 Aug 2009 16:55:03 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monoids]]></category>
		<category><![CDATA[Parsing]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=122</guid>
		<description><![CDATA[Two talks from the Boston Area Haskell User Group:
<ol>	
       <li><a href='http://comonad.com/reader/wp-content/uploads/2009/08/IntroductionToMonoids.pdf'>Introduction To Monoids (PDF)</a></li>
	<li><a href='http://comonad.com/reader/wp-content/uploads/2009/08/A-Parsing-Trifecta.pdf'>Iteratees, Parsec and Monoids: A Parsing Trifecta (PDF)</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I was asked to give two talks at the <a href="http://groups.google.com/group/bostonhaskell">Boston Area Haskell User Group</a> for this past Tuesday. The first was pitched at a more introductory level and the second was to go deeper into what I have been using monoids for lately.</p>
<p>The first talk covers an introduction to the mathematical notion of a monoid, introduces some of the features of my Haskell monoids library on hackage, and starts to motivate the use of monoidal parallel/incremental parsing, and the modification use of compression algorithms to recycle monoidal results.</p>
<p>The second talk covers a way to generate a locally-context sensitive parallel/incremental parser by modifying <a href="http://okmij.org/ftp/Haskell/Iteratee/Iteratee.hs">Iteratees</a> to enable them to drive a <a href="http://hackage.haskell.org/package/parsec-3.0.0">Parsec 3</a> lexer, and then wrapping that in a monoid based on <a href="http://dragonbook.stanford.edu/lecture-notes/Columbia-COMS-W4115/08-03-05.html">error productions</a> in the grammar before recycling these techniques at a higher level to deal with parsing seemingly stateful structures, such as Haskell layout.</p>
<ol>
<li><a href='http://comonad.com/reader/wp-content/uploads/2009/08/IntroductionToMonoids.pdf'>Introduction To Monoids (PDF)</a></li>
<li><a href='http://comonad.com/reader/wp-content/uploads/2009/08/A-Parsing-Trifecta.pdf'>Iteratees, Parsec and Monoids: A Parsing Trifecta (PDF)</a></li>
</ol>
<p>Due to a late start, I was unable to give the second talk. However, I did give a quick run through to a few die-hards who stayed late and came to the <a href="http://www.cambrew.com/">Cambridge Brewing Company</a> afterwards. As I promised some people that I would post the slides after the talk, here they are. </p>
<p>The current plan is to possibly give the second talk in full at either the September or October Boston Haskell User Group sessions, depending on scheduling and availability.</p>
<p>[ <a href='http://comonad.com/reader/wp-content/uploads/2009/08/Iteratee.hs'>Iteratee.hs</a> ]</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2009/iteratees-parsec-and-monoid/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Slides from Hac Phi: &#8220;All About Monoids&#8221;</title>
		<link>http://comonad.com/reader/2009/hac-phi-slides/</link>
		<comments>http://comonad.com/reader/2009/hac-phi-slides/#comments</comments>
		<pubDate>Fri, 31 Jul 2009 15:41:16 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monoids]]></category>
		<category><![CDATA[Parsing]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=85</guid>
		<description><![CDATA[Some people have requested my slides from the short talk I gave about monoids and monoidal parsing at Hac Phi. So, here they are.

Hac Phi Slides (Powerpoint 2007)
Hac Phi Slides (PDF)

There will be more to come at the next Boston Haskell User Group in August, where it looks like I'll be giving two short talks [...]]]></description>
			<content:encoded><![CDATA[<p>Some people have requested my slides from the short talk I gave about monoids and monoidal parsing at Hac Phi. So, here they are.</p>
<ul>
<li><a href='http://comonad.com/reader/wp-content/uploads/2009/07/AllAboutMonoids.pptx'>Hac Phi Slides (Powerpoint 2007)</a></li>
<li><a href='http://comonad.com/reader/wp-content/uploads/2009/07/AllAboutMonoids.pdf'>Hac Phi Slides (PDF)</a></li>
</ul>
<p>There will be more to come at the next Boston Haskell User Group in August, where it looks like I'll be giving two short talks covering monoids. I may use the monoidal parsing engine from Kata as an example for the advanced talk if I have time and will start to cover parsing larger classes of grammars in general (regular languages, CFGs/TIGs, TAGs, PEGs, LALR, attribute-grammars, etc.)</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2009/hac-phi-slides/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Recursion Schemes: A Field Guide (Redux)</title>
		<link>http://comonad.com/reader/2009/recursion-schemes/</link>
		<comments>http://comonad.com/reader/2009/recursion-schemes/#comments</comments>
		<pubDate>Thu, 11 Jun 2009 16:22:48 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Mathematics]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/2009/recursion-schemes/</guid>
		<description><![CDATA[About a year back I posted a field guide of recursion schemes on this blog and then lost it a few months later when I lost a couple of months of blog entries to a crash. I recently recovered the table of recursion schemes from the original post thanks to Google Reader's long memory and [...]]]></description>
			<content:encoded><![CDATA[<p>About a year back I posted a field guide of recursion schemes on this blog and then lost it a few months later when I lost a couple of months of blog entries to a <a href="http://comonad.com/reader/2008/still-alive/">crash</a>. I recently recovered the table of recursion schemes from the original post thanks to <a href="http://www.google.com/reader/">Google Reader</a>'s long memory and the help of Jeff Cutsinger.</p>
<p>The following recursion schemes can be found in <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/category-extras">category-extras</a>, along with variations on the underlying themes, so this should work as a punch-list.</p>
<table border=1>
<tr>
<th colspan=3>Folds</th>
</tr>
<tr>
<th>Scheme</th>
<th>Code</th>
<th>Description</th>
</tr>
<tr>
<td><a href="http://knol.google.com/k/edward-kmett/catamorphisms/">catamorphism</a>†</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Cata.hs">Cata</a></td>
<td>tears down a structure level by level</td>
</tr>
<tr>
<td>paramorphism*†</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Para.hs">Para</a></td>
<td>tears down a structure with primitive recursion</td>
</tr>
<tr>
<td>zygomorphism*†</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Zygo.hs">Zygo</a></td>
<td>tears down a structure with the aid of a helper function</td>
</tr>
<tr>
<td>histomorphism†</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Histo.hs">Histo</a></td>
<td>tears down a structure with the aid of the previous answers it has given.  </td>
</tr>
<tr>
<td>prepromorphism*†</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Prepro.hs">Prepro</a>
  </td>
<td>tears down a structure after repeatedly applying a natural transformation</td>
</tr>
<tr>
<th colspan=3>Unfolds</th>
</tr>
<tr>
<th>Scheme</th>
<th>Code</th>
<th>Description</th>
</tr>
<tr>
<td>anamorphism†</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Ana.hs">Ana</a></td>
<td>builds up a structure level by level</td>
</tr>
<tr>
<td>apomorphism*†</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Apo.hs">Apo</a></td>
<td>builds up a structure opting to return a single level or an entire branch at each point</td>
</tr>
<tr>
<td>futumorphism†</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Futu.hs">Futu</a></td>
<td>builds up a structure multiple levels at a time </td>
</tr>
<tr>
<td>postpromorphism*†</td>
<td>
  <a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Postpro.hs">Postpro</a>
  </td>
<td>builds up a structure and repeatedly transforms it with a natural transformation</td>
</tr>
<tr>
<th colspan=3>Refolds</th>
</tr>
<tr>
<th>Scheme</th>
<th>Code</th>
<th>Description</th>
</tr>
<tr>
<td>hylomorphism†</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Hylo.hs">Hylo</a></td>
<td>builds up and tears down a virtual structure</td>
</tr>
<tr>
<td>chronomorphism†</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Chrono.hs">Chrono</a></td>
<td>builds up a virtual structure with a futumorphism and tears it down<br />
  with a histomorphism</td>
</tr>
<tr>
<td>synchromorphism</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Synchro.hs">Synchro</a></td>
<td>a high level transformation between data structures using a third data structure to queue intermediate results</td>
</tr>
<tr>
<td>exomorphism</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Exo.hs">Exo</a></td>
<td>a high level transformation between data structures from a trialgebra to a bialgebraga</td>
</tr>
<tr>
<td>metamorphism</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Meta/Erwig.hs">Erwig</a></td>
<td>a hylomorphism expressed in terms of bialgebras</td>
</tr>
<tr>
<td>metamorphism</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Meta/Gibbons.hs">Gibbons</a></td>
<td>A fold followed by an unfold; change of representation</td>
</tr>
<tr>
<td>dynamorphism†</td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Morphism/Dyna.hs">Dyna</a></td>
<td>builds up a virtual structure with an anamorphism and tears it down with a histomorphism</td>
</tr>
<tr>
<td><a href="http://arxiv.org/abs/cs/0609040">Elgot algebra</a></td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Functor/Algebra/Elgot.hs">Elgot</a></td>
<td>builds up a structure and tears it down but may shortcircuit the process during construction</td>
</tr>
<tr>
<td><a href="http://comonad.com/reader/2008/elgot-coalgebras/">Elgot coalgebra</a></td>
<td><a href="http://comonad.com/haskell/category-extras/src/Control/Functor/Algebra/Elgot.hs">Elgot</a></td>
<td>builds up a structure and tears it down but may shortcircuit the process during deconstruction</td>
</tr>
</table>
<p>* This gives rise to a family of related recursion schemes, modeled in category-extras with distributive law combinators<br />
† The scheme can be generalized to accept one or more F-distributive (co)monads.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2009/recursion-schemes/feed/</wfw:commentRss>
		<slash:comments>10</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>
	</channel>
</rss>

