<?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>Thu, 22 Jul 2010 19:53:03 +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>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>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>8</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>9</slash:comments>
		</item>
		<item>
		<title>Kan Extensions</title>
		<link>http://comonad.com/reader/2008/kan-extensions/</link>
		<comments>http://comonad.com/reader/2008/kan-extensions/#comments</comments>
		<pubDate>Wed, 21 May 2008 01:39:54 +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/2008/kan-extensions/</guid>
		<description><![CDATA[I think I may spend a post or two talking about Kan extensions.
They appear to be black magic to Haskell programmers, but as Saunders Mac Lane said in Categories for the Working Mathematician:
All concepts are Kan extensions.
So what is a Kan extension? They come in two forms: right- and left- Kan extensions. 
First I'll talk [...]]]></description>
			<content:encoded><![CDATA[<p>I think I may spend a post or two talking about <a href="http://en.wikipedia.org/wiki/Kan_extension">Kan extensions</a>.</p>
<p>They appear to be black magic to Haskell programmers, but as <a href="http://en.wikipedia.org/wiki/Saunders_Mac_Lane">Saunders Mac Lane</a> said in <a href="http://www.amazon.com/Categories-Working-Mathematician-Graduate-Mathematics/dp/0387984038">Categories for the Working Mathematician</a>:</p>
<blockquote><p>All concepts are Kan extensions.</p></blockquote>
<p>So what is a Kan extension? They come in two forms: right- and left- Kan extensions. </p>
<p>First I'll talk about right Kan extensions, since Haskell programmers have a better intuition for them.</p>
<p><span id="more-63"></span></p>
<p><b>Introducing Right Kan Extension</b></p>
<p>If we observe the type for a right Kan extension over the category of Haskell types:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> g h a = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a>
        <span style="color: green;">&#123;</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> :: <span style="color: #06c; font-weight: bold;">forall</span> b. <span style="color: green;">&#40;</span>a -&gt; g b<span style="color: green;">&#41;</span> -&gt; h b <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>This is defined in category-extras under <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html">Control.Functor.KanExtension</a> along with a lot of the traditional machinery for working with them.</p>
<p>We say that <code>Ran g h</code> is the right Kan extension of <code>h</code> along <code>g</code>. and mathematicians denote it <img src='http://comonad.com/latex/d25e3743e640a40def94940c807014da.png' title='$\mathbf{Ran}_G H$' alt='$\mathbf{Ran}_G H$' align=absmiddle>. It has a <a href="http://en.wikipedia.org/wiki/Kan_extension">pretty diagram</a> associated with it, but thats as deep as I'll let the category theory go.</p>
<p>This looks an awful lot like the type of a continuation monad transformer:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> ContT r m a = ContT
        <span style="color: green;">&#123;</span> runContT :: <span style="color: green;">&#40;</span>a -&gt; m r<span style="color: green;">&#41;</span> -&gt; m r <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>The main difference is that we have two functors involved and that the body of the Kan extension is universally quantified over the value it contains, so the function it carries can't just hand you back an <code>m r</code> it has lying around unless the functor it has closed over doesn't depend at all on the type <code>r</code>.</p>
<p>Interestingly we can define an instance of <code>Functor</code> for a right Kan extension without even knowing that <code>g</code> or <code>h</code> are functors! Anything of kind * -> * will do.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> g h<span style="color: green;">&#41;</span> <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 = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>\\k -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> m <span style="color: green;">&#40;</span>k . f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p><b>The monad generated by a functor</b></p>
<p>We can take the right Kan extension of a functor <code>f</code> along itself (this works for any functor in Haskell) and get what is known as the <i>monad generated by <code>f</code></i> or the <i>codensity monad of <code>f</code></i>:</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><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 f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> x = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>\\k -&gt; k x<span style="color: green;">&#41;</span>
	m &gt;&gt;= k = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#40;</span>\\c -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> m <span style="color: green;">&#40;</span>\\a -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#v:runRan"><span style="font-weight: bold;">runRan</span></a> <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> c<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>This monad is mentioned in passing in <a href="http://citeseer.ist.psu.edu/mccrudden02opmonoidal.html">Opmonoidal Monads</a> by Paddy McCrudden and dates back further to Ross Street's "The formal theory of monads" from 1972. The term codensity seems to date back at least to Dubuc's thesis in 1974. </p>
<p>Again, this monad doesn't care one whit about the fact that <code>f</code> is a Functor in the Haskell sense.</p>
<p>This monad provides a useful opportunity for optimization. For instance Janis Voigtländer noted in <a href="http://wwwtcs.inf.tu-dresden.de/~voigt/mpc08.pdf">Asymptotic improvement of functions over Free Monads</a> that a particular monad could be used to improve performance -- Free monads as you'll recall are the tool used in Wouter Sweirstra's <a href="http://www.cs.nott.ac.uk/~wss/Publications/DataTypesALaCarte.pdf">Data Types á la Carte</a>, and provide an approach for, among other things, decomposing the <code>IO</code> monad into something more modular, so this is by no means a purely academic exercise! </p>
<p>Voigtländer's monad,</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> C m a = C <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> b. <span style="color: green;">&#40;</span>a -&gt; m b<span style="color: green;">&#41;</span> -&gt; m b<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>turns out to be just the right Kan extension of another monad along itself, and can equivalently be thought of as a <code>ContT</code> that has been universally quantified over its result type.</p>
<p>The improvement results from the fact that the continuation passing style transformation it applies keeps you from traversing back and forth over the entire tree when performing substitution in the free monad.</p>
<p><b>The Yoneda Lemma</b></p>
<p>Heretofore we've only used right Kan extensions where we have extended a functor along itself. Lets change that:</p>
<p>Dan Piponi <a href="http://sigfpe.blogspot.com/2006/11/yoneda-lemma.html">posted a bit</a> about the Yoneda lemma a couple of years back, which ended with the observation that the Yoneda lemma says that check and uncheck are inverses:</p>
<pre class="haskell">&nbsp;
&gt; check :: <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; <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> b . <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt; f b<span style="color: green;">&#41;</span>
&gt; check a f = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f a
&nbsp;
&gt; uncheck :: <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> b . <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt; f b<span style="color: green;">&#41;</span> -&gt; f a
&gt; uncheck t = t <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>We can see that this definition for a right Kan extension just boxes up that universal quantifier in a <code>newtype</code> and that we could instantiate:</p>
<pre class="haskell">&nbsp;
&gt; <span style="color: #06c; font-weight: bold;">type</span> Yoneda = <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> Identity
&nbsp;</pre>
<p>and we can define <code>check</code> and <code>uncheck</code> as:</p>
<pre class="haskell">&nbsp;
check' :: <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
check' a = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> <span style="color: green;">&#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> <span style="color: green;">&#40;</span>runIdentity . f<span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span>
&nbsp;
uncheck' :: Yoneda f a -&gt; f a
uncheck' t = <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> t Identity
&nbsp;</pre>
<p><b>Limits</b></p>
<p>We can go on and define categorical limits in terms of right Kan extensions using the <code>Trivial</code> functor that maps everything to a category with a single value and function. In Haskell, this is best expressed by:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Trivial a = Trivial
<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> Trivial <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 _ = Trivial
trivialize :: a -&gt; Trivial b
trivialize _ = Trivial
&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Lim = <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> Trivial
&nbsp;</pre>
<p>Now, in Haskell, this gives us a clear operational understanding of categorical limits.</p>
<pre class="haskell">&nbsp;
Lim f a ~ <span style="color: #06c; font-weight: bold;">forall</span> b. <span style="color: green;">&#40;</span>a -&gt; Trivial b<span style="color: green;">&#41;</span> -&gt; f b
&nbsp;</pre>
<p>This says that we can't use any information of the value <code>a</code> we supply, or given by the function <code>(a -> Trivial b)</code> when constructing <code>f b</code>, but we have to be able to define an <code>f b</code> for any type <code>b</code> requested. However, we have no way to get any <code>b</code> to plug into the functor! So the only (non-cheating) member of <code>Lim Maybe a</code> is <code>Nothing</code>, of <code>Lim [] a</code> is <code>[]</code>, etc.</p>
<p><b>Left Kan extensions</b></p>
<p>Left Kan extensions are a bit more obscure to a Haskell programmer, because where right Kan extensions relate to the well-known <code>ContT</code> monad transformer, the left Kan extension is related to a less well known comonad transformer.</p>
<p>First, the a Haskell type for the Left Kan extension of <code>h</code> along <code>g</code>:</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> g h a = <span style="color: #06c; font-weight: bold;">forall</span> b. <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <span style="color: green;">&#40;</span>g b -&gt; a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>h b<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>This is related to the admittedly somewhat obscure <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad-Context.html">state-in-context comonad transformer</a>, which I constructed  for category-extras.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> ContextT s w a = ContextT
        <span style="color: green;">&#123;</span> runContextT :: <span style="color: green;">&#40;</span>w s -&gt; a, w s<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>However, the left Kan extension provides no information about the type <code>b</code> contained inside of its <code>h</code> functor and <code>g</code> and <code>h</code> are not necessarily the same functor.</p>
<p>As before we get that <code>Lan g h</code> is a Functor regardless of what <code>g</code> and <code>h</code> are, because we only have to map over the right hand side of the contained function:</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><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> g h<span style="color: green;">&#41;</span> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <span style="color: green;">&#40;</span>f . g<span style="color: green;">&#41;</span> h
&nbsp;</pre>
<p><b>The comonad generated by a functor</b></p>
<p>We can also see that the left Kan extension of any functor <code>f</code> along itself is a comonad, even if f is not a Haskell <code>Functor</code>. This is of course known as the <i>comonad generated by <code>f</code></i>, or the <i>density comonad of <code>f</code></i>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f f<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><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f a<span style="color: green;">&#41;</span> = f a
	<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f ws<span style="color: green;">&#41;</span> = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> f<span style="color: green;">&#41;</span> ws
&nbsp;</pre>
<p><b>Colimits</b></p>
<p>Finally we can derive colimits, by:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Colim = <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> Trivial
&nbsp;</pre>
<p>then <code>Colim f a ~ exists b. (Trivial b -> a, f b)</code>, and we can see that operationally, we have an <code>f</code> of some unknown type <code>b</code> and for all intents and purposes a value of type <code>a</code> since we can generate a Trivial b from thin air, so while limits allow only structures without values, colimits allow arbitrary structures, but keep you from inspecting the values in them by existential quantification. So for instance you could apply a length function to a <code>Colim [] a</code>, but not add up its values.</p>
<p>You can also build up a covariant analog of the traditional Yoneda lemma using <code>Lan Identity</code>, but I leave that as an exercise for the reader.</p>
<p>I've barely scratched the surface of what you can do with Kan extensions, but I just wanted to shine a little light on this dark corner of category theory.</p>
<p>For more information feel free to explore category-extras. For instance, both right and left Kan extensions along a functor are <a href="http://comonad.com/haskell/category-extras/src/Control/Functor/HigherOrder.hs">higher-order functors</a>, and hence so are Yoneda, Lim, and Colim as defined above.</p>
<p>Thats all I have time for now.</p>
<p>Code for right and left Kan extensions, limits, colimits and the Yoneda lemma are all available from category-extras on hackage.</p>
<p>[Edit: the code has since been refactored to treat Yoneda, CoYoneda, Density and Codensity as separate newtypes to allow for instance both Yoneda and Codensity to be different monads]</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2008/kan-extensions/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Elgot (Co)Algebras</title>
		<link>http://comonad.com/reader/2008/elgot-coalgebras/</link>
		<comments>http://comonad.com/reader/2008/elgot-coalgebras/#comments</comments>
		<pubDate>Tue, 20 May 2008 02:31:26 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Squiggol]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/2008/elgot-algebras/</guid>
		<description><![CDATA[&#160;
&#62; import Control.Arrow &#40;&#40;&#124;&#124;&#124;&#41;,&#40;&#38;&#38;&#38;&#41;,left&#41;
&#62; newtype Mu f = InF &#123; outF :: f &#40;Mu f&#41; &#125;
&#160;
I want to talk about a novel recursion scheme that hasn't received a lot of attention from the Haskell community and its even more obscure dual -- which is necessarily more obscure because I believe this is the first time [...]]]></description>
			<content:encoded><![CDATA[<pre class="haskell">&nbsp;
&gt; <span style="color: #06c; font-weight: bold;">import</span> Control.Arrow <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>|||<span style="color: green;">&#41;</span>,<span style="color: green;">&#40;</span>&amp;&amp;&amp;<span style="color: green;">&#41;</span>,left<span style="color: green;">&#41;</span>
&gt; <span style="color: #06c; font-weight: bold;">newtype</span> Mu f = InF <span style="color: green;">&#123;</span> outF :: f <span style="color: green;">&#40;</span>Mu f<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>I want to talk about a novel recursion scheme that hasn't received a lot of attention from the Haskell community and its even more obscure dual -- which is necessarily more obscure because I believe this is the first time anyone has talked about it. </p>
<p><a href="http://www.iti.cs.tu-bs.de/~adamek/adamek.html">Jiri Adámek</a>, <a href="http://www.iti.cs.tu-bs.de/~milius/">Stefan Milius</a> and <a href="http://math.feld.cvut.cz/velebil/">Jiri Velebil</a> have done a lot of work on <a href="http://arxiv.org/abs/cs/0609040">Elgot algebras</a>.  Here I'd like to translate them into Haskell, dualize them, observe that the dual can encode primitive recursion, and provide some observations.</p>
<p>You can kind of think an Elgot algebra as a hylomorphism that cheats.</p>
<pre class="haskell">&nbsp;
&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Algebra-Elgot.html#v:elgot"><span style="font-weight: bold;">elgot</span></a> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <span style="color: green;">&#40;</span>f b -&gt; b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a> b <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; a -&gt; b
&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Algebra-Elgot.html#v:elgot"><span style="font-weight: bold;">elgot</span></a> phi psi = h <span style="color: #06c; font-weight: bold;">where</span> h = <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> ||| phi . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h<span style="color: green;">&#41;</span> . psi
&nbsp;</pre>
<p><span id="more-60"></span></p>
<p>If you look at the signature for a hylomorphism:</p>
<pre class="haskell">&nbsp;
&gt; hylo :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <span style="color: green;">&#40;</span>f b -&gt; b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; f a<span style="color: green;">&#41;</span> -&gt; a -&gt; b
&gt; hylo phi psi = h <span style="color: #06c; font-weight: bold;">where</span> h = phi . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h . psi
&nbsp;</pre>
<p>Then you can see that an Elgot algebra is basically a hylomorphism that is allowed to shortcircuit the infinite tower of fmaps and return an intermediate result directly.</p>
<p>In some sense you can say that the coalgebra-like side of the hylomorphism is no longer oblivious to the algebra used to deconstruct the intermediate result.</p>
<p>We can take the Elgot algebra and dualize it to get a novel construction where the algebra-like side is no longer oblivious to the coalgebra. This allows your algebra to cheat and just use the intermediate results constructed by the anamorphism to return an answer. I'll choose to call this co-(Elgot algebra) an Elgot coalgebra in the sequel.</p>
<pre class="haskell">&nbsp;
&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Algebra-Elgot.html#v:coelgot"><span style="font-weight: bold;">coelgot</span></a> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a, f b<span style="color: green;">&#41;</span> -&gt; b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; f a<span style="color: green;">&#41;</span> -&gt; a -&gt; b
&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Algebra-Elgot.html#v:coelgot"><span style="font-weight: bold;">coelgot</span></a> phi psi = h <span style="color: #06c; font-weight: bold;">where</span> h = phi . <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> &amp;&amp;&amp; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h . psi<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>In a lot of ways an Elgot algebra resembles Vene and Uustalu's <a href="http://citeseer.ist.psu.edu/vene98functional.html">apomorphism</a>.</p>
<pre class="haskell">&nbsp;
&gt; apo :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <span style="color: green;">&#40;</span>a -&gt; f <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a> <span style="color: green;">&#40;</span>Mu f<span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; a -&gt; Mu f
&gt; apo psi = h <span style="color: #06c; font-weight: bold;">where</span> h = InF . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h . <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:Left"><span style="font-weight: bold;">Left</span></a> . outF ||| psi<span style="color: green;">&#41;</span> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a>
&nbsp;</pre>
<p>However, we have 'unfixed' the algebra to be used from InF to something more general and the layering of Either and f is different.</p>
<p>Now, a generalized apomorphism does something similar entangling two coalgebras, but the signature doesn't quite match up either, since a generalized apomorphism uses an F-coalgebras and an F-(b + _)-monadic coalgebra. </p>
<pre class="haskell">&nbsp;
&gt; g_apo :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <span style="color: green;">&#40;</span>b -&gt; f b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; f <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a> b a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; a -&gt; Mu f
&gt; g_apo g f = h <span style="color: #06c; font-weight: bold;">where</span> h = InF . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h . <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:Left"><span style="font-weight: bold;">Left</span></a> . g ||| f<span style="color: green;">&#41;</span> . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a>
&nbsp;</pre>
<p>Similarly a zygomorphism, or more generally a <a href="http://dbappl.cs.utwente.nl/Publications/PaperStore/db-utwente-0000003537.pdf">mutumorphism</a> entangles two algebras.</p>
<p>An Elgot algebra occupies a somewhat rare spot in the theory of constructive algorithmics or recursion schemes in that it while it mixes an algebra with a coalgebra like a hylomorphism or metamorphisms, it entangles them in a novel way.</p>
<p>If we specialize the Elgot algebra by fixing its algebra to InF we get:</p>
<pre class="haskell">&nbsp;
&gt; elgot_apo :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <span style="color: green;">&#40;</span>a -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a> <span style="color: green;">&#40;</span>Mu f<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; a -&gt; Mu f
&gt; elgot_apo psi = h <span style="color: #06c; font-weight: bold;">where</span> h = <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> ||| InF . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> h<span style="color: green;">&#41;</span> . psi
&nbsp;</pre>
<p>We can see that the type is now closely related to that of an apomorphism with some slight changes in design decisions. Instead of wrapping a functor around further seeds, a, or a finished structure, this specialized Elgot algebra returns the finished structure directly or an f wrapped around seeds. </p>
<p><b>The Good</b></p>
<p>So can we convert between an apomorphism and an Elgot algebra? For a somewhat circuitous path to that answer lets recall the <a href="http://comonad.com/reader/2008/deriving-strength-from-laziness/">definition of strength</a> from my post a couple of weeks ago. Flipping the arguments and direction of application for strength to simplify what is coming we get:</p>
<pre class="haskell">&nbsp;
&gt; strength' :: <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; t -&gt; f a -&gt; f <span style="color: green;">&#40;</span>t, a<span style="color: green;">&#41;</span>
&gt; strength' fa b = <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>,<span style="color: green;">&#41;</span>b<span style="color: green;">&#41;</span> fa
&nbsp;</pre>
<p>With that in hand we quickly find that we can rederive <a href="http://en.wikipedia.org/wiki/Paramorphism">paramorphisms</a> (and hence primitive recursion) from the novel notion of an Elgot coalgebra that we defined above by leaning on the strength of our functor.</p>
<pre class="haskell">&nbsp;
&gt; para :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>Mu f, c<span style="color: green;">&#41;</span> -&gt; c<span style="color: green;">&#41;</span> -&gt; Mu f -&gt; c
&gt; para f = <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-Algebra-Elgot.html#v:coelgot"><span style="font-weight: bold;">coelgot</span></a> <span style="color: green;">&#40;</span>f . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:uncurry"><span style="font-weight: bold;">uncurry</span></a> strength'<span style="color: green;">&#41;</span> outF
&nbsp;</pre>
<p>This result tells us that the shiny new Elgot coalgebras we defined above are strong enough to encode primitive recursion when working in Haskell.</p>
<p><b>The Bad</b></p>
<p>This tempts us to try to derive apomorphisms from Elgot algebras using the dual case, costrength. However, if you'll recall from my previous post on comonadic costrength, we can't do that in general. The result is only defined for Traversable functors; not every functor is costrong in Haskell!</p>
<p>Consequently and counterintuitively, though we can define a paramorphism in terms of Elgot coalgebras, we can only define an apomorphism in terms of Elgot algebras for traversable functors.</p>
<p><b>The Ugly</b></p>
<p>Now, worse news. Since the tower of functors we build up doesn't run off to infinity we lose the ability to generalize Elgot (co)algebras using the same machinery we can use to generalize the various traditional recursion schemes by parameterizing it by a (co)monad and distributive law.</p>
<p>At least the straightforward translation fails. For instance in the case of an Elgot algebra, the obvious addition would be to allow for the algebra (f a -> a) to be replaced with a F-W-comonadic algebra (f (w a) -> a) for some comonad w. However, attempts to do so run afoul of the fact that the coalgebra-like structure feeds us an 'a' not a 'w a'. We can of course change the signature of the coalgebra to give us the comonad, but the breakdown of modularity is unfortunate. </p>
<p>Similary, parameterizing the coalgebra-like structure with a monad requires the ability to distribute the monad over Either b to get to where it can apply the distributive law for the base functor f. Interestingly the Either monad works, which gives us ways to compose Elgot (co)algebras, but that is a story for another day.</p>
<p>As usual there is a tradeoff in expressivity in one area to compensate for gains in another, but this manner of entangling provides us with a new set of possibilities to explore.</p>
<p>Code for Elgot algebras and Elgot coalgebras has been included in <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/category-extras-0.50.3">category-extras</a> as of release 0.50.3 as <a href="http://comonad.com/haskell/category-extras/src/Control/Functor/Algebra/">Control.Functor.Algebra.Elgot</a>. </p>
<p>Now available from hackage.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2008/elgot-coalgebras/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Generatingfunctorology</title>
		<link>http://comonad.com/reader/2008/generatingfunctorology/</link>
		<comments>http://comonad.com/reader/2008/generatingfunctorology/#comments</comments>
		<pubDate>Wed, 14 May 2008 07:45:38 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Type Theory]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/2008/generatingfunctorology/</guid>
		<description><![CDATA[Ok, I decided to take a step back from my flawed approach in the last post and play with the idea of power series of functors from a different perspective.
I dusted off my copy of Herbert Wilf's generatingfunctionology and switched goals to try to see some well known recursive functors or species as formal power [...]]]></description>
			<content:encoded><![CDATA[<p>Ok, I decided to take a step back from my flawed approach in the <a href="http://comonad.com/reader/2008/towards-formal-power-series-for-functors">last post</a> and play with the idea of power series of functors from a different perspective.</p>
<p>I dusted off my copy of Herbert Wilf's <a href="http://www.math.upenn.edu/~wilf/DownldGF.html">generatingfunctionology</a> and switched goals to try to see some well known recursive functors or <a href="http://www.cas.mcmaster.ca/~carette/species/msfp08_species.pdf">species</a> as formal power series. It appears that we can pick a few things out about the generating functions of polynomial functors.</p>
<p>As an example:</p>
<pre class="haskell">&nbsp;
<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> x = <span style="color: red;">1</span> + x
&nbsp;</pre>
<p>Ok. We're done. Thank you very much. I'll be here all week. Try the veal... </p>
<p>For a more serious example, the formal power series for the list [x] is just a <a href="http://en.wikipedia.org/wiki/Geometric_series">geometric series</a>:</p>
<p><span id="more-58"></span></p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#91;</span>x<span style="color: green;">&#93;</span> = mu y . <span style="color: red;">1</span> + x y  <span style="color: #5d478b; font-style: italic;">-- the mu here is a pleasant fiction, more below</span>
    = <span style="color: red;">1</span> + x <span style="color: green;">&#40;</span><span style="color: red;">1</span> + x <span style="color: green;">&#40;</span><span style="color: red;">1</span> + x <span style="color: green;">&#40;</span>...<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
    = <span style="color: red;">1</span> + x + x^<span style="color: red;">2</span> + x^<span style="color: red;">3</span> + ...
    = <span style="color: red;">1</span>/<span style="color: green;">&#40;</span><span style="color: red;">1</span>-x<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Given the power series of a functor, its nth coefficient * n! tells you how many distinguishable ways its constructors can house n values. If we see that a list of n values can be permuted n! ways this has some interesting possibilities for linearizing the storage of some functors. The list case is boring, we can store a <i>finite</i> list of n elements by supplying the length of the array and an array of n elements, hence (among other reasons) the mu above.</p>
<p>Lets try decorated binary trees:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Tree x = Leaf | Node <span style="color: green;">&#40;</span>Tree x<span style="color: green;">&#41;</span> x <span style="color: green;">&#40;</span>Tree x<span style="color: green;">&#41;</span>
&nbsp;
Tree x = mu y. <span style="color: red;">1</span> + x * y * y
       = <span style="color: red;">1</span> + x * <span style="color: green;">&#40;</span><span style="color: red;">1</span> + x * <span style="color: green;">&#40;</span>...<span style="color: green;">&#41;</span>^<span style="color: red;">2</span><span style="color: green;">&#41;</span>^<span style="color: red;">2</span>
       = <span style="color: red;">1</span> + x + 2x^<span style="color: red;">2</span> + 5x^<span style="color: red;">3</span> + 14x^<span style="color: red;">4</span> + 42x^<span style="color: red;">5</span> + ...
&nbsp;</pre>
<p>It turns out the coefficients of our generating function are the <a href="http://en.wikipedia.org/wiki/Catalan_number">Catalan numbers</a>, <a href="http://www.research.att.com/~njas/sequences/A000108">A000108</a>, commonly denoted C(n), which happen to be well known for among other things, being the number of ways you can build a binary tree of n nodes.</p>
<p>This tells us we could store a tree by storing a number <em>n</em> of nodes it contains, an array of that many nodes, and an index 0 < = i < C(n) to tell you which particular tree you selected. Not that this is likely to be an incredibly time-efficient encoding, but you could then fmap over the tree by just fmapping over your array.</p>
<p>For a formal power series,</p>
<p><img src='http://comonad.com/latex/7b6fb5aa61c9491ac598d6ebbfcfe5c9.png' title='$f(x) = \sum_{i=0}^{\infty} a_n x^n = a_0 + a_1 x + a_2 x^2 + ... $' alt='$f(x) = \sum_{i=0}^{\infty} a_n x^n = a_0 + a_1 x + a_2 x^2 + ... $' align=absmiddle></p>
<p>its derivative is given by differentiating the series term by term:</p>
<p><img src='http://comonad.com/latex/da09bd9c7661fddc0b0d62cfd6f139b8.png' title='$f&#039;(x) = \sum_{i=1}^{\infty} n a_n x^{n - 1} = a_1 + 2 a_2 x + 3 a_3 x^2 + ...$' alt='$f&#039;(x) = \sum_{i=1}^{\infty} n a_n x^{n - 1} = a_1 + 2 a_2 x + 3 a_3 x^2 + ...$' align=absmiddle></p>
<p>Consequently we can take the derivative of a list:</p>
<p>([]') x = 1 + 2x + 3x^2 + ... = 1/(1-x)^2 = ([] :*: []) x</p>
<p>and rederive the notion that a derivative/one hole context of a list can be represented by a pair of lists.</p>
<p>If we step slightly outside of the Haskell users' comfort zone and notion of a Functor and allow other Species, we get (as noted by apfelmus the other day) that Exp a is just a bag of elements with no predetermined order.</p>
<pre class="haskell">&nbsp;
Exp x = <span style="color: red;">1</span> + x + x^<span style="color: red;">2</span>/<span style="color: red;">2</span>! + x^<span style="color: red;">3</span>/<span style="color: red;">3</span>! + ... = Bag x
&nbsp;
Since there are n! ways to order n elements <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:and"><span style="font-weight: bold;">and</span></a> Bag manages to forget that information, we can get a feeling for the meaning <span style="color: #06c; font-weight: bold;">of</span> division <span style="color: #06c; font-weight: bold;">in</span> this setting.
&nbsp;
Similarly we can define:
&lt;pre lang=<span style="color: #3c7331;">&quot;haskell&quot;</span>&gt;
Sinh x = x + x^<span style="color: red;">3</span>/<span style="color: red;">3</span>! + ... <span style="color: #5d478b; font-style: italic;">-- a Bag of some odd number of elements.</span>
Cosh x = <span style="color: red;">1</span> + x^<span style="color: red;">2</span>/<span style="color: red;">2</span>! + ... <span style="color: #5d478b; font-style: italic;">--  a Bag of some even number of elements.</span>
&nbsp;</pre>
<p>Then by construction:</p>
<pre class="haskell">&nbsp;
Exp = Cosh :+: Sinh
&nbsp;</pre>
<p>The derivative of Exp is Exp, of Cosh is Sinh, of Sinh is Cosh, all as you would expect.</p>
<p>We can handle other species as well:</p>
<pre class="haskell">&nbsp;
Cycle a = <span style="color: red;">1</span> + x^<span style="color: red;">2</span>/<span style="color: red;">2</span> + x^<span style="color: red;">3</span>/<span style="color: red;">3</span> + x^<span style="color: red;">4</span>/<span style="color: red;">4</span> + ... <span style="color: #5d478b; font-style: italic;">-- cycles</span>
Cycle_n a = x^n/n <span style="color: #5d478b; font-style: italic;">-- cycles of n elements</span>
Bag_n a = x^n/n!  <span style="color: #5d478b; font-style: italic;">-- bags of n elements</span>
&nbsp;</pre>
<p>That said, there seem to be some problems, not every functor is well behaved in this way. Lets take for instance the type of natural numbers given by the functor:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Nat a = S <span style="color: green;">&#40;</span>Nat a<span style="color: green;">&#41;</span> | Z
&nbsp;</pre>
<p>Then the recurrence blows up, the coefficient for 0 is <img src='http://comonad.com/latex/05337ee7dbe333d118d371bc95c44f7a.png' title='$\aleph_0$' alt='$\aleph_0$' align=absmiddle>!</p>
<p>Similarly, if we parameterized a functor on another value we have to deal with the number of cases that other value can denote.</p>
<pre class="haskell">&nbsp;
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a> a x = |a| + x
<span style="color: green;">&#40;</span>a,x<span style="color: green;">&#41;</span> = |a| x
&nbsp;</pre>
<p>This is both good and bad, using the above, we can quickly establish an isomorphism between Either () and the Maybe Functor, but we blow up again for Either Integer. This gets even worse if we allow 'functors in space.' (i.e. functors that can contain functions)</p>
<p>On the other extreme, we might modify our tree example and remove the leaves, yielding infinite decorated cotrees.</p>
<pre class="haskell">&nbsp;
Tree x = nu y. x * y * y
       = x * <span style="color: green;">&#40;</span>x * <span style="color: green;">&#40;</span>...<span style="color: green;">&#41;</span>^<span style="color: red;">2</span><span style="color: green;">&#41;</span>^<span style="color: red;">2</span>
       = <span style="color: red;">0</span> + 0x + 0x^<span style="color: red;">2</span> + 0x^<span style="color: red;">3</span> + ...
&nbsp;</pre>
<p>Then a_n = 0 for all n in the natural numbers, so you can't use the coefficients of the generating function to tell you about the behavior of an infinite structure! It would appear that the generating function of a functor does not capture what happens in the greatest fixed point case, so we can only use generating functions to describe the behavior of data defined with mu, not in general codata defined by nu.</p>
<p>The Bags and Cycles above are nice examples, but if we wanted to rule out the non-polynomial Functors (from the Haskell perspective) in the above then we can simply limit ourselves to <a href="http://en.wikipedia.org/wiki/Generating_function#Ordinary_generating_function_2">ordinary generating functions</a> with natural number coefficients, that is to say generating functions of the form:</p>
<p><img src='http://comonad.com/latex/7b6fb5aa61c9491ac598d6ebbfcfe5c9.png' title='$f(x) = \sum_{i=0}^{\infty} a_n x^n = a_0 + a_1 x + a_2 x^2 + ... $' alt='$f(x) = \sum_{i=0}^{\infty} a_n x^n = a_0 + a_1 x + a_2 x^2 + ... $' align=absmiddle></p>
<p>To choose to admit bags,  cycles and other species etc. then you need merely also permit <a href="http://en.wikipedia.org/wiki/Generating_function#Exponential_generating_function_2">exponential generating functions</a> with natural coefficients, that is to say, generating functions of the form:</p>
<p><img src='http://comonad.com/latex/c30686528791fe1a38720bf5006b81a3.png' title='$f(x) = \sum_{i=0}^{\infty} a_n x^n / n! = a_0 + a_1 x / 1! + a_2 x^2 / 2! + ... $' alt='$f(x) = \sum_{i=0}^{\infty} a_n x^n / n! = a_0 + a_1 x / 1! + a_2 x^2 / 2! + ... $' align=absmiddle></p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2008/generatingfunctorology/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Towards Formal Power Series for Functors</title>
		<link>http://comonad.com/reader/2008/towards-formal-power-series-for-functors/</link>
		<comments>http://comonad.com/reader/2008/towards-formal-power-series-for-functors/#comments</comments>
		<pubDate>Tue, 13 May 2008 09:22:19 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Type Theory]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/2008/towards-formal-power-series-for-functors/</guid>
		<description><![CDATA[The post below will only compile on a version of GHC >= 6.9, since it uses type families.

There has been a lot of posting recently about automatic differentiation in Haskell, and I wanted to try the same thing with functors in the spirit of Conor McBride's Clowns to the Left of me, Jokers to the [...]]]></description>
			<content:encoded><![CDATA[<p>The post below will only compile on a version of GHC >= 6.9, since it uses type families.</p>
<p><span id="more-57"></span></p>
<p>There has been a lot of posting recently about automatic differentiation in Haskell, and I wanted to try the same thing with functors in the spirit of Conor McBride's <a href="http://strictlypositive.org/CJ.pdf">Clowns to the Left of me, Jokers to the Right</a> and <a href="http://citeseer.ist.psu.edu/472190.html">The derivative of a regular type is its type of one hole contexts</a>, figuring that a Power Series could fully generalize Christophe Poucet's <a href="http://notvincenz.blogspot.com/2007/07/higher-order-zippers.html">Higher Order Zippers</a>, and might provide me with a neat extension to the zipper comonadic automata I've been aluding to recently.</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# OPTIONS -fglasgow-exts -fallow-undecidable-instances -fallow-overlapping-instances #-}</span>
<span style="color: #06c; font-weight: bold;">module</span> Derivatives <span style="color: #06c; font-weight: bold;">where</span>
<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>.Identity
<span style="color: #06c; font-weight: bold;">import</span> Control.Arrow <span style="color: green;">&#40;</span><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;">&#40;</span>&amp;&amp;&amp;<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Data.Monoid
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">9</span> :.:
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">7</span> :*:
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">6</span> :+:
&nbsp;</pre>
<p>To avoid importing <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/category-extras-0.44.4">category-extras</a> and keep this post self-contained (modulo GHC 6.9!), we'll define some preliminaries such as Bifunctors:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Bifunctor f <span style="color: #06c; font-weight: bold;">where</span>
	bimap :: <span style="color: green;">&#40;</span>a -&gt; c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>b -&gt; d<span style="color: green;">&#41;</span> -&gt; f a b -&gt; f c d
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Bifunctor <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	bimap f g ~<span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>f a, g b<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Bifunctor <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a> <span style="color: #06c; font-weight: bold;">where</span>
	bimap f _ <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Left"><span style="font-weight: bold;">Left</span></a> a<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Left"><span style="font-weight: bold;">Left</span></a> <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
	bimap _ g <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a> b<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a> <span style="color: green;">&#40;</span>g b<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Constant functors:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Void
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a> Void <span style="color: #06c; font-weight: bold;">where</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:show"><span style="font-weight: bold;">show</span></a> _ = <span style="color: #3c7331;">&quot;Void&quot;</span>
<span style="color: #06c; font-weight: bold;">newtype</span> Const k a = Const <span style="color: green;">&#123;</span> runConst :: k <span style="color: green;">&#125;</span> <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a><span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">type</span> Zero = Const Void
<span style="color: #06c; font-weight: bold;">type</span> One = Const <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
<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>Const k<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f = Const . runConst
&nbsp;</pre>
<p>and functor products and coproducts:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Lift p f g a = Lift <span style="color: green;">&#123;</span> runLift ::  p <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
<span style="color: #06c; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:+:<span style="color: green;">&#41;</span> = Lift <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a>
<span style="color: #06c; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:*:<span style="color: green;">&#41;</span> = Lift <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a> <span style="color: green;">&#40;</span>p <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a> <span style="color: green;">&#40;</span>Lift p f g a<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:show"><span style="font-weight: bold;">show</span></a> <span style="color: green;">&#40;</span>Lift x<span style="color: green;">&#41;</span> = <span style="color: #3c7331;">&quot;(Lift (&quot;</span> ++ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:show"><span style="font-weight: bold;">show</span></a> x ++ <span style="color: #3c7331;">&quot;))&quot;</span>
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Bifunctor p, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> g<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Lift p f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f = Lift . bimap <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> . runLift
&nbsp;</pre>
<p>and finally functor composition</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> <span style="color: green;">&#40;</span>f :.: g<span style="color: green;">&#41;</span> a = Comp <span style="color: green;">&#123;</span> runComp :: f <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span> <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a><span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> g<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>f :.: g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f = Comp . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> . runComp
&nbsp;</pre>
<p>So then, an ideal type for repeated differentiation would look something like the following, for some definition of D.</p>
<p>[Edit: sigfpe pointed out, quite rightly, that this is just repeated differentiation, and apfelmus pointed out that it not a power series, because I have no division!]</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> AD f a  = AD <span style="color: green;">&#123;</span> runAD :: <span style="color: green;">&#40;</span>f a,  AD <span style="color: green;">&#40;</span>D f<span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>As a first crack at D, you might be tempted to just go with a type family:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-
type family D (f :: * -&gt; *) :: * -&gt; *
type instance D Identity = One
type instance D (Const k) = Zero
type instance D (f :+: g) = D f :+: D g
type instance D (f :*: g) = f :*: D g :+: D f :*: g
type instance D (f :.: g) = (D f :.: g) :*: D g
-}</span>
&nbsp;</pre>
<p>This could take you pretty far, but unfortunately doesn't adequately provide you with any constraints on the type so that we can treat AD f as a functor.</p>
<p>So, we'll go with:</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> <span style="color: green;">&#40;</span>D f<span style="color: green;">&#41;</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<span style="color: green;">&#41;</span> =&gt; Derivable <span style="color: green;">&#40;</span>f :: * -&gt; *<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D f :: * -&gt; *
&nbsp;</pre>
<p>and cherry pick the instances necessary to handle the above cases:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Derivable Identity <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D Identity = One
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Derivable <span style="color: green;">&#40;</span>Const k<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D <span style="color: green;">&#40;</span>Const k<span style="color: green;">&#41;</span> = Zero
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Derivable f, Derivable g<span style="color: green;">&#41;</span> =&gt; Derivable <span style="color: green;">&#40;</span>f :+: g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D <span style="color: green;">&#40;</span>f :+: g<span style="color: green;">&#41;</span> = D f :+: D g 
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Derivable f, Derivable g<span style="color: green;">&#41;</span> =&gt; Derivable <span style="color: green;">&#40;</span>f :*: g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D <span style="color: green;">&#40;</span>f :*: g<span style="color: green;">&#41;</span> = f :*: D g :+: D f :*: g
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Derivable f, Derivable g<span style="color: green;">&#41;</span> =&gt; Derivable <span style="color: green;">&#40;</span>f :.: g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D <span style="color: green;">&#40;</span>f :.: g<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>D f :.: g<span style="color: green;">&#41;</span> :*: D g
&nbsp;</pre>
<p>With those instances in hand, we can define the definition of a Functor for the automatic differentiation of a Functor built out of these primitives:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Derivable f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>AD <span style="color: green;">&#40;</span>D f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>AD 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 = Power . bimap <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> . runPower
&nbsp;</pre>
<p>Unfortunately, here is where I run out of steam, because any attempt to actually use the construct in question blows the context stack because the recursion for Functor (AD f) isn't well founded and my attempts to force it to be so through overlapping-instances have thus-far failed.</p>
<p>Thoughts?</p>
<p>[<a href="http://comonad.com/haskell/Derivatives.hs">Source Code</a>]</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2008/towards-formal-power-series-for-functors/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>
