<?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; Category Theory</title>
	<atom:link href="http://comonad.com/reader/category/category-theory/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>Abstracting with Applicatives</title>
		<link>http://comonad.com/reader/2012/abstracting-with-applicatives/</link>
		<comments>http://comonad.com/reader/2012/abstracting-with-applicatives/#comments</comments>
		<pubDate>Thu, 27 Dec 2012 01:25:13 +0000</pubDate>
		<dc:creator>Gershom Bazerman</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Monoids]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=756</guid>
		<description><![CDATA[Consider the humble Applicative. More than a functor, less than a monad. It gives us such lovely syntax. Who among us still prefers to write liftM2 foo a b when we could instead write foo &#60;$> a &#60;*> b? But we seldom use the Applicative as such — when Functor is too little, Monad is [...]]]></description>
			<content:encoded><![CDATA[<p>Consider the humble Applicative. More than a functor, less than a monad. It gives us such lovely syntax. Who among us still prefers to write <code>liftM2 foo a b</code> when we could instead write <code>foo &lt;$> a &lt;*> b</code>? But we seldom use the Applicative as such — when Functor is too little, Monad is too much, but a lax monoidal functor is just right. I noticed lately a spate of proper uses of Applicative —<a href="http://groups.inf.ed.ac.uk/links/formlets/">Formlets</a> (and their later incarnation in the <a href="http://hackage.haskell.org/package/reform">reform</a> library), <a href="http://hackage.haskell.org/package/optparse-applicative">OptParse-Applicative</a> (and its competitor library <a href=""http://hackage.haskell.org/package/cmdtheline>CmdTheLine</a>), and a <a href="http://gergo.erdi.hu/blog/2012-12-01-static_analysis_with_applicatives/">post by Gergo Erdi</a> on applicatives for declaring dependencies of computations. I also ran into a very similar genuine use for applicatives in working on the Panels library (part of <a href="http://hackage.haskell.org/package/jmacro-rpc">jmacro-rpc</a>), where I wanted to determine dependencies of a dynamically generated dataflow computation. And then, again, I stumbled into an applicative while cooking up a form validation library, which turned out to be a reinvention of the same ideas as formlets.</p>
<p>Given all this, It seems post on thinking with applicatives is in order, showing how to build them up and reason about them. One nice thing about the approach we'll be taking is that it uses a "final" encoding of applicatives, rather than building up and then later interpreting a structure. This is in fact how we typically write monads (pace operational, free, etc.), but since we more often only determine our data structures are applicative after the fact, we often get some extra junk lying around (OptParse-Applicative, for example, has a GADT that I think is entirely extraneous).</p>
<p>So the usual throat clearing:</p>
<pre class="haskell"><span style="color: #5d478b; font-style: italic;">{-# LANGUAGE TypeOperators, MultiParamTypeClasses, FlexibleInstances,
StandaloneDeriving, FlexibleContexts, UndecidableInstances,
GADTs, KindSignatures, RankNTypes #-}</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">module</span> Main <span style="color: #06c; font-weight: bold;">where</span>
<span style="color: #06c; font-weight: bold;">import</span> Control.Applicative <span style="color: #06c; font-weight: bold;">hiding</span> <span style="color: green;">&#40;</span>Const<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Data.Monoid <span style="color: #06c; font-weight: bold;">hiding</span> <span style="color: green;">&#40;</span>Sum, Product<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a>.Identity
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a> a =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a> <span style="color: green;">&#40;</span>Identity a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:show"><span style="font-weight: bold;">show</span></a> <span style="color: green;">&#40;</span>Identity x<span style="color: green;">&#41;</span> = <span style="color: #3c7331;">&quot;(Identity &quot;</span> ++ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:show"><span style="font-weight: bold;">show</span></a> x ++ <span style="color: #3c7331;">&quot;)&quot;</span></pre>
<p>And now, let's start with a classic applicative, going back to the <a href="http://www.soi.city.ac.uk/~ross/papers/Applicative.pdf">Applicative Programming With Effects</a> paper:</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">data</span> Const mo a = Const mo <span style="color: #06c; font-weight: bold;">deriving</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a>
&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>Const mo<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> _ <span style="color: green;">&#40;</span>Const mo<span style="color: green;">&#41;</span> = Const mo
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Monoid mo =&gt; Applicative <span style="color: green;">&#40;</span>Const mo<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    pure _ = Const mempty
    <span style="color: green;">&#40;</span>Const f<span style="color: green;">&#41;</span> &lt; *&gt; <span style="color: green;">&#40;</span>Const x<span style="color: green;">&#41;</span> = Const <span style="color: green;">&#40;</span>f &lt;&gt; x<span style="color: green;">&#41;</span></pre>
<p>(<code>Const</code> lives in <a href="http://hackage.haskell.org/package/transformers">transformers</a> as the <code>Constant</code> functor, or in base as <code>Const</code>)</p>
<p>Note that <code>Const</code> is not a monad. We've defined it so that its structure is independent of the `a` type. Hence if we try to write <code>(>>=) </code>of type <code>Const mo a -> (a -> Const mo b) -> Const mo b</code>, we'll have no way to "get out" the first `a` and feed it to our second argument.</p>
<p>One great thing about Applicatives is that there is no distinction between applicative transformers and applicatives themselves. This is to say that the composition of two applicatives is cleanly and naturally always also an applicative. We can capture this like so:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Compose f g a = Compose <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">deriving</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> g<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Compose f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Compose x<span style="color: green;">&#41;</span> = Compose $ <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> . <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;">&#41;</span> f x
&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>Compose f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    pure = Compose . pure . pure
    <span style="color: green;">&#40;</span>Compose f<span style="color: green;">&#41;</span> &lt; *&gt; <span style="color: green;">&#40;</span>Compose x<span style="color: green;">&#41;</span> = Compose $ <span style="color: green;">&#40;</span>&lt; *&gt;<span style="color: green;">&#41;</span> &lt; $&gt; f &lt; *&gt; x</pre>
<p>(<code>Compose</code> also lives in transformers)</p>
<p>Note that Applicatives compose <b>two</b> ways. We can also write:</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">data</span> Product f g a = Product <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">deriving</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> g<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Product f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>Product  x y<span style="color: green;">&#41;</span> = Product <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 x<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f y<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>Product f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    pure x = Product <span style="color: green;">&#40;</span>pure x<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>pure x<span style="color: green;">&#41;</span>
    <span style="color: green;">&#40;</span>Product f g<span style="color: green;">&#41;</span> &lt; *&gt; <span style="color: green;">&#40;</span>Product  x y<span style="color: green;">&#41;</span> = Product <span style="color: green;">&#40;</span>f &lt; *&gt; x<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>g &lt; *&gt; y<span style="color: green;">&#41;</span></pre>
<p>(<code>Product</code> lives in transformers as well)</p>
<p>This lets us now construct an extremely rich set of applicative structures from humble beginnings. For example, we can reconstruct the Writer Applicative.</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">type</span> Writer mo = Product <span style="color: green;">&#40;</span>Const mo<span style="color: green;">&#41;</span> Identity
&nbsp;
tell :: mo -&gt; Writer mo <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
tell x = Product <span style="color: green;">&#40;</span>Const x<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>pure <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span></pre>
<pre>-- tell [1] *> tell [2]
-- > Product (Const [1,2]) (Identity ())</pre>
<p>Note that if we strip away the newtype noise, Writer turns into <code>(mo,a)</code> which is isomorphic to the Writer monad. However, we've learned something along the way, which is that the monoidal component of Writer (as long as we stay within the rules of applicative) is entirely independent from the "identity" component. However, if we went on to write the Monad instance for our writer (by defining <code>>>=</code>), we'd have to "reach in" to the identity component to grab a value to hand back to the function yielding our monoidal component. Which is to say we would destroy this nice seperation of "trace" and "computational content" afforded by simply taking the product of two Applicatives.</p>
<p>Now let's make things more interesting. It turns out that just as the composition of two applicatives may be a monad, so too the composition of two monads may be no stronger than an applicative!</p>
<p>We'll see this by introducing Maybe into the picture, for possibly failing computations.</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">type</span> FailingWriter mo = Compose <span style="color: green;">&#40;</span>Writer mo<span style="color: green;">&#41;</span> <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>
&nbsp;
tellFW :: Monoid mo =&gt; mo -&gt; FailingWriter mo <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
tellFW x = Compose <span style="color: green;">&#40;</span>tell x *&gt; pure <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Just"><span style="font-weight: bold;">Just</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
failFW :: Monoid mo =&gt; FailingWriter mo a
failFW = Compose <span style="color: green;">&#40;</span>pure <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Nothing"><span style="font-weight: bold;">Nothing</span></a><span style="color: green;">&#41;</span></pre>
<pre>-- tellFW [1] *> tellFW [2]
-- > Compose (Product (Const [1,2]) (Identity Just ()))

-- tellFW [1] *> failFW *> tellFW [2]
-- > Compose (Product (Const [1,2]) (Identity Nothing))</pre>
<p>Maybe over Writer gives us the same effects we'd get in a Monad — either the entire computation fails, or we get the result and the trace. But Writer over Maybe gives us new behavior. We get the entire trace, even if some computations have failed! This structure, just like Const, cannot be given a proper Monad instance. (In fact if we take Writer over Maybe as a Monad, we get only the trace until the first point of failure).</p>
<p>This seperation of a monoidal trace from computational effects (either entirely independent of a computation [via a product] or independent between parts of a computation [via Compose]) is the key to lots of neat tricks with applicative functors.</p>
<p>Next, let's look at Gergo Erdi's "Static Analysis with Applicatives" that is built using free applicatives. We can get essentially the same behavior directly from the product of a constant monad with an arbitrary effectful monad representing our ambient environment of information. As long as we constrain ourselves to only querying it with the takeEnv function, then we can either read the left side of our product to statically read dependencies, or the right side to actually utilize them.</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">type</span> HasEnv k m = Product <span style="color: green;">&#40;</span>Const <span style="color: green;">&#91;</span>k<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span> m
takeEnv :: <span style="color: green;">&#40;</span>k -&gt; m a<span style="color: green;">&#41;</span> -&gt; k -&gt; HasEnv k m a
takeEnv f x = Product <span style="color: green;">&#40;</span>Const <span style="color: green;">&#91;</span>x<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f x<span style="color: green;">&#41;</span></pre>
<p>If we prefer, we can capture queries of a static environment directly with the standard Reader applicative, which is just a newtype over the function arrow. There are other varients of this that perhaps come closer to exactly how Erdi's post does things, but I think this is enough to demonstrate the general idea.</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">data</span> Reader r a = Reader <span style="color: green;">&#40;</span>r -&gt; a<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Reader 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 <span style="color: green;">&#40;</span>Reader x<span style="color: green;">&#41;</span> = Reader <span style="color: green;">&#40;</span>f . x<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">instance</span> Applicative <span style="color: green;">&#40;</span>Reader r<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    pure x = Reader $ pure x
    <span style="color: green;">&#40;</span>Reader f<span style="color: green;">&#41;</span> &lt; *&gt; <span style="color: green;">&#40;</span>Reader x<span style="color: green;">&#41;</span> = Reader <span style="color: green;">&#40;</span>f &lt; *&gt; x<span style="color: green;">&#41;</span>
&nbsp;
runReader :: <span style="color: green;">&#40;</span>Reader r a<span style="color: green;">&#41;</span> -&gt; r -&gt; a
runReader <span style="color: green;">&#40;</span>Reader f<span style="color: green;">&#41;</span> = f
&nbsp;
takeEnvNew :: <span style="color: green;">&#40;</span>env -&gt; k -&gt; a<span style="color: green;">&#41;</span> -&gt; k -&gt; HasEnv k <span style="color: green;">&#40;</span>Reader env<span style="color: green;">&#41;</span> a
takeEnvNew f x = Product <span style="color: green;">&#40;</span>Const <span style="color: green;">&#91;</span>x<span style="color: green;">&#93;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Reader $ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:flip"><span style="font-weight: bold;">flip</span></a> f x<span style="color: green;">&#41;</span></pre>
<p>So, what then is a full formlet? It's something that can be executed in one context as a monoid that builds a form, and in another as a parser. so the top level must be a product.</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">type</span> FormletOne mo a = Product <span style="color: green;">&#40;</span>Const mo<span style="color: green;">&#41;</span> Identity a</pre>
<p>Below the product, we read from an environment and perhaps get an answer. So that's reader with a maybe.</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">type</span> FormletTwo mo env a =
    Product <span style="color: green;">&#40;</span>Const mo<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Compose <span style="color: green;">&#40;</span>Reader env<span style="color: green;">&#41;</span> <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;">&#41;</span> a</pre>
<p>Now if we fail, we want to have a trace of errors. So we expand out the Maybe into a product as well to get the following, which adds monoidal errors:</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">type</span> FormletThree mo err env a =
    Product <span style="color: green;">&#40;</span>Const mo<span style="color: green;">&#41;</span>
            <span style="color: green;">&#40;</span>Compose <span style="color: green;">&#40;</span>Reader env<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Product <span style="color: green;">&#40;</span>Const err<span style="color: green;">&#41;</span> <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;">&#41;</span><span style="color: green;">&#41;</span> a</pre>
<p>But now we get errors whether or not the parse succeeds. We want to say either the parse succeeds or we get errors. For this, we can turn to the typical Sum functor, which currently lives as Coproduct in comonad-transformers, but will hopefully be moving as Sum to the transformers library in short order.</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">data</span> Sum f g a = InL <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> | InR <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">deriving</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> g<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Sum f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>InL x<span style="color: green;">&#41;</span> = InL <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 x<span style="color: green;">&#41;</span>
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>InR y<span style="color: green;">&#41;</span> = InR <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 y<span style="color: green;">&#41;</span></pre>
<p>The Functor instance is straightforward for Sum, but the applicative instance is puzzling. What should "pure" do? It needs to inject into either the left or the right, so clearly we need some form of "bias" in the instance. What we really need is the capacity to "work in" one side of the sum until compelled to switch over to the other, at which point we're stuck there. If two functors, F and G are in a relationship such that we can always send <code>f x -> g x</code> in a way that "respects" fmap (that is to say, such that (<code>fmap f . fToG == ftoG . fmap f</code>) then we call this a natural transformation. The action that sends f to g is typically called "eta". (We actually want something slightly stronger called a "monoidal natural transformation" that respects not only the functorial action <code>fmap</code> but the applicative action <code>&lt;*></code>, but we can ignore that for now).</p>
<p>Now we can assert that as long as there is a natural transformation between g and f, then Sum f g can be made an Applicative, like so:</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">class</span> Natural f g <span style="color: #06c; font-weight: bold;">where</span>
    eta :: f a -&gt; g a
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Applicative f, Applicative g, Natural g f<span style="color: green;">&#41;</span> =&gt;
  Applicative <span style="color: green;">&#40;</span>Sum f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    pure x = InR $ pure x
    <span style="color: green;">&#40;</span>InL f<span style="color: green;">&#41;</span> &lt; *&gt; <span style="color: green;">&#40;</span>InL x<span style="color: green;">&#41;</span> = InL <span style="color: green;">&#40;</span>f &lt; *&gt; x<span style="color: green;">&#41;</span>
    <span style="color: green;">&#40;</span>InR g<span style="color: green;">&#41;</span> &lt; *&gt; <span style="color: green;">&#40;</span>InR y<span style="color: green;">&#41;</span> = InR <span style="color: green;">&#40;</span>g &lt; *&gt; y<span style="color: green;">&#41;</span>
    <span style="color: green;">&#40;</span>InL f<span style="color: green;">&#41;</span> &lt; *&gt; <span style="color: green;">&#40;</span>InR x<span style="color: green;">&#41;</span> = InL <span style="color: green;">&#40;</span>f &lt; *&gt; eta x<span style="color: green;">&#41;</span>
    <span style="color: green;">&#40;</span>InR g<span style="color: green;">&#41;</span> &lt; *&gt; <span style="color: green;">&#40;</span>InL x<span style="color: green;">&#41;</span> = InL <span style="color: green;">&#40;</span>eta g &lt; *&gt; x<span style="color: green;">&#41;</span></pre>
<p>The natural transformation we'll tend to use simply sends any functor to Const.</p>
<pre>instance Monoid mo => Natural f (Const mo) where
    eta = const (Const mempty)</pre>
<p>However, there are plenty of other natural transformations that we could potentially make use of, like so:</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">instance</span> Applicative f =&gt;
  Natural g <span style="color: green;">&#40;</span>Compose f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
     eta = Compose . pure
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Applicative g, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f<span style="color: green;">&#41;</span> =&gt; Natural f <span style="color: green;">&#40;</span>Compose f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
     eta = Compose . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> pure
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Natural f g<span style="color: green;">&#41;</span> =&gt; Natural f <span style="color: green;">&#40;</span>Product f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    eta x = Product x <span style="color: green;">&#40;</span>eta x<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Natural g f<span style="color: green;">&#41;</span> =&gt; Natural g <span style="color: green;">&#40;</span>Product f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    eta x = Product <span style="color: green;">&#40;</span>eta x<span style="color: green;">&#41;</span> x
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Natural <span style="color: green;">&#40;</span>Product f g<span style="color: green;">&#41;</span> f <span style="color: #06c; font-weight: bold;">where</span>
    eta <span style="color: green;">&#40;</span>Product x _ <span style="color: green;">&#41;</span> = x
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Natural <span style="color: green;">&#40;</span>Product f g<span style="color: green;">&#41;</span> g <span style="color: #06c; font-weight: bold;">where</span>
    eta <span style="color: green;">&#40;</span>Product _ x<span style="color: green;">&#41;</span> = x
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Natural g f =&gt; Natural <span style="color: green;">&#40;</span>Sum f g<span style="color: green;">&#41;</span> f <span style="color: #06c; font-weight: bold;">where</span>
    eta <span style="color: green;">&#40;</span>InL x<span style="color: green;">&#41;</span> = x
    eta <span style="color: green;">&#40;</span>InR y<span style="color: green;">&#41;</span> = eta y
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Natural Identity <span style="color: green;">&#40;</span>Reader r<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
    eta <span style="color: green;">&#40;</span>Identity x<span style="color: green;">&#41;</span> = pure x</pre>
<p>In theory, there should also be a natural transformation that can be built magically from the product of any other two natural transformations, but that will just confuse the Haskell typechecker hopelessly. This is because we know that often different "paths" of typeclass choices will often be isomorphic, but the compiler has to actually pick one "canonical" composition of natural transformations to compute with, although multiple paths will typically be possible.</p>
<p>For similar reasons of avoiding overlap, we can't both have the terminal homomorphism that sends everything to "Const" <b>and</b> the initial homomorphism that sends "Identity" to anything like so:</p>
<pre class="haskell"><span style="color: #5d478b; font-style: italic;">-- instance Applicative g =&gt; Natural Identity g where</span>
<span style="color: #5d478b; font-style: italic;">--     eta (Identity x) = pure x</span>
&nbsp;</pre>
<p>We choose to keep the terminal transformation around because it is more generally useful for our purposes. As the comments below point out, it turns out that a version of "Sum" with the initial transformation baked in now lives in transformers as <code>Lift</code>.</p>
<p>In any case we can now write a proper Validation applicative:</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">type</span> Validation mo = Sum <span style="color: green;">&#40;</span>Const mo<span style="color: green;">&#41;</span> Identity
&nbsp;
validationError :: Monoid mo =&gt; mo -&gt; Validation mo a
validationError x = InL <span style="color: green;">&#40;</span>Const x<span style="color: green;">&#41;</span></pre>
<p>This applicative will yield either a single result, or an accumulation of monoidal errors. It exists on hackage in the <a href="http://hackage.haskell.org/package/Validation">Validation</a> package.</p>
<p>Now, based on the same principles, we can produce a full Formlet.</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">type</span> Formlet mo err env a =
    Product <span style="color: green;">&#40;</span>Const mo<span style="color: green;">&#41;</span>
            <span style="color: green;">&#40;</span>Compose <span style="color: green;">&#40;</span>Reader env<span style="color: green;">&#41;</span>
                     <span style="color: green;">&#40;</span>Sum <span style="color: green;">&#40;</span>Const err<span style="color: green;">&#41;</span> Identity<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
    a</pre>
<p>All the type and newtype noise looks a bit ugly, I'll grant. But the idea is to <strong>think</strong> with structures built with applicatives, which gives guarantees that we're building applicative structures, and furthermore, structures with certain guarantees in terms of which components can be interpreted independently of which others. So, for example, we can strip away the newtype noise and find the following:</p>
<pre class="haskell"><span style="color: #06c; font-weight: bold;">type</span> FormletClean mo err env a = <span style="color: green;">&#40;</span>mo, env -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a> err a<span style="color: green;">&#41;</span></pre>
<p>Because we built this up from our basic library of applicatives, we also know how to write its applicative instance directly.</p>
<p>Now that we've gotten a basic algebraic vocabulary of applicatives, and especially now that we've produced this nifty Sum applicative (which I haven't seen presented before), we've gotten to where I intended to stop.</p>
<p>But lots of other questions arise, on two axes. First, what other typeclasses beyond applicative do our constructions satisfy? Second, what basic pieces of vocabulary are missing from our constructions — what do we need to add to flesh out our universe of discourse? (Fixpoints come to mind).</p>
<p>Also, what statements can we make about "completeness" — what portion of the space of all applicatives can we enumerate and construct in this way? Finally, why is it that monoids seem to crop up so much in the course of working with Applicatives? I plan to tackle at least some of these questions in future blog posts.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2012/abstracting-with-applicatives/feed/</wfw:commentRss>
		<slash:comments>56</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>Catamorphism Knol</title>
		<link>http://comonad.com/reader/2012/catamorphism-knol/</link>
		<comments>http://comonad.com/reader/2012/catamorphism-knol/#comments</comments>
		<pubDate>Sun, 27 May 2012 18:17:24 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=579</guid>
		<description><![CDATA[I was contacted by someone who wanted to read my old catamorphism knol, despite the fact that Google Knol is no more. 
Fortunately, while it was rather inconvenient that they shut down Google Knol completely, and I'll forever remember a knol as a "unit of abandonment", Google did provide a nice way to download at [...]]]></description>
			<content:encoded><![CDATA[<p>I was contacted by someone who wanted to read my old catamorphism knol, despite the fact that Google Knol is no more. </p>
<p>Fortunately, while it was rather inconvenient that they shut down Google Knol completely, and I'll forever remember a knol as a "unit of abandonment", Google did provide a nice way to download at least your own user content and for that I am grateful.</p>
<p>I have fixed up the internal linkage as much as possible and have placed a copy of the original article below.</p>
<p><a href="http://comonad.com/haskell/catamorphisms.html">Catamorphisms: A Knol</a></p>
<p>Sadly, as I am not "Dark Magus", I am unable to download the Russian translation. If anyone knows how to contact him, I would love to obtain and preserve a copy of the translation as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2012/catamorphism-knol/feed/</wfw:commentRss>
		<slash:comments>405</slash:comments>
		</item>
		<item>
		<title>What Constraints Entail: Part 1</title>
		<link>http://comonad.com/reader/2011/what-constraints-entail-part-1/</link>
		<comments>http://comonad.com/reader/2011/what-constraints-entail-part-1/#comments</comments>
		<pubDate>Thu, 03 Nov 2011 05:46:11 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Constraint Kinds]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Type Hackery]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=430</guid>
		<description><![CDATA[Max Bolingbroke has done a wonderful job on adding Constraint kinds to GHC.
Constraint Kinds adds a new kind Constraint, such that Eq :: * -> Constraint, Monad :: (* -> *) -> Constraint, but since it is a kind, we can make type families for constraints, and even parameterize constraints on constraints. 
So, let's play [...]]]></description>
			<content:encoded><![CDATA[<p>Max Bolingbroke has done a wonderful job on adding Constraint kinds to GHC.</p>
<p>Constraint Kinds adds a new kind <code>Constraint</code>, such that <code>Eq :: * -> Constraint</code>, <code>Monad :: (* -> *) -> Constraint</code>, but since it is a kind, we can make type families for constraints, and even parameterize constraints <em>on</em> constraints. </p>
<p>So, let's play with them and see what we can come up with!</p>
<p><span id="more-430"></span></p>
<h2>A Few Extensions</h2>
<p>First, we'll need a few language features:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# LANGUAGE
  CPP,
  ScopedTypeVariables,
  FlexibleInstances,
  FlexibleContexts,
  ConstraintKinds,
  KindSignatures,
  TypeOperators,
  FunctionalDependencies,
  Rank2Types,
  StandaloneDeriving,
  GADTs
  #-}</span>
&nbsp;</pre>
<p>Because of the particular version of GHC I'm using I'll also need</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# LANGUAGE UndecidableInstances #-}</span>
#define UNDECIDABLE
&nbsp;</pre>
<p>but this bug has been fixed in the current version of GHC Head. I'll be explicit about any instances that need UndecidableInstances by surrounding them in an <code>#ifdef UNDECIDABLE</code> block.</p>
<h2>Explicit Dictionaries</h2>
<p>So with that out of the way, let's import some definitions</p>
<pre class="haskell">&nbsp;
<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>.Instances
<span style="color: #06c; font-weight: bold;">import</span> Control.Applicative
<span style="color: #06c; font-weight: bold;">import</span> Data.Monoid
<span style="color: #06c; font-weight: bold;">import</span> Data.Complex
<span style="color: #06c; font-weight: bold;">import</span> Data.Ratio
<span style="color: #06c; font-weight: bold;">import</span> Unsafe.Coerce
&nbsp;</pre>
<p>and make one of our own that shows what we get out of making Constraints into a kind we can manipulate like any other.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Dict a <span style="color: #06c; font-weight: bold;">where</span>
  Dict :: a =&gt; Dict a
&nbsp;</pre>
<p>Previously, we coud make a Dict like data type for any one particular class constraint that we wanted to capture, but now we can write this type once and for all. The act of pattern matching on the Dict constructor will bring the constraint 'a' into scope.</p>
<p>Of course, in the absence of incoherent and overlapping instances there is at most one dictionary of a given type, so we could make instances, like we can for any other data type, but standalone deriving is smart enough to figure these out for me. (Thanks copumpkin!)</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: #06c; font-weight: bold;">instance</span> <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> <span style="color: green;">&#40;</span>Dict a<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: #06c; font-weight: bold;">instance</span> <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> <span style="color: green;">&#40;</span>Dict a<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a> <span style="color: green;">&#40;</span>Dict a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>If we're willing to turn on UndecidableInstances to enable the polymorphic constraint we can even add:</p>
<pre class="haskell">&nbsp;
#ifdef UNDECIDABLE
<span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: #06c; font-weight: bold;">instance</span> a =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Read"><span style="background-color: #efefbf; font-weight: bold;">Read</span></a> <span style="color: green;">&#40;</span>Dict a<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">instance</span> a =&gt; Monoid <span style="color: green;">&#40;</span>Dict a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  mappend Dict Dict = Dict
  mempty = Dict
#endif
&nbsp;</pre>
<p>and similar polymorphically constrained instances for <code>Enum</code>, <code>Bounded</code>, etc.</p>
<h2>Entailment</h2>
<p>For that we'll need a notion of entailment.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixr</span> <span style="color: red;">9</span> :-
<span style="color: #06c; font-weight: bold;">newtype</span> a :- b = Sub <span style="color: green;">&#40;</span>a =&gt; Dict b<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:Eq"><span style="background-color: #efefbf; font-weight: bold;">Eq</span></a> <span style="color: green;">&#40;</span>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:True"><span style="font-weight: bold;">True</span></a>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="background-color: #efefbf; font-weight: bold;">Ord</span></a> <span style="color: green;">&#40;</span>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:compare"><span style="font-weight: bold;">compare</span></a> _ _ = EQ
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a> <span style="color: green;">&#40;</span>a :- b<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  showsPrec d _ = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:showParen"><span style="font-weight: bold;">showParen</span></a> <span style="color: green;">&#40;</span>d &gt; <span style="color: red;">10</span><span style="color: green;">&#41;</span> $
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:showString"><span style="font-weight: bold;">showString</span></a> <span style="color: #3c7331;">&quot;Sub Dict&quot;</span>
&nbsp;</pre>
<p>Here we're saying that <code>Sub</code> takes one argument, which is a computation that when implicitly given a constraint of type <em>a</em>, can give me back a dictionary for the type <em>b</em>. Moreover, as a newtype it adds no overhead that isn't aleady present in manipulating terms of type (a => Dict b) directly.</p>
<p>The simplest thing we can define with this is that entailment is reflexive.</p>
<pre class="haskell">&nbsp;
refl :: a :- a
refl = Sub Dict
&nbsp;</pre>
<p>Max has already written up a nice restricted monad example using these, but what I want to play with today is the category of substitutability of constraints, but there are a few observations I need to make, first.</p>
<p>ConstraintKinds overloads <code>()</code> and <code>(a,b)</code> to represent the trivial constraint and the product of two constraints respectively. </p>
<p>The latter is done with a bit of a hack, which we'll talk about in a minute, but we can use the former as a terminal object for our category of entailments.</p>
<pre lang="haskell>
top :: a :- ()
top = Sub Dict
</pre>
<p>We can weaken the constraint, in a manner similar to fst or snd:</p>
<pre class="haskell">&nbsp;
weaken1 :: <span style="color: green;">&#40;</span>a, b<span style="color: green;">&#41;</span> :- a
weaken1 = Sub Dict
&nbsp;
weaken2 :: <span style="color: green;">&#40;</span>a, b<span style="color: green;">&#41;</span> :- b
weaken2 = Sub Dict
&nbsp;</pre>
<p>Constraints are idempotent, so we can duplicate one, perhaps as a prelude to transforming one of them into something else.</p>
<pre class="haskell">&nbsp;
contract :: a :- <span style="color: green;">&#40;</span>a, a<span style="color: green;">&#41;</span>
contract = Sub Dict
&nbsp;</pre>
<p>But to do much more complicated, we're going to need a notion of substitution, letting us use our entailment relation to satisfy obligations.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">1</span> \\ <span style="color: #5d478b; font-style: italic;">-- required comment</span>
<span style="color: green;">&#40;</span>\\<span style="color: green;">&#41;</span> :: a =&gt; <span style="color: green;">&#40;</span>b =&gt; r<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a :- b<span style="color: green;">&#41;</span> -&gt; r
r \\ Sub Dict = r
&nbsp;</pre>
<p>The type says that given that a constraint <em>a</em> can be satisfied, a computation that needs a constraint of type <em>b</em> to be satisfied in order to obtain a result, and the fact that <em>a</em> entails <em>b</em>, we can compute the result. </p>
<p>The constraint <em>a</em> is satisfied by the type signature, and the fact that we get quietly passed whatever dictionary is needed. Pattern matching on Sub brings into scope a computation of type <code>(a => Dict b)</code>, and we are able to discharge the <em>a</em> obligation, using the dictionary we were passed, Pattern matching on <code>Dict</code> forces that computation to happen and brings b into scope, allowing us to meet the obligation of the computation of r. All of this happens for us behind the scenes just by pattern matching.</p>
<p>So what can we do with this?</p>
<p>We can use \\ to compose constraints.</p>
<pre class="haskell">&nbsp;
trans :: <span style="color: green;">&#40;</span>b :- c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a :- b<span style="color: green;">&#41;</span> -&gt; a :- c
trans f g = Sub $ Dict \\ f \\ g
&nbsp;</pre>
<p>In fact, the way the dictionaries get plumbed around inside the argument to Sub is rather nice, because we can give that same definition different type signatures, letting us make (,) more product-like, giving us the canonical product morphism to go with the weakenings/projections we defined above.</p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#40;</span>&amp;&amp;&amp;<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span>a :- b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a :- c<span style="color: green;">&#41;</span> -&gt; a :- <span style="color: green;">&#40;</span>b, c<span style="color: green;">&#41;</span>
f &amp;&amp;&amp; g = Sub $ Dict \\ f \\ g
&nbsp;</pre>
<p>And since we're using it as a product, we can make it act like a bifunctor also using the same definition.</p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#40;</span>***<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span>a :- b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>c :- d<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a, c<span style="color: green;">&#41;</span> :- <span style="color: green;">&#40;</span>b, d<span style="color: green;">&#41;</span>
f *** g = Sub $ Dict \\ f \\ g
&nbsp;</pre>
<h2>Limited Sub-Superkinding?</h2>
<p>Ideally we'd be able to capture something like that bifunctoriality using a type like</p>
<pre class="haskell">&nbsp;
#if <span style="color: red;">0</span>
<span style="color: #06c; font-weight: bold;">class</span> BifunctorS <span style="color: green;">&#40;</span>p :: Constraint -&gt; Constraint -&gt; Constraint<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  bimapS :: <span style="color: green;">&#40;</span>a :- b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>c :- d<span style="color: green;">&#41;</span> -&gt; p a c :- p b d
#endif
&nbsp;</pre>
<p>In an even more ideal world, it would be enriched using something like</p>
<pre class="haskell">&nbsp;
#ifdef POLYMORPHIC_KINDS
<span style="color: #06c; font-weight: bold;">class</span> Category <span style="color: green;">&#40;</span>k :: x -&gt; x -&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> :: k a a
  <span style="color: green;">&#40;</span>.<span style="color: green;">&#41;</span> :: k b c -&gt; k a b -&gt; k a c
<span style="color: #06c; font-weight: bold;">instance</span> Category <span style="color: green;">&#40;</span>:-<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> = refl
  <span style="color: green;">&#40;</span>.<span style="color: green;">&#41;</span> = trans
#endif
&nbsp;</pre>
<p>where x is a <strong>kind variable</strong>, then we could obtain a more baroque and admittedly far less thought-out bifunctor class like:</p>
<pre class="haskell">&nbsp;
#if <span style="color: red;">0</span>
<span style="color: #06c; font-weight: bold;">class</span> Bifunctor <span style="color: green;">&#40;</span>p :: x -&gt; y -&gt; z<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <span style="color: #06c; font-weight: bold;">type</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Left"><span style="font-weight: bold;">Left</span></a> p :: x -&gt; x -&gt; *
  <span style="color: #06c; font-weight: bold;">type</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Left"><span style="font-weight: bold;">Left</span></a> p = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span>
  <span style="color: #06c; font-weight: bold;">type</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a> p :: y -&gt; y -&gt; *
  <span style="color: #06c; font-weight: bold;">type</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a> p = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span>
  <span style="color: #06c; font-weight: bold;">type</span> Cod p :: z -&gt; z -&gt; *
  <span style="color: #06c; font-weight: bold;">type</span> Cod p = <span style="color: green;">&#40;</span>-&gt;<span style="color: green;">&#41;</span>
  bimap :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Left"><span style="font-weight: bold;">Left</span></a> p a b -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a> p c d -&gt; Cod p <span style="color: green;">&#40;</span>p a c<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>p b d<span style="color: green;">&#41;</span>
#endif
&nbsp;</pre>
<p>Or even more more ideally, you could use the fact that we can directly define product categories!</p>
<p>Since they are talking about kind-indexing for classes and type families, we could have separate bifunctors for (,) for both kinds * and Constraint.</p>
<p>The current constraint kind code uses a hack to let (a,b) be used as a type inhabiting * and as the syntax for constraints. This hack is limited however. It only works when the type (,) is fully applied to its arguments. Otherwise you'd wind up with the fact that the type (,) needs to have both of these kinds:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- (,) :: Constraint -&gt; Constraint -&gt; Constraint and</span>
<span style="color: #5d478b; font-style: italic;">-- (,) :: * -&gt; * -&gt; *</span>
&nbsp;</pre>
<p>What is currently done is that the kind magically switches for <code>()</code> and <code>(,)</code> in certain circumstances. GHC already had some support for this because it parses <code>(Foo a, Bar b)</code> as a type in <code>(Foo a, Bar b) => Baz a b</code> before transforming it into a bunch of constraints.</p>
<p>Since we already have a notion of sub-kinding at the kind level, we could solve this for <code>()</code> by making up a new kind, say, <code>???</code> which is the subkind of both <code>*</code> and <code>Constraint</code>, but this would break the nice join lattice properties of the current system.</p>
<p>[Edit: in the initial draft, I had said superkind]</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">--    ?</span>
<span style="color: #5d478b; font-style: italic;">--   / \</span>
<span style="color: #5d478b; font-style: italic;">-- (#)  ??</span>
<span style="color: #5d478b; font-style: italic;">--     /  \</span>
<span style="color: #5d478b; font-style: italic;">--    #    *  Constraint</span>
<span style="color: #5d478b; font-style: italic;">--          \ /</span>
<span style="color: #5d478b; font-style: italic;">--          ???</span>
&nbsp;</pre>
<p>But this doesn't address the kind of <code>(,)</code> above. With the new polymorphic kinds that Brent Yorgey and company have been working on and a limited notion of sub-superkinding, this could be resolved by making a new super-kind <code>@</code> that is the super-kind of both <code>*</code> and <code>Constraint</code>, and which is a sub-superkind of the usual unnamed Box superkind. </p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- Box</span>
<span style="color: #5d478b; font-style: italic;">--  |</span>
<span style="color: #5d478b; font-style: italic;">--  @</span>
&nbsp;</pre>
<p>Then we can have:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- (,) :: forall (k :: @). k -&gt; k -&gt; k</span>
<span style="color: #5d478b; font-style: italic;">-- () :: forall (k :: @). k</span>
&nbsp;</pre>
<p>and kind checking/inference will do the right thing about keeping the kind ambiguous for types like <code>(,) () :: forall (k :: @). k</code></p>
<p>This would get rid of the hack and let me make a proper bifunctor for <code>(,)</code> in the category of entailments.</p>
<p>The version of GHC head I'm working with right now doesn't support polymorphic kinds, so I've only been playing with these in a toy type checker, but I'm really looking forward to being able to have product categories!</p>
<h2>Stay Tuned</h2>
<p><a href="http://comonad.com/reader/2011/what-constraints-entail-part-2/">Next</a>, we'll go over how to reflect the class and instance declarations so we can derive entailment of a superclass for a class, and the entailment of instances.</p>
<p>[<a href="https://github.com/ekmett/constraints/blob/master/Data/Constraint.hs">Source</a>]</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/what-constraints-entail-part-1/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Homotopy and Directed Type Theory Slides</title>
		<link>http://comonad.com/reader/2011/homotopy-and-directed-type-theory-slides/</link>
		<comments>http://comonad.com/reader/2011/homotopy-and-directed-type-theory-slides/#comments</comments>
		<pubDate>Fri, 28 Oct 2011 02:38:34 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Boston Haskell]]></category>
		<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Type Theory]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=425</guid>
		<description><![CDATA[As requested, here are the slides from Dan Doel's excellent presentation on Homotopy and Directed Type Theory from this past Monday's Boston Haskell.
]]></description>
			<content:encoded><![CDATA[<p>As requested, here are the slides from Dan Doel's excellent presentation on <a href='http://comonad.com/reader/wp-content/uploads/2011/10/slides.pdf'>Homotopy and Directed Type Theory</a> from this past Monday's <a href="http://groups.google.com/group/bostonhaskell/browse_thread/thread/9892caece9ebb4d4">Boston Haskell</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/homotopy-and-directed-type-theory-slides/feed/</wfw:commentRss>
		<slash:comments>0</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>
	</channel>
</rss>
