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

<channel>
	<title>The Comonad.Reader &#187; Kan Extensions</title>
	<atom:link href="http://comonad.com/reader/category/kan-extensions/feed/" rel="self" type="application/rss+xml" />
	<link>http://comonad.com/reader</link>
	<description>types, (co)monads, substructural logic</description>
	<lastBuildDate>Mon, 24 Oct 2022 17:48:27 +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>Categories of Structures in Haskell</title>
		<link>http://comonad.com/reader/2015/categories-of-structures-in-haskell/</link>
		<comments>http://comonad.com/reader/2015/categories-of-structures-in-haskell/#comments</comments>
		<pubDate>Tue, 26 May 2015 01:32:49 +0000</pubDate>
		<dc:creator>Dan Doel</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Type Hackery]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=1037</guid>
		<description><![CDATA[In the last couple posts I've used some 'free' constructions, and not remarked too much on how they arise. In this post, I'd like to explore them more. This is going to be something of a departure from the previous posts, though, since I'm not going to worry about thinking precisely about bottom/domains. This is [...]]]></description>
			<content:encoded><![CDATA[<p>In the last couple posts I've used some 'free' constructions, and not remarked too much on how they arise. In this post, I'd like to explore them more. This is going to be something of a departure from the previous posts, though, since I'm not going to worry about thinking precisely about bottom/domains. This is more an exercise in applying some category theory to Haskell, "fast and loose".</p>
<p>(Advance note: for some continuous code to look at see <a href="http://code.haskell.org/~dolio/haskell-share/categories-of-structures/COS.hs">this file</a>.)</p>
<p>First, it'll help to talk about how some categories can work in Haskell. For any kind <code>k</code> made of <code>*</code> and <code>(->)</code>, [0] we can define a category of type constructors. Objects of the category will be first-class [1] types of that kind, and arrows will be defined by the following type family:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Transformer f g = Transform <span style="color: green;">&#123;</span> <span style="color: green;">&#40;</span>$$<span style="color: green;">&#41;</span> :: <span style="color: #06c; font-weight: bold;">forall</span> i. f i ~&gt; g i <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> family <span style="color: green;">&#40;</span>~&gt;<span style="color: green;">&#41;</span> :: k -&gt; k -&gt; * <span style="color: #06c; font-weight: bold;">where</span>
  <span style="color: green;">&#40;</span>~&gt;<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span>
  <span style="color: green;">&#40;</span>~&gt;<span style="color: green;">&#41;</span> = Transformer
&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> a &lt; -&gt; b = <span style="color: green;">&#40;</span>a -&gt; b, b -&gt; a<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">type</span> a &lt; ~&gt; b = <span style="color: green;">&#40;</span>a ~&gt; b, b ~&gt; a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>So, for a base case, * has monomorphic functions as arrows, and categories for higher kinds have polymorphic functions that saturate the constructor:</p>
<pre class="haskell">&nbsp;
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a> ~&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Char"><span style="background-color: #efefbf; font-weight: bold;">Char</span></a>
  <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> ~&gt; <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> = <span style="color: #06c; font-weight: bold;">forall</span> a. <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> a -&gt; <span style="color: green;">&#91;</span>a<span style="color: green;">&#93;</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> ~&gt; <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span> = <span style="color: #06c; font-weight: bold;">forall</span> a b. <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 b -&gt; <span style="color: green;">&#40;</span>a, b<span style="color: green;">&#41;</span>
  StateT ~&gt; ReaderT = <span style="color: #06c; font-weight: bold;">forall</span> s m a. StateT s m a -&gt; ReaderT s m a
&nbsp;</pre>
<p>We can of course define identity and composition for these, and it will be handy to do so:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Morph <span style="color: green;">&#40;</span>p :: k -&gt; k -&gt; *<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:id"><span style="font-weight: bold;">id</span></a> :: p a a
  <span style="color: green;">&#40;</span>.<span style="color: green;">&#41;</span> :: p b c -&gt; p a b -&gt; p a c
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Morph <span style="color: green;">&#40;</span>-&gt;<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:id"><span style="font-weight: bold;">id</span></a> x = x
  <span style="color: green;">&#40;</span>g . f<span style="color: green;">&#41;</span> x = g <span style="color: green;">&#40;</span>f x<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Morph <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>~&gt;<span style="color: green;">&#41;</span> :: k -&gt; k -&gt; *<span style="color: green;">&#41;</span>
      =&gt; Morph <span style="color: green;">&#40;</span>Transformer :: <span style="color: green;">&#40;</span>i -&gt; k<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>i -&gt; k<span style="color: green;">&#41;</span> -&gt; *<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:id"><span style="font-weight: bold;">id</span></a> = Transform <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
  Transform f . Transform g = Transform $ f . g
&nbsp;</pre>
<p>These categories can be looked upon as the most basic substrates in Haskell. For instance, every type of kind <code>* -> *</code> is an object of the relevant category, even if it's a GADT or has other structure that prevents it from being nicely functorial.</p>
<p>The category for * is of course just the normal category of types and functions we usually call Hask, and it is fairly analogous to the category of sets. One common activity in category theory is to study categories of sets equipped with extra structure, and it turns out we can do this in Haskell, as well. And it even makes some sense to study categories of structures over any of these type categories.</p>
<p>When we equip our types with structure, we often use type classes, so that's how I'll do things here. Classes have a special status socially in that we expect people to only define instances that adhere to certain equational rules. This will take the place of equations that we are not able to state in the Haskell type system, because it doesn't have dependent types. So using classes will allow us to define more structures that we normally would, if only by convention.</p>
<p>So, if we have a kind <code>k</code>, then a corresponding structure will be <code>σ :: k -> Constraint</code>. We can then define the category <code>(k,σ)</code> as having objects <code>t :: k</code> such that there is an instance <code>σ t</code>. Arrows are then taken to be <code>f :: t ~> u</code> such that <code>f</code> "respects" the operations of <code>σ</code>.</p>
<p>As a simple example, we have:</p>
<pre class="haskell">&nbsp;
  k = *
  σ = Monoid :: * -&gt; Constraint
&nbsp;
  Sum <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a>, Product <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a>, <span style="color: green;">&#91;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Integer"><span style="background-color: #efefbf; font-weight: bold;">Integer</span></a><span style="color: green;">&#93;</span> :: <span style="color: green;">&#40;</span>*, Monoid<span style="color: green;">&#41;</span>
&nbsp;
  f :: <span style="color: green;">&#40;</span>Monoid m, Monoid n<span style="color: green;">&#41;</span> =&gt; m -&gt; n
    <span style="color: #06c; font-weight: bold;">if</span> f mempty = mempty
       f <span style="color: green;">&#40;</span>m &lt;&gt; n<span style="color: green;">&#41;</span> = f m &lt;&gt; f n
&nbsp;</pre>
<p>This is just the category of monoids in Haskell.</p>
<p>As a side note, we will sometimes be wanting to quantify over these "categories of structures". There isn't really a good way to package together a kind and a structure such that they work as a unit, but we can just add a constraint to the quantification. So, to quantify over all <code>Monoid</code>s, we'll use '<code>forall m. Monoid m => ...</code>'.</p>
<p>Now, once we have these categories of structures, there is an obvious forgetful functor back into the unadorned category. We can then look for free and cofree functors as adjoints to this. More symbolically:</p>
<pre class="haskell">&nbsp;
  Forget σ :: <span style="color: green;">&#40;</span>k,σ<span style="color: green;">&#41;</span> -&gt; k
  Free   σ :: k -&gt; <span style="color: green;">&#40;</span>k,σ<span style="color: green;">&#41;</span>
  Cofree σ :: k -&gt; <span style="color: green;">&#40;</span>k,σ<span style="color: green;">&#41;</span>
&nbsp;
  Free σ ⊣ Forget σ ⊣ Cofree σ
&nbsp;</pre>
<p>However, what would be nicer (for some purposes) than having to look for these is being able to construct them all systematically, without having to think much about the structure <code>σ</code>.</p>
<p>Category theory gives a hint at this, too, in the form of Kan extensions. In category terms they look like:</p>
<pre>
  p : C -> C'
  f : C -> D
  Ran p f : C' -> D
  Lan p f : C' -> D

  Ran p f c' = end (c : C). Hom_C'(c', p c) ⇒ f c
  Lan p f c' = coend (c : c). Hom_C'(p c, c') ⊗ f c
</pre>
<p>where <code>⇒</code> is a "power" and <code>⊗</code> is a copower, which are like being able to take exponentials and products by sets (or whatever the objects of the hom category are), instead of other objects within the category. Ends and coends are like universal and existential quantifiers (as are limits and colimits, but ends and coends involve mixed-variance).</p>
<p>Some handy theorems relate Kan extensions and adjoint functors:</p>
<pre>
  if L ⊣ R
  then L = Ran R Id and R = Lan L Id

  if Ran R Id exists and is absolute
  then Ran R Id ⊣ R

  if Lan L Id exists and is absolute
  then L ⊣ Lan L Id

  Kan P F is absolute iff forall G. (G . Kan P F) ~= Kan P (G . F)
</pre>
<p>It turns out we can write down Kan extensions fairly generally in Haskell. Our restricted case is:</p>
<pre class="haskell">&nbsp;
  p = Forget σ :: <span style="color: green;">&#40;</span>k,σ<span style="color: green;">&#41;</span> -&gt; k
  f = Id :: <span style="color: green;">&#40;</span>k,σ<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>k,σ<span style="color: green;">&#41;</span>
&nbsp;
  Free   σ = <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>Forget σ<span style="color: green;">&#41;</span> Id :: k -&gt; <span style="color: green;">&#40;</span>k,σ<span style="color: green;">&#41;</span>
  Cofree σ = <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>Forget σ<span style="color: green;">&#41;</span> Id :: k -&gt; <span style="color: green;">&#40;</span>k,σ<span style="color: green;">&#41;</span>
&nbsp;
  g :: <span style="color: green;">&#40;</span>k,σ<span style="color: green;">&#41;</span> -&gt; j
  g . Free   σ = <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>Forget σ<span style="color: green;">&#41;</span> g
  g . Cofree σ = <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>Forget σ<span style="color: green;">&#41;</span> g
&nbsp;</pre>
<p>As long as the final category is like one of our type constructor categories, ends are universal quantifiers, powers are function types, coends are existential quantifiers and copowers are product spaces. This only breaks down for our purposes when <code>g</code> is contravariant, in which case they are flipped.  For higher kinds, these constructions occur point-wise. So, we can break things down into four general cases, each with cases for each arity:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Ran0 σ p <span style="color: green;">&#40;</span>f :: k -&gt; *<span style="color: green;">&#41;</span> a =
  Ran0 <span style="color: green;">&#123;</span> ran0 :: <span style="color: #06c; font-weight: bold;">forall</span> r. σ r =&gt; <span style="color: green;">&#40;</span>a ~&gt; p r<span style="color: green;">&#41;</span> -&gt; f r <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Ran1 σ p <span style="color: green;">&#40;</span>f :: k -&gt; j -&gt; *<span style="color: green;">&#41;</span> a b =
  Ran1 <span style="color: green;">&#123;</span> ran1 :: <span style="color: #06c; font-weight: bold;">forall</span> r. σ r =&gt; <span style="color: green;">&#40;</span>a ~&gt; p r<span style="color: green;">&#41;</span> -&gt; f r b <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> RanOp0 σ p <span style="color: green;">&#40;</span>f :: k -&gt; *<span style="color: green;">&#41;</span> a =
  <span style="color: #06c; font-weight: bold;">forall</span> e. σ e =&gt; RanOp0 <span style="color: green;">&#40;</span>a ~&gt; p e<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f e<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Lan0 σ p <span style="color: green;">&#40;</span>f :: k -&gt; *<span style="color: green;">&#41;</span> a =
  <span style="color: #06c; font-weight: bold;">forall</span> e. σ e =&gt; Lan0 <span style="color: green;">&#40;</span>p e ~&gt; a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f e<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Lan1 σ p <span style="color: green;">&#40;</span>f :: k -&gt; j -&gt; *<span style="color: green;">&#41;</span> a b =
  <span style="color: #06c; font-weight: bold;">forall</span> e. σ e =&gt; Lan1 <span style="color: green;">&#40;</span>p e ~&gt; a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f e b<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> LanOp0 σ p <span style="color: green;">&#40;</span>f :: k -&gt; *<span style="color: green;">&#41;</span> a =
  LanOp0 <span style="color: green;">&#123;</span> lan0 :: <span style="color: #06c; font-weight: bold;">forall</span> r. σ r =&gt; <span style="color: green;">&#40;</span>p r -&gt; a<span style="color: green;">&#41;</span> -&gt; f r <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;</pre>
<p>The more specific proposed (co)free definitions are:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> family Free   :: <span style="color: green;">&#40;</span>k -&gt; Constraint<span style="color: green;">&#41;</span> -&gt; k -&gt; k
<span style="color: #06c; font-weight: bold;">type</span> family Cofree :: <span style="color: green;">&#40;</span>k -&gt; Constraint<span style="color: green;">&#41;</span> -&gt; k -&gt; k
&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Free0 σ a = Free0 <span style="color: green;">&#123;</span> gratis0 :: <span style="color: #06c; font-weight: bold;">forall</span> r. σ r =&gt; <span style="color: green;">&#40;</span>a ~&gt; r<span style="color: green;">&#41;</span> -&gt; r <span style="color: green;">&#125;</span>
<span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">instance</span> Free = Free0
&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Free1 σ f a = Free1 <span style="color: green;">&#123;</span> gratis1 :: <span style="color: #06c; font-weight: bold;">forall</span> g. σ g =&gt; <span style="color: green;">&#40;</span>f ~&gt; g<span style="color: green;">&#41;</span> -&gt; g a <span style="color: green;">&#125;</span>
<span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">instance</span> Free = Free1
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Cofree0 σ a = <span style="color: #06c; font-weight: bold;">forall</span> e. σ e =&gt; Cofree0 <span style="color: green;">&#40;</span>e ~&gt; a<span style="color: green;">&#41;</span> e
<span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">instance</span> Cofree = Cofree0
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Cofree1 σ f a = <span style="color: #06c; font-weight: bold;">forall</span> g. σ g =&gt; Cofree1 <span style="color: green;">&#40;</span>g ~&gt; f<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">instance</span> Cofree = Cofree1
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;</pre>
<p>We can define some handly classes and instances for working with these types, several of which generalize existing Haskell concepts:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Covariant <span style="color: green;">&#40;</span>f :: i -&gt; j<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  comap :: <span style="color: green;">&#40;</span>a ~&gt; b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f a ~&gt; f b<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Contravariant f <span style="color: #06c; font-weight: bold;">where</span>
  contramap :: <span style="color: green;">&#40;</span>b ~&gt; a<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f a ~&gt; f b<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Covariant m =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>m :: i -&gt; i<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure :: a ~&gt; m a
  join :: m <span style="color: green;">&#40;</span>m a<span style="color: green;">&#41;</span> ~&gt; m a
&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Covariant w =&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> <span style="color: green;">&#40;</span>w :: i -&gt; i<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> :: w a ~&gt; a
  split :: w a ~&gt; w <span style="color: green;">&#40;</span>w a<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Couniversal σ f | f -&gt; σ <span style="color: #06c; font-weight: bold;">where</span>
  couniversal :: σ r =&gt; <span style="color: green;">&#40;</span>a ~&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f a ~&gt; r<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Universal σ f | f -&gt; σ <span style="color: #06c; font-weight: bold;">where</span>
  universal :: σ e =&gt; <span style="color: green;">&#40;</span>e ~&gt; a<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>e ~&gt; f a<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Covariant <span style="color: green;">&#40;</span>Free0 σ<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  comap f <span style="color: green;">&#40;</span>Free0 e<span style="color: green;">&#41;</span> = Free0 <span style="color: green;">&#40;</span>e . <span style="color: green;">&#40;</span>.f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://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>Free0 σ<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure x = Free0 $ \k -&gt; k x
  join <span style="color: green;">&#40;</span>Free0 e<span style="color: green;">&#41;</span> = Free0 $ \k -&gt; e $ \<span style="color: green;">&#40;</span>Free0 e<span style="color: green;">&#41;</span> -&gt; e k
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Couniversal σ <span style="color: green;">&#40;</span>Free0 σ<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  couniversal h <span style="color: green;">&#40;</span>Free0 e<span style="color: green;">&#41;</span> = e h
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;</pre>
<p>The only unfamiliar classes here should be <code>(Co)Universal</code>. They are for witnessing the adjunctions that make <code>Free σ</code> the initial <code>σ</code> and <code>Cofree σ</code> the final <code>σ</code> in the relevant way. Only one direction is given, since the opposite is very easy to construct with the (co)monad structure.</p>
<p><code>Free σ</code> is a monad and couniversal, <code>Cofree σ</code> is a comonad and universal.</p>
<p>We can now try to convince ourselves that <code>Free σ</code> and <code>Cofree σ</code> are absolute Here are some examples:</p>
<pre class="haskell">&nbsp;
free0Absolute0 :: <span style="color: #06c; font-weight: bold;">forall</span> g σ a. <span style="color: green;">&#40;</span>Covariant g, σ <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
               =&gt; g <span style="color: green;">&#40;</span>Free0 σ a<span style="color: green;">&#41;</span> &lt; -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> σ Forget g a
free0Absolute0 = <span style="color: green;">&#40;</span>l, r<span style="color: green;">&#41;</span>
 <span style="color: #06c; font-weight: bold;">where</span>
 l :: g <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span> -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> σ Forget g a
 l g = Ran0 $ \k -&gt; comap <span style="color: green;">&#40;</span>couniversal $ remember0 . k<span style="color: green;">&#41;</span> g
&nbsp;
 r :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> σ Forget g a -&gt; g <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span>
 r <span style="color: green;">&#40;</span>Ran0 e<span style="color: green;">&#41;</span> = e $ Forget0 . pure
&nbsp;
free0Absolute1 :: <span style="color: #06c; font-weight: bold;">forall</span> <span style="color: green;">&#40;</span>g :: * -&gt; * -&gt; *<span style="color: green;">&#41;</span> σ a x. <span style="color: green;">&#40;</span>Covariant g, σ <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
               =&gt; g <span style="color: green;">&#40;</span>Free0 σ a<span style="color: green;">&#41;</span> x &lt; -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> σ Forget g a x
free0Absolute1 = <span style="color: green;">&#40;</span>l, r<span style="color: green;">&#41;</span>
 <span style="color: #06c; font-weight: bold;">where</span>
 l :: g <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span> x -&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> σ Forget g a x
 l g = Ran1 $ \k -&gt; comap <span style="color: green;">&#40;</span>couniversal $ remember0 . k<span style="color: green;">&#41;</span> $$ g
&nbsp;
 r :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> σ Forget g a x -&gt; g <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span> x
 r <span style="color: green;">&#40;</span>Ran1 e<span style="color: green;">&#41;</span> = e $ Forget0 . pure
&nbsp;
free0Absolute0Op :: <span style="color: #06c; font-weight: bold;">forall</span> g σ a. <span style="color: green;">&#40;</span>Contravariant g, σ <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
                 =&gt; g <span style="color: green;">&#40;</span>Free0 σ a<span style="color: green;">&#41;</span> &lt; -&gt; RanOp σ Forget g a
free0Absolute0Op = <span style="color: green;">&#40;</span>l, r<span style="color: green;">&#41;</span>
 <span style="color: #06c; font-weight: bold;">where</span>
 l :: g <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span> -&gt; RanOp σ Forget g a
 l = RanOp0 $ Forget0 . pure
&nbsp;
 r :: RanOp σ Forget g a -&gt; g <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span>
 r <span style="color: green;">&#40;</span>RanOp0 h g<span style="color: green;">&#41;</span> = contramap <span style="color: green;">&#40;</span>couniversal $ remember0 . h<span style="color: green;">&#41;</span> g
&nbsp;
<span style="color: #5d478b; font-style: italic;">-- ...</span>
&nbsp;</pre>
<p>As can be seen, the definitions share a lot of structure. I'm quite confident that with the right building blocks these could be defined once for each of the four types of Kan extensions, with types like:</p>
<pre class="haskell">&nbsp;
freeAbsolute
  :: <span style="color: #06c; font-weight: bold;">forall</span> g σ a. <span style="color: green;">&#40;</span>Covariant g, σ <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  =&gt; g <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span> &lt; ~&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Ran"><span style="background-color: #efefbf; font-weight: bold;">Ran</span></a> σ Forget g a
&nbsp;
cofreeAbsolute
  :: <span style="color: #06c; font-weight: bold;">forall</span> g σ a. <span style="color: green;">&#40;</span>Covariant g, σ <span style="color: green;">&#40;</span>Cofree σ a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  =&gt; g <span style="color: green;">&#40;</span>Cofree σ a<span style="color: green;">&#41;</span> &lt; ~&gt; <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Functor-KanExtension.html#t:Lan"><span style="background-color: #efefbf; font-weight: bold;">Lan</span></a> σ Forget g a
&nbsp;
freeAbsoluteOp
  :: <span style="color: #06c; font-weight: bold;">forall</span> g σ a. <span style="color: green;">&#40;</span>Contravariant g, σ <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  =&gt; g <span style="color: green;">&#40;</span>Free σ a<span style="color: green;">&#41;</span> &lt; ~&gt; RanOp σ Forget g a
&nbsp;
cofreeAbsoluteOp
  :: <span style="color: #06c; font-weight: bold;">forall</span> g σ a. <span style="color: green;">&#40;</span>Contravariant g, σ <span style="color: green;">&#40;</span>Cofree σ a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
  =&gt; g <span style="color: green;">&#40;</span>Cofree σ a<span style="color: green;">&#41;</span> &lt; ~&gt; LanOp σ Forget g a
&nbsp;</pre>
<p>However, it seems quite difficult to structure things in a way such that GHC will accept the definitions. I've successfully written <code>freeAbsolute</code> using some axioms, but turning those axioms into class definitions and the like seems impossible.</p>
<p>Anyhow, the punchline is that we can prove absoluteness using only the premise that there is a valid <code>σ</code> instance for <code>Free σ</code> and <code>Cofree σ</code>. This tends to be quite easy; we just borrow the structure of the type we are quantifying over. This means that in all these cases, we are justified in saying that <code>Free σ ⊣ Forget σ ⊣ Cofree σ</code>, and we have a very generic presentations of (co)free structures in Haskell. So let's look at some.</p>
<p>We've already seen <code>Free Monoid</code>, and last time we talked about <code>Free Applicative</code>, and its relation to traversals. But, <code>Applicative</code> is to traversal as <code>Functor</code> is to lens, so it may be interesting to consider constructions on that. Both <code>Free Functor</code> and <code>Cofree Functor</code> make <code>Functor</code>s:</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>Free1 <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> <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>Free1 e<span style="color: green;">&#41;</span> = Free1 $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f . e
&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>Cofree1 <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> <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>Cofree1 h e<span style="color: green;">&#41;</span> = Cofree1 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> f e<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>And of course, they are (co)monads, covariant functors and (co)universal among <code>Functor</code>s. But, it happens that I know some other types with these properties:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> CoYo f a = <span style="color: #06c; font-weight: bold;">forall</span> e. CoYo <span style="color: green;">&#40;</span>e -&gt; a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f e<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Covariant CoYo <span style="color: #06c; font-weight: bold;">where</span>
  comap f = Transform $ \<span style="color: green;">&#40;</span>CoYo h e<span style="color: green;">&#41;</span> -&gt; CoYo h <span style="color: green;">&#40;</span>f $$ e<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> CoYo <span style="color: #06c; font-weight: bold;">where</span>
  pure = Transform $ CoYo <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
  join = Transform $ \<span style="color: green;">&#40;</span>CoYo h <span style="color: green;">&#40;</span>CoYo h' e<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt; CoYo <span style="color: green;">&#40;</span>h . h'<span style="color: green;">&#41;</span> e
&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>CoYo f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>CoYo h e<span style="color: green;">&#41;</span> = CoYo <span style="color: green;">&#40;</span>f . h<span style="color: green;">&#41;</span> e
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Couniversal <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> CoYo <span style="color: #06c; font-weight: bold;">where</span>
  couniversal tr = Transform $ \<span style="color: green;">&#40;</span>CoYo h e<span style="color: green;">&#41;</span> -&gt; <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>tr $$ e<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Yo f a = Yo <span style="color: green;">&#123;</span> oy :: <span style="color: #06c; font-weight: bold;">forall</span> r. <span style="color: green;">&#40;</span>a -&gt; r<span style="color: green;">&#41;</span> -&gt; f r <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Covariant Yo <span style="color: #06c; font-weight: bold;">where</span>
  comap f = Transform $ \<span style="color: green;">&#40;</span>Yo e<span style="color: green;">&#41;</span> -&gt; Yo $ <span style="color: green;">&#40;</span>f $$<span style="color: green;">&#41;</span> . e
&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> Yo <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> = Transform $ \<span style="color: green;">&#40;</span>Yo e<span style="color: green;">&#41;</span> -&gt; e <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
  split = Transform $ \<span style="color: green;">&#40;</span>Yo e<span style="color: green;">&#41;</span> -&gt; Yo $ \k -&gt; Yo $ \k' -&gt; e $ k' . k
&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>Yo f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Yo e<span style="color: green;">&#41;</span> = Yo $ \k -&gt; e <span style="color: green;">&#40;</span>k . f<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Universal <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> Yo <span style="color: #06c; font-weight: bold;">where</span>
  universal tr = Transform $ \e -&gt; Yo $ \k -&gt; tr $$ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> k e
&nbsp;</pre>
<p>These are the types involved in the (co-)Yoneda lemma. <code>CoYo</code> is a monad, couniversal among functors, and <code>CoYo f</code> is a <code>Functor</code>. <code>Yo</code> is a comonad, universal among functors, and is always a <code>Functor</code>. So, are these equivalent types?</p>
<pre class="haskell">&nbsp;
coyoIso :: CoYo &lt; ~&gt; Free <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>
coyoIso = <span style="color: green;">&#40;</span>Transform $ couniversal pure, Transform $ couniversal pure<span style="color: green;">&#41;</span>
&nbsp;
yoIso :: Yo &lt; ~&gt; Cofree <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>
yoIso = <span style="color: green;">&#40;</span>Transform $ universal <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>, Transform $ universal <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Indeed they are. And similar identities hold for the contravariant versions of these constructions.</p>
<p>I don't have much of a use for this last example. I suppose to be perfectly precise, I should point out that these uses of <code>(Co)Yo</code> are not actually part of the (co-)Yoneda lemma. They are two different constructions.  The (co-)Yoneda lemma can be given in terms of Kan extensions as:</p>
<pre class="haskell">&nbsp;
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> Id f &lt; ~&gt; f
&nbsp;
coyoneda :: <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> Id f &lt; ~&gt; f
&nbsp;</pre>
<p>But, the use of <code>(Co)Yo</code> to make <code>Functor</code>s out of things that aren't necessarily is properly thought of in other terms. In short, we have some kind of category of Haskell types with only identity arrows---it is discrete. Then any type constructor, even non-functorial ones, is certainly a functor from said category (call it Haskrete) into the normal one (Hask). And there is an inclusion functor from Haskrete into Hask:</p>
<pre>
             F
 Haskrete -----> Hask
      |        /|
      |       /
      |      /
Incl  |     /
      |    /  Ran/Lan Incl F
      |   /
      |  /
      v /
    Hask
</pre>
<p>So, <code>(Co)Free Functor</code> can also be thought of in terms of these Kan extensions involving the discrete category.</p>
<p>To see more fleshed out, loadable versions of the code in this post, see <a href="http://code.haskell.org/~dolio/haskell-share/categories-of-structures/COS.hs">this file</a>. I may also try a similar Agda development at a later date, as it may admit the more general absoluteness constructions easier.</p>
<p>[0]: The reason for restricting ourselves to kinds involving only <code>*</code> and <code>(->)</code> is that they work much more simply than data kinds. Haskell values can't depend on type-level entities without using type classes. For *, this is natural, but for something like <code>Bool -> *</code>, it is more natural for transformations to be able to inspect the booleans, and so should be something more like <code>forall b. InspectBool b => f b -> g b</code>.</p>
<p>[1]: First-class types are what you get by removing type families and synonyms from consideration. The reason for doing so is that these can't be used properly as parameters and the like, except in cases where they reduce to some other type that is first-class. For example, if we define:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> I a = a
&nbsp;</pre>
<p>even though GHC will report <code>I :: * -> *</code>, it is not legal to write <code>Transform I I</code>.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2015/categories-of-structures-in-haskell/feed/</wfw:commentRss>
		<slash:comments>510</slash:comments>
		</item>
		<item>
		<title>Unnatural Transformations and Quantifiers</title>
		<link>http://comonad.com/reader/2012/unnatural-transformations-and-quantifiers/</link>
		<comments>http://comonad.com/reader/2012/unnatural-transformations-and-quantifiers/#comments</comments>
		<pubDate>Sun, 23 Sep 2012 03:43:13 +0000</pubDate>
		<dc:creator>Dan Doel</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=660</guid>
		<description><![CDATA[Recently, a fellow in category land discovered a fact that we in Haskell land have actually known for a while (in addition to things most of us probably don't). Specifically, given two categories  and , a functor , and provided some conditions in  hold, there exists a monad , the codensity monad of [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, a fellow in category land <a href="http://golem.ph.utexas.edu/category/2012/09/where_do_monads_come_from.html">discovered</a> a fact that we in Haskell land have actually known for a while (in addition to things most of us probably don't). Specifically, given two categories <img src='http://comonad.com/latex/db5f7b3e9934fbc5a2859d88c4ba84a3.png' title='$\mathcal{C}$' alt='$\mathcal{C}$' align=absmiddle> and <img src='http://comonad.com/latex/eaf85f2b753a4c7585def4cc7ecade43.png' title='$\mathcal{D}$' alt='$\mathcal{D}$' align=absmiddle>, a functor <img src='http://comonad.com/latex/28408c9aaded61e50623807633e3ce37.png' title='$G : \mathcal{C} \rightarrow \mathcal{D}$' alt='$G : \mathcal{C} \rightarrow \mathcal{D}$' align=absmiddle>, and provided some conditions in <img src='http://comonad.com/latex/eaf85f2b753a4c7585def4cc7ecade43.png' title='$\mathcal{D}$' alt='$\mathcal{D}$' align=absmiddle> hold, there exists a monad <img src='http://comonad.com/latex/e049fb90e6d941ff5046ca1c48041c8b.png' title='$T^G$' alt='$T^G$' align=absmiddle>, the codensity monad of <img src='http://comonad.com/latex/5201385589993766eea584cd3aa6fa13.png' title='$G$' alt='$G$' align=absmiddle>.</p>
<p>In category theory, the codensity monad is given by the rather frightening expression:</p>
<p><img src='http://comonad.com/latex/050bb5034bed82159df4c52c89c07f3c.png' title='$ T^G(a) = \int_r \left[\mathcal{D}(a, Gr), Gr\right] $' alt='$ T^G(a) = \int_r \left[\mathcal{D}(a, Gr), Gr\right] $' align=absmiddle></p>
<p><span id="more-660"></span></p>
<p>Where the integral notation denotes an <a href="http://comonad.com/reader/2008/kan-extension-iii/">end</a>, and the square brackets denote a <a href="http://nlab.mathforge.org/nlab/show/power">power</a>, which allows us to take what is essentially an exponential of the objects of <img src='http://comonad.com/latex/eaf85f2b753a4c7585def4cc7ecade43.png' title='$\mathcal{D}$' alt='$\mathcal{D}$' align=absmiddle> by objects of <img src='http://comonad.com/latex/76105ebc974ce8a02de91bcaf0d6d25f.png' title='$\mathcal{V}$' alt='$\mathcal{V}$' align=absmiddle>, where <img src='http://comonad.com/latex/eaf85f2b753a4c7585def4cc7ecade43.png' title='$\mathcal{D}$' alt='$\mathcal{D}$' align=absmiddle> is <a href="http://nlab.mathforge.org/nlab/show/enriched+category">enriched</a> in <img src='http://comonad.com/latex/76105ebc974ce8a02de91bcaf0d6d25f.png' title='$\mathcal{V}$' alt='$\mathcal{V}$' align=absmiddle>. Provided the above end exists, <img src='http://comonad.com/latex/e049fb90e6d941ff5046ca1c48041c8b.png' title='$T^G$' alt='$T^G$' align=absmiddle> is a monad regardless of whether <img src='http://comonad.com/latex/5201385589993766eea584cd3aa6fa13.png' title='$G$' alt='$G$' align=absmiddle> has an <a href="http://comonad.com/reader/2008/kan-extensions-ii/">adjoint</a>, which is the usual way one thinks of functors (in general) giving rise to monads.</p>
<p>It also turns out that this construction is a sort of generalization of the adjunction case. If we do have <img src='http://comonad.com/latex/754907e967821ca061438630f9c72a7d.png' title='$F \dashv G$' alt='$F \dashv G$' align=absmiddle>, this gives rise to a monad <img src='http://comonad.com/latex/a095e64d5e4cfbbc3f2bdfd533130212.png' title='$GF$' alt='$GF$' align=absmiddle>. But, in such a case, <img src='http://comonad.com/latex/1e0adde1d1e9eba3705ea3cd2880c6f8.png' title='$T^G \cong GF$' alt='$T^G \cong GF$' align=absmiddle>, so the codensity monad is the same as the monad given by the adjunction when it exists, but codensity may exist when there is no adjunction.</p>
<p>In Haskell, this all becomes a bit simpler (to my eyes, at least). Our category <img src='http://comonad.com/latex/eaf85f2b753a4c7585def4cc7ecade43.png' title='$\mathcal{D}$' alt='$\mathcal{D}$' align=absmiddle> is always <img src='http://comonad.com/latex/129cf6e597bd76a4da1b575b1fa73b20.png' title='$\mathbf{Hask}$' alt='$\mathbf{Hask}$' align=absmiddle>, which is enriched in itself, so powers are just function spaces. And all the functors we write will be rather like <img src='http://comonad.com/latex/129cf6e597bd76a4da1b575b1fa73b20.png' title='$\mathbf{Hask}$' alt='$\mathbf{Hask}$' align=absmiddle> (objects will come from kinds we can quantify over), so ends of functors will look like <code>forall r. F r r</code> where <img src='http://comonad.com/latex/b075975319f2e91538b5f7f577347d83.png' title='$F : \mathcal{C}^{op} \times \mathcal{C} \rightarrow \mathbf{Hask}$' alt='$F : \mathcal{C}^{op} \times \mathcal{C} \rightarrow \mathbf{Hask}$' align=absmiddle>. Then:<br />
<code><br />
newtype Codensity f a = Codensity (forall r. (a -> f r) -> f r)<br />
</code></p>
<p>As mentioned, we've known for a while that we can write a Monad instance for <code>Codensity f</code> without caring at all about <code>f</code>.</p>
<p>As for the adjunction correspondence, consider the adjunction between products and exponentials: <img src='http://comonad.com/latex/179c9a295a34edbdbd4b2f184a62cdc9.png' title='$ - \times S \dashv S \rightarrow - $' alt='$ - \times S \dashv S \rightarrow - $' align=absmiddle></p>
<p>This gives rise to the monad <img src='http://comonad.com/latex/4da4a1547d8498791e0069e7616d7040.png' title='$S \rightarrow (- \times S)$' alt='$S \rightarrow (- \times S)$' align=absmiddle>, the state monad. According to the facts above, we should have that <code>Codensity (s ->)</code> (excuse the sectioning) is the same as state, and if we look, we see:<br />
<code><br />
forall r. (a -> s -> r) -> s -> r<br />
</code></p>
<p>which is the continuation passing, or Church (or <a href="http://comments.gmane.org/gmane.comp.lang.haskell.cafe/100508">Boehm-Berarducci</a>) encoding of the monad.</p>
<p>Now, it's also well known that for any monad, we can construct an adjunction that gives rise to it. There are multiple ways to do this, but the most accessible in Haskell is probably via the Kleisli category. So, given a monad <img src='http://comonad.com/latex/fb97d38bcc19230b0acd442e17db879c.png' title='$M$' alt='$M$' align=absmiddle> on <img src='http://comonad.com/latex/129cf6e597bd76a4da1b575b1fa73b20.png' title='$\mathbf{Hask}$' alt='$\mathbf{Hask}$' align=absmiddle>, there is a category <img src='http://comonad.com/latex/a4b150035aa58ceef406ef607d2c3c70.png' title='$\mathbf{Hask}_M$' alt='$\mathbf{Hask}_M$' align=absmiddle> with the same objects, but where <img src='http://comonad.com/latex/bc31ad3fd58dd9ca8691a1719354e0fb.png' title='$\mathbf{Hask}_M(a, b) = \mathbf{Hask}(a, Mb)$' alt='$\mathbf{Hask}_M(a, b) = \mathbf{Hask}(a, Mb)$' align=absmiddle>. The identity for each object is <code>return</code> and composition of arrows is:<br />
<code><br />
(f >=> g) x = f x >>= g<br />
</code></p>
<p>Our two functors are:<br />
<code><br />
F a = a<br />
F f = return . f</p>
<p>U a = M a<br />
U f = (>>= f)<br />
</code></p>
<p>Verifying that <img src='http://comonad.com/latex/388ff8dfabfc1466d587e51adb83212a.png' title='$F \dashv U$' alt='$F \dashv U$' align=absmiddle> requires only that <img src='http://comonad.com/latex/1f96b28abbe86107fdb6e1a8ffe2ea35.png' title='$\mathbf{Hask}_M(F-, =) \cong \mathbf{Hask}(-, U\!\!=)$' alt='$\mathbf{Hask}_M(F-, =) \cong \mathbf{Hask}(-, U\!\!=)$' align=absmiddle>, but this is just <img src='http://comonad.com/latex/d29fe5c1dc21ef08d41e2b5f780f1521.png' title='$\mathbf{Hask}(-, M\!\!=) \cong \mathbf{Hask}(-, M\!\!=)$' alt='$\mathbf{Hask}(-, M\!\!=) \cong \mathbf{Hask}(-, M\!\!=)$' align=absmiddle>, which is a triviality. Now we should have that <img src='http://comonad.com/latex/bf2765813f7499243599cc3bf3e7f73b.png' title='$T^U = M$' alt='$T^U = M$' align=absmiddle>.</p>
<p>So, one of the simplest monads is reader, <img src='http://comonad.com/latex/0b94f1fc58a44d88f75b94e136f017db.png' title='$(e \rightarrow)$' alt='$(e \rightarrow)$' align=absmiddle>. Now, <img src='http://comonad.com/latex/6bac6ec50c01592407695ef84f457232.png' title='$U$' alt='$U$' align=absmiddle> just takes objects in the Kleisli category (which are objects in <img src='http://comonad.com/latex/129cf6e597bd76a4da1b575b1fa73b20.png' title='$\mathbf{Hask}$' alt='$\mathbf{Hask}$' align=absmiddle>) and applies <img src='http://comonad.com/latex/fb97d38bcc19230b0acd442e17db879c.png' title='$M$' alt='$M$' align=absmiddle> to them, so we should have <code>Codensity (e ->)</code> is reader. But earlier we had <code>Codensity (e ->)</code> was state. So reader is state, right?</p>
<p>We can actually arrive at this result another way. One of the most famous pieces of category theory is the <a href="http://blog.sigfpe.com/2006/11/yoneda-lemma.html">Yoneda lemma</a>, which states that the following correspondence holds for any functor <img src='http://comonad.com/latex/d15d65be74350891964d514d80d23f4e.png' title='$F : \mathcal{C} \rightarrow \mathbf{Set}$' alt='$F : \mathcal{C} \rightarrow \mathbf{Set}$' align=absmiddle>:</p>
<p><img src='http://comonad.com/latex/291bd125d994fd0c7d00a147403dc44e.png' title='$ Fa \,\, \cong \, \mathbf{Set}^\mathcal{C}\left(C(a,-), F\right) $' alt='$ Fa \,\, \cong \, \mathbf{Set}^\mathcal{C}\left(C(a,-), F\right) $' align=absmiddle></p>
<p>This also works for any functor into <img src='http://comonad.com/latex/129cf6e597bd76a4da1b575b1fa73b20.png' title='$\mathbf{Hask}$' alt='$\mathbf{Hask}$' align=absmiddle> and looks like:<br />
<code><br />
F a ~= forall r. (a -> r) -> F r<br />
</code></p>
<p>for <img src='http://comonad.com/latex/e426801111acba9fcbd11a4bde602af4.png' title='$F : \mathbf{Hask} \rightarrow \mathbf{Hask}$' alt='$F : \mathbf{Hask} \rightarrow \mathbf{Hask}$' align=absmiddle>. But we also have our functor <img src='http://comonad.com/latex/d721b9a42081d5f73eec6b96d40c8f87.png' title='$U : \mathbf{Hask}_M \rightarrow \mathbf{Hask}$' alt='$U : \mathbf{Hask}_M \rightarrow \mathbf{Hask}$' align=absmiddle>, which should look more like:</p>
<p><code> U a ~= forall r. (a -> M r) -> U r<br />
M a ~= forall r. (a -> M r) -> M r</code></p>
<p>So, we fill in <code>M = (e ->)</code> and get that reader is isomorphic to state, right? What's going on?</p>
<p>To see, we have to take a closer look at natural transformations. Given two categories <img src='http://comonad.com/latex/db5f7b3e9934fbc5a2859d88c4ba84a3.png' title='$\mathcal{C}$' alt='$\mathcal{C}$' align=absmiddle> and <img src='http://comonad.com/latex/eaf85f2b753a4c7585def4cc7ecade43.png' title='$\mathcal{D}$' alt='$\mathcal{D}$' align=absmiddle>, and functors <img src='http://comonad.com/latex/f9715681e693462be2b2901abbdce20e.png' title='$F, G : \mathcal{C} \rightarrow \mathcal{D}$' alt='$F, G : \mathcal{C} \rightarrow \mathcal{D}$' align=absmiddle>, a natural transformation <img src='http://comonad.com/latex/08bda09160c0fde7f63da195d07031c3.png' title='$\phi : F \Rightarrow G$' alt='$\phi : F \Rightarrow G$' align=absmiddle> is a family of maps <img src='http://comonad.com/latex/86b3a786efd28fc240d095754564a874.png' title='$\phi_a : Fa \rightarrow Ga$' alt='$\phi_a : Fa \rightarrow Ga$' align=absmiddle> such that for every <img src='http://comonad.com/latex/78c2fecc46b4ab88b04b97e64cc513f7.png' title='$f : a \rightarrow b$' alt='$f : a \rightarrow b$' align=absmiddle> the following diagram commutes:</p>
<div style="text-align: center"><img src='http://comonad.com/latex/f3b765d571311e2ac37cb7a4d5c849d6.png' title='$ \bfig \square&amp;lt;1000,1000&gt;[Fa`Ga`Fb`Gb;\phi_a`Ff`Gf`\phi_b]\efig $' alt='$ \bfig \square&amp;lt;1000,1000&gt;[Fa`Ga`Fb`Gb;\phi_a`Ff`Gf`\phi_b]\efig $' align=absmiddle></div>
<p>The key piece is what the morphisms look like. It's well known that parametricity ensures the naturality of <code>t :: forall a. F a -> G a</code> for <img src='http://comonad.com/latex/764d49adf41244778f7b1f65677bd4ec.png' title='$F, G : \mathbf{Hask} \rightarrow \mathbf{Hask}$' alt='$F, G : \mathbf{Hask} \rightarrow \mathbf{Hask}$' align=absmiddle>, and it also works when the source is <img src='http://comonad.com/latex/142c3f0a398b3921283c65dba9b426f6.png' title='$\mathbf{Hask}^{op}$' alt='$\mathbf{Hask}^{op}$' align=absmiddle>. It should also work for a category, call it <img src='http://comonad.com/latex/b7581780b90f85bba660172715c3991e.png' title='$\mathbf{Hask}^{\sim}$' alt='$\mathbf{Hask}^{\sim}$' align=absmiddle>, which has Haskell types as objects, but where <img src='http://comonad.com/latex/90c1cbbbf7ae5d1def60bc7bd8600cc1.png' title='$\mathbf{Hask}^{\sim}(a, b) = \mathbf{Hask}(a, b) \times \mathbf{Hask}(b, a)$' alt='$\mathbf{Hask}^{\sim}(a, b) = \mathbf{Hask}(a, b) \times \mathbf{Hask}(b, a)$' align=absmiddle>, which is the sort of category that <code>newtype Endo a = Endo (a -> a)</code> is a functor from. So we should be at liberty to say:<br />
<code><br />
Codensity Endo a = forall r. (a -> r -> r) -> r -> r ~= [a]<br />
</code></p>
<p>However, hom types for <img src='http://comonad.com/latex/a4b150035aa58ceef406ef607d2c3c70.png' title='$\mathbf{Hask}_M$' alt='$\mathbf{Hask}_M$' align=absmiddle> are not merely made up of <img src='http://comonad.com/latex/129cf6e597bd76a4da1b575b1fa73b20.png' title='$\mathbf{Hask}$' alt='$\mathbf{Hask}$' align=absmiddle> hom types on the same arguments, so naturality turns out not to be guaranteed. A functor <img src='http://comonad.com/latex/46cde8a293393bfb788e2146a377dfd6.png' title='$F : \mathbf{Hask}_M \rightarrow \mathbf{Hask}$' alt='$F : \mathbf{Hask}_M \rightarrow \mathbf{Hask}$' align=absmiddle> must take a Kleisli arrow <img src='http://comonad.com/latex/4f2fe22635b432c01d95ba33d4fc994e.png' title='$f : b \rightarrow Mc$' alt='$f : b \rightarrow Mc$' align=absmiddle> to an arrow <img src='http://comonad.com/latex/ec40c947207bed2928a683a7a8014fb7.png' title='$Ff : Fb \rightarrow Fc$' alt='$Ff : Fb \rightarrow Fc$' align=absmiddle>, and transformations must commute with that mapping. So, if we look at our use of Yoneda, we are considering transformations <img src='http://comonad.com/latex/47051979f30f700aee1fda6eab3554f3.png' title='$\phi : \mathbf{Hask}_M(a, -) \Rightarrow U$' alt='$\phi : \mathbf{Hask}_M(a, -) \Rightarrow U$' align=absmiddle>:</p>
<div style="text-align: center"><img src='http://comonad.com/latex/b2ed6d7df91f89030039a41b41533753.png' title='$ \bfig\square&amp;lt;1000,1000&gt;[\mathbf{Hask}_M(a,b)`Ub`\mathbf{Hask}_M(a,c)`Uc;\phi_a`\mathbf{Hask}_M(a,f)`Uf`\phi_h]\efig $' alt='$ \bfig\square&amp;lt;1000,1000&gt;[\mathbf{Hask}_M(a,b)`Ub`\mathbf{Hask}_M(a,c)`Uc;\phi_a`\mathbf{Hask}_M(a,f)`Uf`\phi_h]\efig $' align=absmiddle></div>
<p>Now, <img src='http://comonad.com/latex/7bb5b195ef8bd7e285fdf865d6e658a0.png' title='$\mathbf{Hask}_M(a,b) = \mathbf{Hask}(a, Mb)$' alt='$\mathbf{Hask}_M(a,b) = \mathbf{Hask}(a, Mb)$' align=absmiddle> and <img src='http://comonad.com/latex/9c2c2564bc88a3ea51f03f36675984c1.png' title='$Ub = Mb$' alt='$Ub = Mb$' align=absmiddle>. So</p>
<p><code>t :: forall r. (a -> M r) -> M r</code></p>
<p>will get us the right type of maps. But, the above commutative square corresponds to the condition that for all <code>f :: b -> M c</code>:<br />
<code><br />
t . (>=> f) = (>>= f) . t<br />
</code></p>
<p>So, if we have <code>h :: a -> M b</code>, Kleisli composing it with <code>f</code> and then feeding to <code>t</code> is the same as feeding <code>h</code> to <code>t</code> and then binding the result with <code>f</code>.</p>
<p>Now, if we go back to reader, we can consider the reader morphism:<br />
<code><br />
f = const id :: a -> e -> e<br />
</code></p>
<p>For all relevant <code>m</code> and <code>g</code>, <code> m >>= f = id</code> and <code>g >=> f = f</code>. So the<br />
naturality condition here states that <code>t f = id</code>.</p>
<p>Now, <code>t :: forall r. (a -> e -> r) -> e -> r</code>. The general form of these is state actions (I've split <code>e -> (a, e)</code> into two pieces):</p>
<pre language="haskell">
t f e = f (v e) (st e)
  where
  rd :: e -> a
  st :: e -> e
</pre>
<p>If <code>f = const id</code>, then:</p>
<pre language="haskell">
t (const id) e = st e
 where
 st :: e -> e
</pre>
<p>But our naturality condition states that this must be the identity, so we must have <code>st = id</code>. That is, the naturality condition selects <code>t</code> for which the corresponding state action does not change the state, meaning it is equivalent to a reader action! Presumably the definition of an end (which involves dinaturality) enforces a similar condition, although I won't work through it, as it'd be rather more complicated.</p>
<p>However, we have learned a lesson. Quantifiers do not necessarily enforce (di)naturality for every category with objects of the relevant kind. It is important to look at the hom types, not just the objects .In this case, the point of failure seems to be the common, extra <code>s</code>. Even though the type contains nautral transformations for the similar functors over <img src='http://comonad.com/latex/129cf6e597bd76a4da1b575b1fa73b20.png' title='$\mathbf{Hask}$' alt='$\mathbf{Hask}$' align=absmiddle>, they can (in general) still manipulate the shared parameter in ways that are not natural for the domain in question.</p>
<p>I am unsure of how exactly one could enforce the above condition in (Haskell's) types. For instance, if we consider:</p>
<p><code>forall r m. Monad m => (a -> m r) -> m r</code></p>
<p>This still contains transformations of the form:</p>
<p><code> t k = k a >> k a </code></p>
<p>And for this to be natural would require:</p>
<p><code> (k >=> f) a >> (k >=> f) a = (k a >> k a) >>= f </code></p>
<p>Which is not true for all possible instantiations of f. It seems as though leaving <code>m</code> unconstrained would be sufficient, as all that could happen is <code>t</code> feeding a value to <code>k</code> and yielding the result, but it seems likely to be over-restrictive.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2012/unnatural-transformations-and-quantifiers/feed/</wfw:commentRss>
		<slash:comments>458</slash:comments>
		</item>
		<item>
		<title>Searching Infinity Parametrically</title>
		<link>http://comonad.com/reader/2011/searching-infinity/</link>
		<comments>http://comonad.com/reader/2011/searching-infinity/#comments</comments>
		<pubDate>Sun, 25 Dec 2011 06:19:43 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Type Hackery]]></category>

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

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

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

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

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

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

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

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

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

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

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

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

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