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

<channel>
	<title>The Comonad.Reader &#187; Mathematics</title>
	<atom:link href="http://comonad.com/reader/category/mathematics/feed/" rel="self" type="application/rss+xml" />
	<link>http://comonad.com/reader</link>
	<description>types, (co)monads, substructural logic</description>
	<lastBuildDate>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>Adjoint Triples</title>
		<link>http://comonad.com/reader/2016/adjoint-triples/</link>
		<comments>http://comonad.com/reader/2016/adjoint-triples/#comments</comments>
		<pubDate>Thu, 14 Jan 2016 00:02:33 +0000</pubDate>
		<dc:creator>Dan Doel</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Type Theory]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=1114</guid>
		<description><![CDATA[A common occurrence in category theory is the adjoint triple. This is a pair of adjunctions relating three functors:

F ⊣ G ⊣ H
F ⊣ G, G ⊣ H

Perhaps part of the reason they are so common is that (co)limits form one:

colim ⊣ Δ ⊣ lim

where Δ : C -> C^J is the diagonal functor, which [...]]]></description>
			<content:encoded><![CDATA[<p>A common occurrence in category theory is the <a href="https://ncatlab.org/nlab/show/adjoint+triple">adjoint triple</a>. This is a pair of adjunctions relating three functors:</p>
<pre>
F ⊣ G ⊣ H
F ⊣ G, G ⊣ H
</pre>
<p>Perhaps part of the reason they are so common is that (co)limits form one:</p>
<pre>
colim ⊣ Δ ⊣ lim
</pre>
<p>where <code>Δ : C -> C^J</code> is the diagonal functor, which takes objects in <code>C</code> to the constant functor returning that object. A version of this shows up in Haskell (with some extensions) and dependent type theories, as:</p>
<pre>
∃ ⊣ Const ⊣ ∀
Σ ⊣ Const ⊣ Π
</pre>
<p>where, if we only care about quantifying over a single variable, existential and sigma types can be seen as a left adjoint to a diagonal functor that maps types into constant type families (either over <code>*</code> for the first triple in Haskell, or some other type for the second in a dependently typed language), while universal and pi types can be seen as a right adjoint to the same.</p>
<p>It's not uncommon to see the above information in type theory discussion forums. But, there are a few cute properties and examples of adjoint triples that I haven't really seen come up in such contexts.</p>
<p>To begin, we can compose the two adjunctions involved, since the common functor ensures things match up. By calculating on the hom definition, we can see:</p>
<pre>
Hom(FGA, B)     Hom(GFA, B)
    ~=              ~=
Hom(GA, GB)     Hom(FA, HB)
    ~=              ~=
Hom(A, HGB)     Hom(A, GHB)
</pre>
<p>So there are two ways to compose the adjunctions, giving two induced adjunctions:</p>
<pre>
FG ⊣ HG,  GF ⊣ GH
</pre>
<p>And there is something special about these adjunctions. Note that <code>FG</code> is the comonad for the <code>F ⊣ G</code> adjunction, while <code>HG</code> is the monad for the <code>G ⊣ H</code> adjunction. Similarly, <code>GF</code> is the <code>F ⊣ G</code> monad, and <code>GH</code> is the <code>G ⊣ H</code> comonad. So each adjoint triple gives rise to two adjunctions between monads and comonads.</p>
<p>The second of these has another interesting property. We often want to consider the algebras of a monad, and coalgebras of a comonad. The (co)algebra operations with carrier <code>A</code> have type:</p>
<pre>
alg   : GFA -> A
coalg : A -> GHA
</pre>
<p>but these types are isomorphic according to the <code>GF ⊣ GH</code> adjunction. Thus, one might guess that <code>GF</code> monad algebras are also <code>GH</code> comonad coalgebras, and that in such a situation, we actually have some structure that can be characterized both ways. In fact this is true for any monad left adjoint to a comonad; <a href="#note0">[0]</a> but all adjoint triples give rise to these.</p>
<p>The first adjunction actually turns out to be more familiar for the triple examples above, though. (Edit: <a href="#note2">[2]</a>) If we consider the <code>Σ ⊣ Const ⊣ Π</code> adjunction, where:</p>
<pre>
Σ Π : (A -> Type) -> Type
Const : Type -> (A -> Type)
</pre>
<p>we get:</p>
<pre>
ΣConst : Type -> Type
ΣConst B = A × B
ΠConst : Type -> Type
ΠConst B = A -> B
</pre>
<p>So this is the familiar adjunction:</p>
<pre>
A × - ⊣ A -> -
</pre>
<p>But, there happens to be a triple that is a bit more interesting for both cases. It refers back to categories of functors vs. bare type constructors mentioned in previous posts. So, suppose we have a category called <code>Con</code> whose objects are (partially applied) type constructors (f, g) with kind <code>* -> *</code>, and arrows are polymorphic functions with types like:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">forall</span> x. f x -&gt; g x
&nbsp;</pre>
<p>And let us further imagine that there is a similar category, called <code>Func</code>, except its objects are the things with <code>Functor</code> instances. Now, there is a functor:</p>
<pre>
U : Func -> Con
</pre>
<p>that 'forgets' the functor instance requirement. This functor is in the middle of an adjoint triple:</p>
<pre>
F ⊣ U ⊣ C
F, C : Con -> Func
</pre>
<p>where <code>F</code> creates the free functor over a type constructor, and <code>C</code> creates the cofree functor over a type constructor. These can be written using the types:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> F f a = <span style="color: #06c; font-weight: bold;">forall</span> e. F <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>
<span style="color: #06c; font-weight: bold;">newtype</span> C f a = C <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>and these types will also serve as the types involved in the composite adjunctions:</p>
<pre>
FU ⊣ CU : Func -> Func
UF ⊣ UC : Con -> Con
</pre>
<p>Now, <code>CU</code> is a monad on functors, and the Yoneda lemma tells us that it is actually the identity monad. Similarly, <code>FU</code> is a comonad, and the co-Yoneda lemma tells us that it is the identity comonad (which makes sense, because identity is self-adjoint; and the above is why <code>F</code> and <code>C</code> are often named <code>(Co)Yoneda</code> in Haskell examples).</p>
<p>On the other hand, <code>UF</code> is a <em>monad</em> on type constructors (note, <code>U</code> isn't represented in the Haskell types; <code>F</code> and <code>C</code> just play triple duty, and the constraints on <code>f</code> control what's going on):</p>
<pre class="haskell">&nbsp;
eta :: f a -&gt; F f a
eta = 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;
transform :: <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> x. f x -&gt; g x<span style="color: green;">&#41;</span> -&gt; F f a -&gt; F g a
transform tr <span style="color: green;">&#40;</span>F g x<span style="color: green;">&#41;</span> = F g <span style="color: green;">&#40;</span>tr x<span style="color: green;">&#41;</span>
&nbsp;
mu :: F <span style="color: green;">&#40;</span>F f<span style="color: green;">&#41;</span> a -&gt; F f a
mu <span style="color: green;">&#40;</span>F g <span style="color: green;">&#40;</span>F h x<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> = F <span style="color: green;">&#40;</span>g . h<span style="color: green;">&#41;</span> x
&nbsp;</pre>
<p>and <code>UC</code> is a <em>comonad</em>:</p>
<pre class="haskell">&nbsp;
epsilon :: C f a -&gt; f a
epsilon <span style="color: green;">&#40;</span>C e<span style="color: green;">&#41;</span> = e <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
&nbsp;
transform' :: <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> x. f x -&gt; g x<span style="color: green;">&#41;</span> -&gt; C f a -&gt; C g a
transform' tr <span style="color: green;">&#40;</span>C e<span style="color: green;">&#41;</span> = C <span style="color: green;">&#40;</span>tr . e<span style="color: green;">&#41;</span>
&nbsp;
delta :: C f a -&gt; C <span style="color: green;">&#40;</span>C f<span style="color: green;">&#41;</span> a
delta <span style="color: green;">&#40;</span>C e<span style="color: green;">&#41;</span> = C $ \h -&gt; C $ \g -&gt; e <span style="color: green;">&#40;</span>g . h<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>These are not the identity (co)monad, but this is the case where we have algebras and coalgebras that are equivalent. So, what are the (co)algebras? If we consider <code>UF</code> (and unpack the definitions somewhat):</p>
<pre class="haskell">&nbsp;
alg :: <span style="color: #06c; font-weight: bold;">forall</span> e. <span style="color: green;">&#40;</span>e -&gt; a, f e<span style="color: green;">&#41;</span> -&gt; f a
alg <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>, x<span style="color: green;">&#41;</span> = x
alg <span style="color: green;">&#40;</span>g . h, x<span style="color: green;">&#41;</span> = alg <span style="color: green;">&#40;</span>g, alg <span style="color: green;">&#40;</span>h, x<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and for <code>UC</code>:</p>
<pre class="haskell">&nbsp;
coalg :: f a -&gt; <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
coalg x <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a> = x
coalg x <span style="color: green;">&#40;</span>g . h<span style="color: green;">&#41;</span> = coalg <span style="color: green;">&#40;</span>coalg x h<span style="color: green;">&#41;</span> g
&nbsp;</pre>
<p>in other words, (co)algebra actions of these (co)monads are (mangled) <code>fmap</code> implementations, and the commutativity requirements are exactly what is required to be a law abiding instance. So the (co)algebras are exactly the <code>Functors</code>. <a href="#note1">[1]</a></p>
<p>There are, of course, many other examples of adjoint triples. And further, there are even adjoint quadruples, which in turn give rise to adjoint triples of (co)monads. Hopefully this has sparked some folks' interest in finding and studying more interesting examples.</p>
<p><a name="note0">[0]</a>: Another exmaple is <code>A × - ⊣ A -> -</code> where the <code>A</code> in question is a monoid. (Co)monad (co)algebras of these correspond to actions of the monoid on the carrier set.</p>
<p><a name="note1">[1]</a>: This shouldn't be too surprising, because having a category of (co)algebraic structures that is equivalent to the category of (co)algebras of the (co)monad that comes from the (co)free-forgetful adjunction is the basis for doing algebra in category theory (with (co)monads, at least). However, it is somewhat unusual for a forgetful functor to have both a left and right adjoint. In many cases, something is either algebraic or coalgebraic, and not both.</p>
<p><a name="note2">[2]</a>: Urs Schreiber informed me of an interesting interpretation of the <code>ConstΣ ⊣ ConstΠ</code> adjunction. If you are familiar with modal logic and the possible worlds semantics thereof, you can probably imagine that we could model it using something like <code>P : W -> Type</code>, where <code>W</code> is the type of possible worlds, and propositions are types. Then values of type <code>Σ P</code> demonstrate that <code>P</code> holds in particular worlds, while values of type <code>Π P</code> demonstrate that it holds in all worlds. <code>Const</code> turns these types back into world-indexed 'propositions,' so <code>ConstΣ</code> is the possibility modality and <code>ConstΠ</code> is the necessity modality.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2016/adjoint-triples/feed/</wfw:commentRss>
		<slash:comments>426</slash:comments>
		</item>
		<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>Domains, Sets, Traversals and Applicatives</title>
		<link>http://comonad.com/reader/2015/domains-sets-traversals-and-applicatives/</link>
		<comments>http://comonad.com/reader/2015/domains-sets-traversals-and-applicatives/#comments</comments>
		<pubDate>Wed, 29 Apr 2015 07:36:19 +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[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=994</guid>
		<description><![CDATA[Last time I looked at free monoids, and noticed that in Haskell lists don't really cut it. This is a consequence of laziness and general recursion. To model a language with those properties, one needs to use domains and monotone, continuous maps, rather than sets and total functions (a call-by-value language with general recursion would [...]]]></description>
			<content:encoded><![CDATA[<p>Last time I looked at free monoids, and noticed that in Haskell lists don't really cut it. This is a consequence of laziness and general recursion. To model a language with those properties, one needs to use domains and monotone, continuous maps, rather than sets and total functions (a call-by-value language with general recursion would use domains and strict maps instead).</p>
<p>This time I'd like to talk about some other examples of this, and point out how doing so can (perhaps) resolve some disagreements that people have about the specific cases.</p>
<p>The first example is not one that I came up with: induction. It's sometimes said that Haskell does not have inductive types at all, or that we cannot reason about functions on its data types by induction. However, I think this is (techincally) inaccurate. What's true is that we cannot simply pretend that that our types are sets and use the induction principles for sets to reason about Haskell programs.  Instead, one has to figure out what inductive domains would be, and what their proof principles are.</p>
<p>Fortunately, there are some papers about doing this. The most recent (that I'm aware of) is <a href="http://arxiv.org/pdf/1206.0357.pdf">Generic Fibrational Induction</a>. I won't get too into the details, but it shows how one can talk about induction in a general setting, where one has a category that roughly corresponds to the type theory/programming language, and a second category of proofs that is 'indexed' by the first category's objects. Importantly, it is not required that the second category is somehow 'part of' the type theory being reasoned about, as is often the case with dependent types, although that is also a special case of their construction.</p>
<p>One of the results of the paper is that this framework can be used to talk about induction principles for types that don't make sense as sets. Specifically:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Hyp = Hyp <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>Hyp -&gt; <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><span style="color: green;">&#41;</span> -&gt; <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><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>the type of "hyperfunctions". Instead of interpreting this type as a set, where it would effectively require a set that is isomorphic to the power set of its power set, they interpret it in the category of domains and strict functions mentioned earlier. They then construct the proof category in a similar way as one would for sets, except instead of talking about predicates as sub<i>sets</i>, we talk about sub-<i>domains</i> instead. Once this is done, their framework gives a notion of induction for this type.</p>
<p>This example is suitable for ML (and suchlike), due to the strict functions, and sort of breaks the idea that we can really get away with only thinking about sets, even there. Sets are good enough for some simple examples (like flat domains where we don't care about ⊥), but in general we have to generalize induction itself to apply to all types in the 'good' language.</p>
<p>While I haven't worked out how the generic induction would work out for Haskell, I have little doubt that it would, because ML actually contains all of Haskell's data types (and vice versa). So the fact that the framework gives meaning to induction for ML implies that it does so for Haskell. If one wants to know what induction for Haskell's 'lazy naturals' looks like, they can study the ML analogue of:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> LNat = Zero | Succ <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; LNat<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>because function spaces lift their codomain, and make things 'lazy'.</p>
<p>----</p>
<p>The other example I'd like to talk about hearkens back to the previous article.  I explained how <code>foldMap</code> is the proper fundamental method of the <code>Foldable</code> class, because it can be massaged to look like:</p>
<pre class="haskell">&nbsp;
foldMap :: Foldable f =&gt; f a -&gt; FreeMonoid a
&nbsp;</pre>
<p>and lists are not the free monoid, because they do not work properly for various infinite cases.</p>
<p>I also mentioned that <code>foldMap</code> looks a lot like <code>traverse</code>: </p>
<pre class="haskell">&nbsp;
foldMap  :: <span style="color: green;">&#40;</span>Foldable t   , Monoid m<span style="color: green;">&#41;</span>      =&gt; <span style="color: green;">&#40;</span>a -&gt; m<span style="color: green;">&#41;</span>   -&gt; t a -&gt; m
traverse :: <span style="color: green;">&#40;</span>Traversable t, 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; t a -&gt; f <span style="color: green;">&#40;</span>t b<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>And of course, we have <code>Monoid m => Applicative (Const m)</code>, and the functions are expected to agree in this way when applicable.</p>
<p>Now, people like to get in arguments about whether traversals are allowed to be infinite. I know Ed Kmett likes to argue that they can be, because he has lots of examples. But, not everyone agrees, and especially people who have papers proving things about traversals tend to side with the finite-only side. I've heard this includes one of the inventors of <code>Traversable</code>, Conor McBride.</p>
<p>In my opinion, the above disagreement is just another example of a situation where we have a generic notion instantiated in two different ways, and intuition about one does not quite transfer to the other. If you are working in a language like Agda or Coq (for proving), you will be thinking about traversals in the context of sets and total functions. And there, traversals are finite. But in Haskell, there are infinitary cases to consider, and they should work out all right when thinking about domains instead of sets. But I should probably put forward some argument for this position (and even if I don't need to, it leads somewhere else interesting).</p>
<p>One example that people like to give about finitary traversals is that they can be done via lists. Given a finite traversal, we can traverse to get the elements (using <code>Const [a]</code>), traverse the list, then put them back where we got them by traversing again (using <code>State [a]</code>). Usually when you see this, though, there's some subtle cheating in relying on the list to be exactly the right length for the second traversal. It will be, because we got it from a traversal of the same structure, but I would expect that proving the function is actually total to be a lot of work. Thus, I'll use this as an excuse to do my own cheating later.</p>
<p>Now, the above uses lists, but why are we using lists when we're in Haskell? We know they're deficient in certain ways. It turns out that we can give a lot of the same relevant structure to the better free monoid type:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> FM a = FM <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> m. Monoid m =&gt; <span style="color: green;">&#40;</span>a -&gt; m<span style="color: green;">&#41;</span> -&gt; m<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Applicative FM <span style="color: #06c; font-weight: bold;">where</span>
  pure x = FM <span style="color: green;">&#40;</span>$ x<span style="color: green;">&#41;</span>
  FM ef &lt; *&gt; FM ex = FM $ \k -&gt; ef $ \f -&gt; ex $ \x -&gt; k <span style="color: green;">&#40;</span>f x<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Monoid <span style="color: green;">&#40;</span>FM a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  mempty = FM $ \_ -&gt; mempty
  mappend <span style="color: green;">&#40;</span>FM l<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>FM r<span style="color: green;">&#41;</span> = FM $ \k -&gt; l k &lt;&gt; r k
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Foldable FM <span style="color: #06c; font-weight: bold;">where</span>
  foldMap f <span style="color: green;">&#40;</span>FM e<span style="color: green;">&#41;</span> = e f
&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Ap f b = Ap <span style="color: green;">&#123;</span> unAp :: f b <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Applicative f, Monoid b<span style="color: green;">&#41;</span> =&gt; Monoid <span style="color: green;">&#40;</span>Ap f b<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  mempty = Ap $ pure mempty
  mappend <span style="color: green;">&#40;</span>Ap l<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Ap r<span style="color: green;">&#41;</span> = Ap $ <span style="color: green;">&#40;</span>&lt;&gt;<span style="color: green;">&#41;</span> &lt; $&gt; l &lt; *&gt; r
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Traversable FM <span style="color: #06c; font-weight: bold;">where</span>
  traverse f <span style="color: green;">&#40;</span>FM e<span style="color: green;">&#41;</span> = unAp . e $ Ap . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> pure . f
&nbsp;</pre>
<p>So, free monoids are <code>Monoids</code> (of course), <code>Foldable</code>, and even <code>Traversable</code>. At least, we can define something with the right type that wouldn't bother anyone if it were written in a total language with the right features, but in Haskell it happens to allow various infinite things that people don't like.</p>
<p>Now it's time to cheat. First, let's define a function that can take any <code>Traversable</code> to our free monoid:</p>
<pre class="haskell">&nbsp;
toFreeMonoid :: Traversable t =&gt; t a -&gt; FM a
toFreeMonoid f = FM $ \k -&gt; getConst $ traverse <span style="color: green;">&#40;</span>Const . k<span style="color: green;">&#41;</span> f
&nbsp;</pre>
<p>Now let's define a <code>Monoid</code> that's not a monoid:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Cheat a = Empty | Single a | Append <span style="color: green;">&#40;</span>Cheat a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Cheat a<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Monoid <span style="color: green;">&#40;</span>Cheat a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  mempty = Empty
  mappend = Append
&nbsp;</pre>
<p>You may recognize this as the data version of the free monoid from the previous article, where we get the real free monoid by taking a quotient. using this, we can define an <code>Applicative</code> that's not valid:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Cheating b a =
  Cheating <span style="color: green;">&#123;</span> prosper :: Cheat b -&gt; a <span style="color: green;">&#125;</span> <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Applicative <span style="color: green;">&#40;</span>Cheating b<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure x = Cheating $ \_ -&gt; x
&nbsp;
  Cheating f &lt; *&gt; Cheating x = Cheating $ \c -&gt; <span style="color: #06c; font-weight: bold;">case</span> c <span style="color: #06c; font-weight: bold;">of</span>
    Append l r -&gt; f l <span style="color: green;">&#40;</span>x r<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Given these building blocks, we can define a function to relabel a traversable using a free monoid:</p>
<pre class="haskell">&nbsp;
relabel :: Traversable t =&gt; t a -&gt; FM b -&gt; t b
relabel t <span style="color: green;">&#40;</span>FM m<span style="color: green;">&#41;</span> = propser <span style="color: green;">&#40;</span>traverse <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> hope<span style="color: green;">&#41;</span> t<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>m Single<span style="color: green;">&#41;</span>
 <span style="color: #06c; font-weight: bold;">where</span>
 hope = Cheating $ \c -&gt; <span style="color: #06c; font-weight: bold;">case</span> c <span style="color: #06c; font-weight: bold;">of</span>
   Single x -&gt; x
&nbsp;</pre>
<p>And we can implement any traversal by taking a trip through the free monoid:</p>
<pre class="haskell">&nbsp;
slowTraverse
  :: <span style="color: green;">&#40;</span>Applicative f, Traversable t<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>a -&gt; f b<span style="color: green;">&#41;</span> -&gt; t a -&gt; f <span style="color: green;">&#40;</span>t b<span style="color: green;">&#41;</span>
slowTraverse f t = <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>relabel t<span style="color: green;">&#41;</span> . traverse f . toFreeMonoid $ t
&nbsp;</pre>
<p>And since we got our free monoid via traversing, all the partiality I hid in the above won't blow up in practice, rather like the case with lists and finite traversals.</p>
<p>Arguably, this is worse cheating. It relies on the exact association structure to work out, rather than just number of elements. The reason is that for infinitary cases, you cannot flatten things out, and there's really no way to detect when you have something infinitary. The finitary traversals have the luxury of being able to reassociate everything to a canonical form, while the infinite cases force us to not do any reassociating at all. So this might be somewhat unsatisfying.</p>
<p>But, what if we didn't have to cheat at all? We can get the free monoid by tweaking <code>foldMap</code>, and it looks like <code>traverse</code>, so what happens if we do the same manipulation to the latter?</p>
<p>It turns out that lens has a type for this purpose, a slight specialization of which is:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Bazaar a b t =
  Bazaar <span style="color: green;">&#123;</span> runBazaar :: <span style="color: #06c; font-weight: bold;">forall</span> f. Applicative f =&gt; <span style="color: green;">&#40;</span>a -&gt; f b<span style="color: green;">&#41;</span> -&gt; f t <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>Using this type, we can reorder <code>traverse</code> to get:</p>
<pre class="haskell">&nbsp;
howBizarre :: Traversable t =&gt; t a -&gt; Bazaar a b <span style="color: green;">&#40;</span>t b<span style="color: green;">&#41;</span>
howBizarre t = Bazaar $ \k -&gt; traverse k t
&nbsp;</pre>
<p>But now, what do we do with this? And what even is it? [1]</p>
<p>If we continue drawing on intuition from <code>Foldable</code>, we know that <code>foldMap</code> is related to the free monoid. <code>Traversable</code> has more indexing, and instead of <code>Monoid</code> uses <code>Applicative</code>. But the latter are actually related to the former; <code>Applicative</code>s are monoidal (closed) functors. And it turns out, <code>Bazaar</code> has to do with free <code>Applicative</code>s.</p>
<p>If we want to construct free <code>Applicative</code>s, we can use our universal property encoding trick:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Free p f a =
  Free <span style="color: green;">&#123;</span> gratis :: <span style="color: #06c; font-weight: bold;">forall</span> g. p g =&gt; <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> x. f x -&gt; g x<span style="color: green;">&#41;</span> -&gt; g a <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>This is a higher-order version of the free <code>p</code>, where we parameterize over the constraint we want to use to represent structures. So <code>Free Applicative f</code> is the free <code>Applicative</code> over a type constructor <code>f</code>. I'll leave the instances as an exercise.</p>
<p>Since free monoid is a monad, we'd expect <code>Free p</code> to be a monad, too.  In this case, it is a McBride style indexed monad, as seen in <a href="https://personal.cis.strath.ac.uk/conor.mcbride/Kleisli.pdf">The Kleisli Arrows of Outrageous Fortune</a>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> f ~&gt; g = <span style="color: #06c; font-weight: bold;">forall</span> x. f x -&gt; g x
&nbsp;
embed :: f ~&gt; Free p f
embed fx = Free $ \k -&gt; k fx
&nbsp;
translate :: <span style="color: green;">&#40;</span>f ~&gt; g<span style="color: green;">&#41;</span> -&gt; Free p f ~&gt; Free p g
translate tr <span style="color: green;">&#40;</span>Free e<span style="color: green;">&#41;</span> = Free $ \k -&gt; e <span style="color: green;">&#40;</span>k . tr<span style="color: green;">&#41;</span>
&nbsp;
collapse :: Free p <span style="color: green;">&#40;</span>Free p f<span style="color: green;">&#41;</span> ~&gt; Free p f
collapse <span style="color: green;">&#40;</span>Free e<span style="color: green;">&#41;</span> = Free $ \k -&gt; e $ \<span style="color: green;">&#40;</span>Free e'<span style="color: green;">&#41;</span> -&gt; e' k
&nbsp;</pre>
<p>That paper explains how these are related to Atkey style indexed monads:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> At key i j <span style="color: #06c; font-weight: bold;">where</span>
  At :: key -&gt; At key i i
&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Atkey m i j a = m <span style="color: green;">&#40;</span>At a j<span style="color: green;">&#41;</span> i
&nbsp;
ireturn :: IMonad m =&gt; a -&gt; Atkey m i i a
ireturn = ...
&nbsp;
ibind :: IMonad m =&gt; Atkey m i j a -&gt; <span style="color: green;">&#40;</span>a -&gt; Atkey m j k b<span style="color: green;">&#41;</span> -&gt; Atkey m i k b
ibind = ...
&nbsp;</pre>
<p>It turns out, <code>Bazaar</code> is exactly the Atkey indexed monad derived from the <code>Free Applicative</code> indexed monad (with some arguments shuffled) [2]:</p>
<pre class="haskell">&nbsp;
hence :: Bazaar a b t -&gt; Atkey <span style="color: green;">&#40;</span>Free Applicative<span style="color: green;">&#41;</span> t b a
hence bz = Free $ \tr -&gt; runBazaar bz $ tr . At
&nbsp;
forth :: Atkey <span style="color: green;">&#40;</span>Free Applicative<span style="color: green;">&#41;</span> t b a -&gt; Bazaar a b t
forth fa = Bazaar $ \g -&gt; gratis fa $ \<span style="color: green;">&#40;</span>At a<span style="color: green;">&#41;</span> -&gt; g a
&nbsp;
imap :: <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt; Bazaar a i j -&gt; Bazaar b i j
imap f <span style="color: green;">&#40;</span>Bazaar e<span style="color: green;">&#41;</span> = Bazaar $ \k -&gt; e <span style="color: green;">&#40;</span>k . f<span style="color: green;">&#41;</span>
&nbsp;
ipure :: a -&gt; Bazaar a i i
ipure x = Bazaar <span style="color: green;">&#40;</span>$ x<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: green;">&#40;</span>&gt;&gt;&gt;=<span style="color: green;">&#41;</span> :: Bazaar a j i -&gt; <span style="color: green;">&#40;</span>a -&gt; Bazaar b k j<span style="color: green;">&#41;</span> -&gt; Bazaar b k i
Bazaar e &gt;&gt;&gt;= f = Bazaar $ \k -&gt; e $ \x -&gt; runBazaar <span style="color: green;">&#40;</span>f x<span style="color: green;">&#41;</span> k
&nbsp;
<span style="color: green;">&#40;</span>&gt;==&gt;<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span>s -&gt; Bazaar i o t<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>i -&gt; Bazaar a b o<span style="color: green;">&#41;</span> -&gt; s -&gt; Bazaar a b t
<span style="color: green;">&#40;</span>f &gt;==&gt; g<span style="color: green;">&#41;</span> x = f x &gt;&gt;&gt;= g
&nbsp;</pre>
<p>As an aside, <code>Bazaar</code> is also an (Atkey) indexed comonad, and the one that characterizes traversals, similar to how indexed store characterizes lenses. A <code>Lens s t a b</code> is equivalent to a coalgebra <code>s -> Store a b t</code>. A traversal is a similar <code>Bazaar</code> coalgebra:</p>
<pre class="haskell">&nbsp;
  s -&gt; Bazaar a b t
    ~
  s -&gt; <span style="color: #06c; font-weight: bold;">forall</span> f. Applicative f =&gt; <span style="color: green;">&#40;</span>a -&gt; f b<span style="color: green;">&#41;</span> -&gt; f t
    ~
  <span style="color: #06c; font-weight: bold;">forall</span> f. Applicative f =&gt; <span style="color: green;">&#40;</span>a -&gt; f b<span style="color: green;">&#41;</span> -&gt; s -&gt; f t
&nbsp;</pre>
<p>It so happens that Kleisli composition of the Atkey indexed monad above <code>(>==>)</code> is traversal composition.</p>
<p>Anyhow, <code>Bazaar</code> also inherits <code>Applicative</code> structure from <code>Free Applicative</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>Bazaar a b<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>Bazaar e<span style="color: green;">&#41;</span> = Bazaar $ \k -&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 <span style="color: green;">&#40;</span>e k<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Applicative <span style="color: green;">&#40;</span>Bazaar a b<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure x = Bazaar $ \_ -&gt; pure x
  Bazaar ef &lt; *&gt; Bazaar ex = Bazaar $ \k -&gt; ef k &lt; *&gt; ex k
&nbsp;</pre>
<p>This is actually analogous to the <code>Monoid</code> instance for the free monoid; we just delegate to the underlying structure.</p>
<p>The more exciting thing is that we can fold and traverse over the first argument of <code>Bazaar</code>, just like we can with the free monoid:</p>
<pre class="haskell">&nbsp;
bfoldMap :: Monoid m =&gt; <span style="color: green;">&#40;</span>a -&gt; m<span style="color: green;">&#41;</span> -&gt; Bazaar a b t -&gt; m
bfoldMap f <span style="color: green;">&#40;</span>Bazaar e<span style="color: green;">&#41;</span> = getConst $ e <span style="color: green;">&#40;</span>Const . f<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Comp g f a = Comp <span style="color: green;">&#123;</span> getComp :: g <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span> <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a><span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Applicative f, Applicative g<span style="color: green;">&#41;</span> =&gt; Applicative <span style="color: green;">&#40;</span>Comp g f<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure = Comp . pure . pure
  Comp f &lt; *&gt; Comp x = Comp $ liftA2 <span style="color: green;">&#40;</span>&lt; *&gt;<span style="color: green;">&#41;</span> f x
&nbsp;
btraverse
  :: <span style="color: green;">&#40;</span>Applicative f<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>a -&gt; f a'<span style="color: green;">&#41;</span> -&gt; Bazaar a b t -&gt; Bazaar a' b t
btraverse f <span style="color: green;">&#40;</span>Bazaar e<span style="color: green;">&#41;</span> = getComp $ e <span style="color: green;">&#40;</span>c . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> ipure . f<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>This is again analogous to the free monoid code. <code>Comp</code> is the analogue of <code>Ap</code>, and we use <code>ipure</code> in <code>traverse</code>. I mentioned that <code>Bazaar</code> is a comonad:</p>
<pre class="haskell">&nbsp;
<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> :: Bazaar b b t -&gt; t
<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>Bazaar e<span style="color: green;">&#41;</span> = runIdentity $ e Identity
&nbsp;</pre>
<p>And now we are finally prepared to not cheat:</p>
<pre class="haskell">&nbsp;
honestTraverse
  :: <span style="color: green;">&#40;</span>Applicative f, Traversable t<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>a -&gt; f b<span style="color: green;">&#41;</span> -&gt; t a -&gt; f <span style="color: green;">&#40;</span>t b<span style="color: green;">&#41;</span>
honestTraverse f = <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://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> . btraverse f . howBizarre
&nbsp;</pre>
<p>So, we can traverse by first turning out <code>Traversable</code> into some structure that's kind of like the free monoid, except having to do with <code>Applicative</code>, traverse that, and then pull a result back out. <code>Bazaar</code> retains the information that we're eventually building back the same type of structure, so we don't need any cheating.</p>
<p>To pull this back around to domains, there's nothing about this code to object to if done in a total language. But, if we think about our free <code>Applicative</code>-ish structure, in Haskell, it will naturally allow infinitary expressions composed of the <code>Applicative</code> operations, just like the free monoid will allow infinitary monoid expressions. And this is okay, because <i>some</i> <code>Applicative</code>s can make sense of those, so throwing them away would make the type not free, in the same way that even finite lists are not the free monoid in Haskell. And this, I think, is compelling enough to say that infinite traversals are right for Haskell, just as they are wrong for Agda.</p>
<p>For those who wish to see executable code for all this, I've put a files <a href="http://code.haskell.org/~dolio/haskell-share/FMon.hs">here</a> and <a href="http://code.haskell.org/~dolio/haskell-share/Libre.hs">here</a>. The latter also contains some extra goodies at the end that I may talk about in further installments.</p>
<p>[1] Truth be told, I'm not exactly sure.</p>
<p>[2] It turns out, you can generalize <code>Bazaar</code> to have a correspondence for every choice of <code>p</code></p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Bizarre p a b t =
  Bizarre <span style="color: green;">&#123;</span> bizarre :: <span style="color: #06c; font-weight: bold;">forall</span> f. p f =&gt; <span style="color: green;">&#40;</span>a -&gt; f b<span style="color: green;">&#41;</span> -&gt; f t <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p><code>hence</code> and <code>forth</code> above go through with the more general types. This can be seen <a href="http://code.haskell.org/~dolio/haskell-share/Libre.hs">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2015/domains-sets-traversals-and-applicatives/feed/</wfw:commentRss>
		<slash:comments>70</slash:comments>
		</item>
		<item>
		<title>Free Monoids in Haskell</title>
		<link>http://comonad.com/reader/2015/free-monoids-in-haskell/</link>
		<comments>http://comonad.com/reader/2015/free-monoids-in-haskell/#comments</comments>
		<pubDate>Sat, 21 Feb 2015 23:00:55 +0000</pubDate>
		<dc:creator>Dan Doel</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Mathematics]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=977</guid>
		<description><![CDATA[It is often stated that Foldable is effectively the toList class. However, this turns out to be wrong. The real fundamental member of Foldable is foldMap (which should look suspiciously like traverse, incidentally). To understand exactly why this is, it helps to understand another surprising fact: lists are not free monoids in Haskell.
This latter fact [...]]]></description>
			<content:encoded><![CDATA[<p>It is often stated that <code>Foldable</code> is effectively the <code>toList</code> class. However, this turns out to be wrong. The real fundamental member of <code>Foldable</code> is <code>foldMap</code> (which should look suspiciously like <code>traverse</code>, incidentally). To understand exactly why this is, it helps to understand another surprising fact: lists are not free monoids in Haskell.</p>
<p>This latter fact can be seen relatively easily by considering another list-like type:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> SL a = Empty | SL a :&gt; a
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Monoid <span style="color: green;">&#40;</span>SL a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  mempty = Empty
  mappend ys Empty = ys
  mappend ys <span style="color: green;">&#40;</span>xs :&gt; x<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>mappend ys xs<span style="color: green;">&#41;</span> :&gt; x
&nbsp;
single :: a -&gt; SL a
single x = Empty :&gt; x
&nbsp;</pre>
<p>So, we have a type <code>SL a</code> of snoc lists, which are a monoid, and a function that embeds <code>a</code> into <code>SL a</code>. If (ordinary) lists were the free monoid, there would be a unique monoid homomorphism from lists to snoc lists. Such a homomorphism (call it <code>h</code>) would have the following properties:</p>
<pre class="haskell">&nbsp;
h <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> = Empty
h <span style="color: green;">&#40;</span>xs &lt;&gt; ys<span style="color: green;">&#41;</span> = h xs &lt;&gt; h ys
h <span style="color: green;">&#91;</span>x<span style="color: green;">&#93;</span> = single x
&nbsp;</pre>
<p>And in fact, this (together with some general facts about Haskell functions) should be enough to define <code>h</code> for our purposes (or any purposes, really).  So, let's consider its behavior on two values:</p>
<pre class="haskell">&nbsp;
h <span style="color: green;">&#91;</span><span style="color: red;">1</span><span style="color: green;">&#93;</span> = single <span style="color: red;">1</span>
&nbsp;
h <span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">1</span>..<span style="color: green;">&#93;</span> = h <span style="color: green;">&#40;</span><span style="color: green;">&#91;</span><span style="color: red;">1</span><span style="color: green;">&#93;</span> &lt;&gt; <span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">1</span>..<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span> <span style="color: #5d478b; font-style: italic;">-- [1,1..] is an infinite list of 1s</span>
          = h <span style="color: green;">&#91;</span><span style="color: red;">1</span><span style="color: green;">&#93;</span> &lt;&gt; h <span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">1</span>..<span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>This second equation can tell us what the value of <code>h</code> is at this infinite value, since we can consider it the definition of a possibly infinite value:</p>
<pre class="haskell">&nbsp;
x = h <span style="color: green;">&#91;</span><span style="color: red;">1</span><span style="color: green;">&#93;</span> &lt;&gt; x = fix <span style="color: green;">&#40;</span>single <span style="color: red;">1</span> &lt;&gt;<span style="color: green;">&#41;</span>
h <span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">1</span>..<span style="color: green;">&#93;</span> = x
&nbsp;</pre>
<p><code>(single 1 <>)</code> is a strict function, so the fixed point theorem tells us that <code>x = ⊥</code>.</p>
<p>This is a problem, though. Considering some additional equations:</p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">1</span>..<span style="color: green;">&#93;</span> &lt;&gt; <span style="color: green;">&#91;</span>n<span style="color: green;">&#93;</span> = <span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">1</span>..<span style="color: green;">&#93;</span> <span style="color: #5d478b; font-style: italic;">-- true for all n</span>
h <span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">1</span>..<span style="color: green;">&#93;</span> = ⊥
h <span style="color: green;">&#40;</span><span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">1</span>..<span style="color: green;">&#93;</span> &lt;&gt; <span style="color: green;">&#91;</span><span style="color: red;">1</span><span style="color: green;">&#93;</span><span style="color: green;">&#41;</span> = h <span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">1</span>..<span style="color: green;">&#93;</span> &lt;&gt; h <span style="color: green;">&#91;</span><span style="color: red;">1</span><span style="color: green;">&#93;</span>
                   = ⊥ &lt;&gt; single <span style="color: red;">1</span>
                   = ⊥ :&gt; <span style="color: red;">1</span>
                   ≠ ⊥
&nbsp;</pre>
<p>So, our requirements for <code>h</code> are contradictory, and no such homomorphism can exist.</p>
<p>The issue is that Haskell types are domains. They contain these extra partially defined values and infinite values. The monoid structure on (cons) lists  has infinite lists absorbing all right-hand sides, while the snoc lists are just the opposite.  </p>
<p>This also means that finite lists (or any method of implementing finite sequences) are not free monoids in Haskell. They, as domains, still contain the additional bottom element, and it absorbs all other elements, which is incorrect behavior for the free monoid: </p>
<pre class="haskell">&nbsp;
pure x &lt;&gt; ⊥ = ⊥
h ⊥ = ⊥
h <span style="color: green;">&#40;</span>pure x &lt;&gt; ⊥<span style="color: green;">&#41;</span> = <span style="color: green;">&#91;</span>x<span style="color: green;">&#93;</span> &lt;&gt; h ⊥
                = <span style="color: green;">&#91;</span>x<span style="color: green;">&#93;</span> ++ ⊥
                = x:⊥
                ≠ ⊥
&nbsp;</pre>
<p>So, what is the free monoid? In a sense, it can't be written down at all in Haskell, because we cannot enforce value-level equations, and because we don't have quotients. But, if conventions are good enough, there is a way. First, suppose we have a free monoid type <code>FM a</code>. Then for any other monoid <code>m</code> and embedding <code>a -> m</code>, there must be a monoid homomorphism from <code>FM a</code> to <code>m</code>. We can model this as a Haskell type:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">forall</span> a m. Monoid m =&gt; <span style="color: green;">&#40;</span>a -&gt; m<span style="color: green;">&#41;</span> -&gt; FM a -&gt; m
&nbsp;</pre>
<p>Where we consider the <code>Monoid m</code> constraint to be enforcing that <code>m</code> actually has valid monoid structure. Now, a trick is to recognize that this sort of universal property can be used to <em>define</em> types in Haskell (or, GHC at least), due to polymorphic types being first class; we just rearrange the arguments and quantifiers, and take <code>FM a</code> to be the polymorphic type:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> FM a = FM <span style="color: green;">&#123;</span> unFM :: <span style="color: #06c; font-weight: bold;">forall</span> m. Monoid m =&gt; <span style="color: green;">&#40;</span>a -&gt; m<span style="color: green;">&#41;</span> -&gt; m <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>Types defined like this are automatically universal in the right sense. <a href="#footnote-1">[1]</a> The only thing we have to check  is that <code>FM a</code> is actually a monoid over <code>a</code>. But that turns out to be easily witnessed:</p>
<pre class="haskell">&nbsp;
embed :: a -&gt; FM a
embed x = FM $ \k -&gt; k x
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Monoid <span style="color: green;">&#40;</span>FM a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  mempty = FM $ \_ -&gt; mempty
  mappend <span style="color: green;">&#40;</span>FM e1<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>FM e2<span style="color: green;">&#41;</span> = FM $ \k -&gt; e1 k &lt;&gt; e2 k
&nbsp;</pre>
<p>Demonstrating that the above is a proper monoid delegates to instances of <code>Monoid</code> being proper monoids. So as long as we trust that convention, we have a free monoid.</p>
<p>However, one might wonder what a free monoid would look like as something closer to a traditional data type. To construct that, first ignore the required equations, and consider only the generators; we get:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> FMG a = None | Single a | FMG a :&lt;&gt; FMG a
&nbsp;</pre>
<p>Now, the proper <code>FM a</code> is the quotient of this by the equations:</p>
<pre class="haskell">&nbsp;
None :&lt;&gt; x = x = x :&lt;&gt; None
x :&lt;&gt; <span style="color: green;">&#40;</span>y :&lt;&gt; z<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>x :&lt;&gt; y<span style="color: green;">&#41;</span> :&lt;&gt; z
&nbsp;</pre>
<p>One way of mimicking this in Haskell is to hide the implementation in a module, and only allow elimination into <code>Monoid</code>s (again, using the convention that <code>Monoid</code> ensures actual monoid structure) using the function:</p>
<pre class="haskell">&nbsp;
unFMG :: <span style="color: #06c; font-weight: bold;">forall</span> a m. Monoid m =&gt; FMG a -&gt; <span style="color: green;">&#40;</span>a -&gt; m<span style="color: green;">&#41;</span> -&gt; m
unFMG None _ = mempty
unFMG <span style="color: green;">&#40;</span>Single x<span style="color: green;">&#41;</span> k = k x
unFMG <span style="color: green;">&#40;</span>x :&lt;&gt; y<span style="color: green;">&#41;</span> k = unFMG x k &lt;&gt; unFMG y k
&nbsp;</pre>
<p>This is actually how quotients can be thought of in richer languages; the quotient does not eliminate any of the generated structure internally, it just restricts the way in which the values can be consumed. Those richer languages just allow us to prove equations, and enforce properties by proof obligations, rather than conventions and structure hiding. Also, one should note that the above should look pretty similar to our encoding of <code>FM a</code> using universal quantification earlier.</p>
<p>Now, one might look at the above and have some objections. For one, we'd normally think that the quotient of the above type is just <code>[a]</code>. Second, it seems like the type is revealing something about the associativity of the operations, because defining recursive values via left nesting is different from right nesting, and this difference is observable by extracting into different monoids. But aren't monoids supposed to remove associativity as a concern? For instance:</p>
<pre class="haskell">&nbsp;
ones1 = embed <span style="color: red;">1</span> &lt;&gt; ones1
ones2 = ones2 &lt;&gt; embed <span style="color: red;">1</span>
&nbsp;</pre>
<p>Shouldn't we be able to prove these are the same, becuase of an argument like:</p>
<pre class="haskell">&nbsp;
ones1 = embed <span style="color: red;">1</span> &lt;&gt; <span style="color: green;">&#40;</span>embed <span style="color: red;">1</span> &lt;&gt; ...<span style="color: green;">&#41;</span>
      ... reassociate ...
      = <span style="color: green;">&#40;</span>... &lt;&gt; embed <span style="color: red;">1</span><span style="color: green;">&#41;</span> &lt;&gt; embed <span style="color: red;">1</span>
      = ones2
&nbsp;</pre>
<p>The answer is that the equation we have only specifies the behavior of associating three values:</p>
<pre class="haskell">&nbsp;
x &lt;&gt; <span style="color: green;">&#40;</span>y &lt;&gt; z<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>x &lt;&gt; y<span style="color: green;">&#41;</span> &lt;&gt; z
&nbsp;</pre>
<p>And while this is sufficient to nail down the behavior of <em>finite</em> values, and <em>finitary</em> reassociating, it does not tell us that <em>infinitary</em> reassociating yields the same value back. And the "... reassociate ..." step in the argument above was decidedly infinitary. And while the rules tell us that we can peel any finite number of copies of <code>embed 1</code> to the front of <code>ones1</code> or the end of <code>ones2</code>, it does not tell us that <code>ones1 = ones2</code>. And in fact it is vital for <code>FM a</code> to have distinct values for these two things; it is what makes it the free monoid when we're dealing with domains of lazy values.</p>
<p>Finally, we can come back to <code>Foldable</code>. If we look at <code>foldMap</code>:</p>
<pre class="haskell">&nbsp;
foldMap :: <span style="color: green;">&#40;</span>Foldable f, Monoid m<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>a -&gt; m<span style="color: green;">&#41;</span> -&gt; f a -&gt; m
&nbsp;</pre>
<p>we can rearrange things a bit, and get the type:</p>
<pre class="haskell">&nbsp;
Foldable f =&gt; f a -&gt; <span style="color: green;">&#40;</span><span style="color: #06c; font-weight: bold;">forall</span> m. Monoid m =&gt; <span style="color: green;">&#40;</span>a -&gt; m<span style="color: green;">&#41;</span> -&gt; m<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>And thus, the most fundamental operation of <code>Foldable</code> is not <code>toList</code>, but <code>toFreeMonoid</code>, and lists are not free monoids in Haskell.</p>
<p><a name="footnote-1">[1]</a>: What we are doing here is noting that (co)limits are objects that internalize natural transformations, but the natural transformations expressible by quantification in GHC are already automatically internalized using quantifiers. However, one has to be careful that the quantifiers are actually enforcing the relevant naturality conditions. In many simple cases they are.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2015/free-monoids-in-haskell/feed/</wfw:commentRss>
		<slash:comments>52</slash:comments>
		</item>
		<item>
		<title>Japanese &#8220;ekmett&#8221; Workshop (Part 1 of 2)</title>
		<link>http://comonad.com/reader/2013/japanese-workshop-1/</link>
		<comments>http://comonad.com/reader/2013/japanese-workshop-1/#comments</comments>
		<pubDate>Mon, 01 Apr 2013 05:59:05 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Japan]]></category>
		<category><![CDATA[Lenses]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[workshop]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=831</guid>
		<description><![CDATA[A couple of weeks back one of my coworkers brought to my attention a several hour long workshop in Japan to go over and describe a number of my libraries, hosted by TANAKA Hideyuki — not the voice actor, I checked!
I was incredibly honored and I figured that if that many people (they had 30 [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks back one of my coworkers brought to my attention <a href="http://partake.in/events/1698f7f8-4151-4048-b317-03a8c3f1a7ab">a several hour long workshop in Japan</a> to go over and describe a number of my libraries, hosted by <a href="https://github.com/tanakh">TANAKA Hideyuki</a> — not the <a href="http://en.wikipedia.org/wiki/Hideyuki_Tanaka">voice actor</a>, I checked!</p>
<p>I was incredibly honored and I figured that if that many people (they had 30 or so registered attendees and 10 presentations) were going to spend that much time going over software that I had written, I should at least offer to show up!</p>
<p>I'd like to apologize for any errors in the romanization of people's names or misunderstandings I may have in the following text. My grasp of Japanese is very poor! Please feel free to send me corrections or additions!</p>
<h2>Surprise!</h2>
<p>Sadly, my <a href="https://twitter.com/mcscottmc">boss</a>'s immediate reaction to hearing that there was a workshop in Japan about my work was to quip that "You're saying you're <a href="http://en.wikipedia.org/wiki/Big_in_Japan_(phrase)">huge in Japan</a>?" With him conspicuously not offering to fly me out here, I had to settle for surprising the organizers and attending via Google Hangout.</p>
<h2>Commentary and Logs</h2>
<p><a href="http://twitter.com/nushio">@nushio</a> was very helpful in getting me connected, and while the speakers gave their talks I sat on the irc.freenode.net #haskell-lens channel and Google Hangout and answered questions and provided a running commentary with more details and references. Per <a href="http://freenode.net/channel_guidelines.shtml">freenode policy</a> the fact that we were logging the channel was announced -- well, at least before things got too far underway.</p>
<p><a href="https://gist.github.com/ekmett/5283253">Here is the IRC session log as a gist</a>. IKEGAMI Daisuke <a href="https://twitter.com/ikegami__">@ikegami__</a> (<code>ikeg</code> in the IRC log) tried to keep up a high-level running commentary about what was happening in the video to the log, which may be helpful if you are trying to follow along through each retroactively.</p>
<p>Other background chatter and material is strewn across twitter under the <a href="https://twitter.com/search?q=%23ekmett_conf&src=typd">#ekmett_conf</a> hash tag and on a japanese twitter aggregator named <a href="http://togetter.com/li/480399">togetter</a></p>
<p><span id="more-831"></span></p>
<h2>Getting Started</h2>
<p>The 1PM start time in Shibuya, Tokyo, Japan translates to midnight at the start of Easter here in Boston, which meant ~6 hours later when we reached the Q&A session, I was a bit loopy from lack of sleep, but they were incredibly polite and didn't seem to mind my long rambling responses.</p>
<p>Thanks to the organizers, we have video of the vast majority of the event! There was no audio for the first couple of minutes, and the recording machine lost power for the last talk and the Q&A session at the end as we ran somewhat longer than they had originally scheduled! -- And since I was attending remotely and a number of others flitted in and out over the course of the night, they were nice enough to put most of the slides and background material online.</p>
<h2>profunctors by Liyang HU and HIBINO Kei</h2>
<p><a href="http://liyang.hu/">Liyang Hu</a> (<a href="http://twitter.com/liyanghu">@liyanghu</a>) started the session off with a nicely self-contained crash course on my <a href="http://github.com/ekmett/profunctors">profunctors</a> package, since profunctors are used fairly heavily inside the implementation of <a href="http://github.com/ekmett/lens">lens</a> and <a href="http://github.com/ekmett/machines">machines</a>, with a couple of detours into <a href="http://github.com/ekmett/contravariant">contravariant</a> and <a href="http://github.com/ekmett/bifunctors">bifunctors</a>.</p>
<p><a href="https://www.fpcomplete.com/user/liyang/profunctors">His presentation materials</a> are available interactively from the new <a href="https://www.fpcomplete.com/">FP Complete</a> School of Haskell. You can also watch the <a href="http://www.ustream.tv/recorded/30668431/highlight/337429">video recording of his talk</a> on <a href="http://www.ustream.tv/">ustream</a>.</p>
<p>This talk was followed by a much more condensed version of very similar content <a href="http://www.ustream.tv/recorded/30668431/highlight/337431">in Japanese by Hibino Kei</a> (<a href="https://github.com/khibino">@khibino</a>) His talk was more focused on the relationship between arrows and profunctors, and the <a href="http://www.slideshare.net/khibino/profunctor-and-arrow-17939130"> slides are available through slideshare</a>.</p>
<h2>lens by @its_out_of_tune</h2>
<p>Once the necessary background material was out of the way, the talk on <a href="http://hackage.haskell.org/package/lens">lens</a> -- arguably the presentation that most of the people were there for -- came early. </p>
<p><a href="http://comonad.com/reader/wp-content/uploads/2013/03/ekmett_conf-its_out_of_tune-1.jpg"><img src="http://comonad.com/reader/wp-content/uploads/2013/03/ekmett_conf-its_out_of_tune-1.jpg" alt="ekmett_conf-its_out_of_tune-1" title="ekmett_conf-its_out_of_tune-1" width="1076" height="736" class="aligncenter size-full wp-image-835" /></a></p>
<p><a href="https://twitter.com/its_out_of_tune">@its_out_of_tune</a> gave an incredibly dense overview of how to use the main parts of the lens package in Japanese. <a href="http://www.slideshare.net/itsoutoftunethismymusic/ekmett-17955009">His slides are available online</a> and <a href="http://www.ustream.tv/recorded/30668431/highlight/337435">here is a recording of his talk</a>. </p>
<p>Over the course of a half hour, he was able to cram in a great cross-section of the library including material that I hadn't even been able to get to even with 4x the amount of time available during <a href="https://www.youtube.com/watch?v=cefnmjtAolY&hd=1">my New York talk</a> on how to use the lens template-haskell code to automatically generate lenses for user data types and how to use the lens <a href=http://hackage.haskell.org/packages/archive/lens/3.9.0.2/doc/html/Control-Lens-Action.html">Action</a> machinery.</p>
<h2>free and free-game by KINOSHITA Fumiaki</h2>
<p>Next up, was my <a href="http://hackage.haskell.org/package/free">free</a> package and the neat <a href="http://hackage.haskell.org/package/free-game">free-game</a> engine that Kinoshita Fumiaki (<a href="https://twitter.com/fumieval">@fumieval</a>) built on top.</p>
<p>The slides were in English, though the talk and humor were very Japanese. ^_^</p>
<p><a href="http://comonad.com/reader/wp-content/uploads/2013/03/ekmett_conf-free.jpg"><img src="http://comonad.com/reader/wp-content/uploads/2013/03/ekmett_conf-free.jpg" alt="ekmett_conf-free" title="ekmett_conf-free" width="1076" height="734" class="aligncenter size-full wp-image-852" /></a></p>
<p>That said, he had some amazingly nice demos, including a live demo of his tetris clone, <a href="https://github.com/fumieval/Monaris">Monaris</a>, which is visible about 10 minutes into <a href="http://www.ustream.tv/recorded/30668431/highlight/337437">the video</a>!</p>
<h2>ad by @nebutalab</h2>
<p><a href="http://twitter.com/nebutalab">@nebutalab</a>, like me, joined the session remotely through Google Hangout, and proceeded to give a tutorial on how <a href="http://en.wikipedia.org/wiki/Automatic_differentiation#Forward_accumulation">forward mode</a> automatic differentiation works through my <a href="http://github.com/ekmett/ad">AD</a> package.</p>
<p><a href="http://www.slideshare.net/nebuta/haskell-ad34">His slides were made available before the talk</a> and the video is available in <a href="http://www.ustream.tv/recorded/30671273/highlight/337441">two</a> <a href="http://www.ustream.tv/recorded/30671623/highlight/337439">parts</a> due a technical hiccup in the middle of the recording.</p>
<p><a href="http://comonad.com/reader/wp-content/uploads/2013/04/ekmett_conf-ad.jpg"><img src="http://comonad.com/reader/wp-content/uploads/2013/04/ekmett_conf-ad-300x204.jpg" alt="ekmett_conf-ad" title="ekmett_conf-ad" width="300" height="204" class="aligncenter size-medium wp-image-862" /></a></p>
<p>I'm currently working to drastically simplify the API for ad with <a href="https://github.com/alang9">Alex Lang</a>. Fortunately almost all of the material in this presentation will still be relevant to the new design.</p>
<h2>tables by MURAYAMA Shohei</h2>
<p>Next up, Murayama Shohei (<a href="https://twitter.com/yuga">@yuga</a>) gave an introduction to <a href="http://hackage.haskell.org/package/tables">tables</a>, which is a small in memory data-store that I wrote a few months back to sit on top of lens.</p>
<p><a href="http://www.ustream.tv/recorded/30672629/highlight/337395">Video of @yuga's talk</a> and <a href="https://gist.github.com/yuga/5279313">his slides</a> are available, which I think makes this the first public talk about this project. -_^</p>
<h2>machines by YOSHIDA Sanshiro</h2>
<p>Yoshida Sanshiro (<a href="http://twitter.com/halcat0x15a">@halcat0x15a</a>) gave a nice overview of the currently released version of <a href="http://hackage.haskell.org/package/machines">machines</a> including a lot of examples! I think he may have actually written more code using machines just for demonstrations than I have written using it myself.</p>
<p><a href="http://www.ustream.tv/recorded/30672629/highlight/337397">Video of his talk is available</a> along with <a href="http://halcat0x15a.github.com/slide/machines/out/#0">his slide deck</a> -- just tap left or right to move through the slides. He has also written <a href="http://krdlab.hatenablog.com/entry/2013/03/16/204039">a blog post</a> documenting his early explorations of the library, and some thoughts about using it with attoparsec.</p>
<p>I've recently been trying to redesign machines with coworker Paul CHIUSANO <a href="https://twitter.com/pchiusano">@pchiusano</a> and we've begun greatly simplifying the design of machines based on some work <a href="http://www.youtube.com/watch?v=8fC2V9HX_m8">he has been doing in Scala</a>, so unfortunately many of the particulars of this talk will be soon outdated, but the overall 'feel' of working with machines should be preserved across the change-over. Some of these changes can be seen in the <a href="http://github.com/ekmett/machines">master branch on github</a> now.</p>
<h2>More to come</h2>
<p>There were 4 more sessions, but alas, I'm out of time for the moment! I'll continue this write-up with more links to the source material and my thoughts as soon as I can tomorrow!</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2013/japanese-workshop-1/feed/</wfw:commentRss>
		<slash:comments>95</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>Free Modules and Functional Linear Functionals</title>
		<link>http://comonad.com/reader/2011/free-modules-and-functional-linear-functionals/</link>
		<comments>http://comonad.com/reader/2011/free-modules-and-functional-linear-functionals/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 20:58:04 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Linear Algebra]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Monoids]]></category>
		<category><![CDATA[Type Hackery]]></category>

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

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

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