<?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; Data Structures</title>
	<atom:link href="http://comonad.com/reader/category/data-structures/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>Internalized Guarded Recursion for Equational Reasoning</title>
		<link>http://comonad.com/reader/2022/internalized-guarded-recursion-for-equational-reasoning/</link>
		<comments>http://comonad.com/reader/2022/internalized-guarded-recursion-for-equational-reasoning/#comments</comments>
		<pubDate>Fri, 21 Oct 2022 18:32:49 +0000</pubDate>
		<dc:creator>Gershom Bazerman</dc:creator>
				<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[circular substitution]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=1171</guid>
		<description><![CDATA[I recently presented a paper on infinite traversals at the Haskell Symposium: <a href="https://gbaz.github.io/papers/3546189.3549915.pdf">A totally predictable outcome: an investigation of traversals of infinite structures</a>. The main result there is a characterization of when a call to <code>traverse</code> on an infinite Traversable functor (like an infinite lazy list) yields a non-bottom result. It turns out this is a condition on the Applicative one traverses with that loosely amounts to it having only a single data constructor. What I want to talk about here is how the technique introduced in that paper, which I call "internal guarded recursion" can be used not only in a lightweight formal way to prove characterization theorems or the like, but just in everyday programming as a "back of the envelope" or "streetfighting" hack to quickly figure out when recursive functional programs terminate and when they go into infinite loops.
]]></description>
			<content:encoded><![CDATA[<p>I recently <a href="https://www.youtube.com/watch?v=xdUgkGqKjS8">presented a paper</a> on infinite traversals at the Haskell Symposium: <a href="https://gbaz.github.io/papers/3546189.3549915.pdf">A totally predictable outcome: an investigation of traversals of infinite structures</a>. The main result there is a characterization of when a call to <code>traverse</code> on an infinite Traversable functor (like an infinite lazy list) yields a non-bottom result. It turns out this is a condition on the Applicative one traverses with that loosely amounts to it having only a single data constructor. What I want to talk about here is how the technique introduced in that paper, which I call "internal guarded recursion" can be used not only in a lightweight formal way to prove characterization theorems or the like, but just in everyday programming as a "back of the envelope" or "streetfighting" hack to quickly figure out when recursive functional programs terminate and when they go into infinite loops.</p>
<p>Let's talk about the basic trick that makes the whole thing work. First, we introduce an abstract newtype for identity, which we will disallow pattern matching against, and instead only allow access to through the structure of an applicative functor.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Later a = Later a <span style="color: #06c; font-weight: bold;">deriving</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>
<span style="color: #06c; font-weight: bold;">instance</span> Applicative Later <span style="color: #06c; font-weight: bold;">where</span>
    pure = Later
    Later f &lt; *&gt; Later x = Later <span style="color: green;">&#40;</span>f x<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Next, we introduce the <em>only</em> function allowed to perform recursion:</p>
<pre class="haskell">&nbsp;
lfix :: <span style="color: green;">&#40;</span>Later a -&gt; a<span style="color: green;">&#41;</span> -&gt; a
lfix f = fix <span style="color: green;">&#40;</span>f . pure<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>This function has almost the same type signature as the typical fixpoint operator, but it "guards" the argument to the function it is taking the fixedpoint of by our abstract <code>Later</code> type constructor.</p>
<p>Now, if you write code that only has recursion via `lfix` and no other function can implicitly or explicitly invoke itself (which the paper refers to as "working in the guarded fragment), your code will <i>never produce a bottom</i>. You can have whatever sorts of recursive Haskell '98 data definitions you like, it doesn't matter! (However, if you have "impredicative" datatypes that pack polymorphic functions into them, I think it would matter... but let's leave that aside). Try, for example, using only this form of recursion, to write a function that produces an infinite list. You'll realize that each recursive step requires using up one <code>Later</code> constructor as "fuel". And since there's no way to get an infinite amount of <code>Later</code> constructors to begin with, you'll only be able to produce lists of finite depth.</p>
<p>However, we <em>can</em> create related data structures to our existing ones, which "guard" their own recurrence behind a <code>Later</code> type constructor as well -- and we can create, consume and manipulate those also, and also do so without risk of writing an expression that produces a bottom. For example, here is the type of possibly infinite lists:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Stream a =
    Nil
    | Cons a <span style="color: green;">&#40;</span>Later <span style="color: green;">&#40;</span>Stream a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>And here is a function that interleaves two such lists:</p>
<pre class="haskell">&nbsp;
sinterleave :: Stream a -&gt; Stream a -&gt; Stream a
sinterleave = lfix $ \f s1 s2 -&gt; <span style="color: #06c; font-weight: bold;">case</span> s1 <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span>Cons x xs<span style="color: green;">&#41;</span> -&gt; Cons x <span style="color: green;">&#40;</span>f &lt; *&gt; pure s2 &lt; *&gt; xs<span style="color: green;">&#41;</span>
    _ -&gt; s2
&nbsp;</pre>
<p>Now, I'm going to diverge from the paper and pose a sort of general problem, based on some discussions I had at ICFP. Suppose you have some tricky recursion, possibly involving "<a href="https://wiki.haskell.org/Tying_the_Knot">tying the knot</a>" and want to show that it terminates, or to figure out under which conditions it terminates -- how can you do that? It turns out that internal guarded recursion can help! Here's the recipe:</p>
<p>1. Write your function using only explicit recursion (via <code>fix</code>).<br />
2. Change <code>fix</code> to <code>lfix</code><br />
3. Figure out what work you have to do adding applicative operations involving <code>Later</code> to fix the types.</p>
<p>The paper has in it a general theorem that says, loosely speaking, that if you have code involving <code>lfix</code> and <code>Later</code>, and change that back to <code>fix</code> and erase all the mucking around with <code>Later</code> you get "essentially the same" function, and you still have a guarantee it won't produce bottoms. So this just turns that around -- start with your normal code, and show you can write it even in the guarded fragment, and then that tells you the properties of your original code!</p>
<p>I'll present this approach to reasoning about two tricky but well known problems in functional programming. First, as suggested by Tom Schrijvers as a question at the talk, is the famous "repmin" function introduced by Bird in <a href="https://link.springer.com/article/10.1007/BF00264249">1984</a>. This is a program that makes essential use of laziness to traverse a tree only once, but replacing each element in the tree by the minimum element anywhere in the tree. Here's a quick one-liner version, making use of traversal in the writer monad -- it works over any finite traversable structure, including typical trees. But it is perhaps easiest to test it over lists. For now, we'll ignore the issue of what happens with traversals of infinite structures, as that will complicate the example.</p>
<pre class="haskell">&nbsp;
repMin1 :: <span style="color: green;">&#40;</span>Traversable t, <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> a<span style="color: green;">&#41;</span> =&gt; t a -&gt; t a
repMin1 xs =
     <span style="color: #06c; font-weight: bold;">let</span> <span style="color: green;">&#40;</span>ans,m<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> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:minimum"><span style="font-weight: bold;">minimum</span></a> . runWriter $
                    traverse <span style="color: green;">&#40;</span>\x -&gt; tell <span style="color: green;">&#91;</span>x<span style="color: green;">&#93;</span> &gt;&gt; pure m<span style="color: green;">&#41;</span> xs <span style="color: #06c; font-weight: bold;">in</span> ans
&nbsp;</pre>
<p>Note that this above definition makes use of a recursive definition -- the body of the definition of <code>(ans,m)</code> makes use of the <code>m</code> being defined.  This works because the definition does not pattern match on the m to compute -- otherwise we would bottom out. Using internal guarded recursion, we can let the type system guide us into rewriting our code into a form where it is directly evident that this does not bottom, rather than relying on careful reasoning about semantics. The first step is to mechanically transform the initial definition into one that is exactly the same, but where the implicit recursion has been rendered explicit by use of fix:</p>
<pre class="haskell">&nbsp;
repMin2 :: <span style="color: green;">&#40;</span>Traversable t, <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> a<span style="color: green;">&#41;</span> =&gt; t a -&gt; t a
repMin2 xs =
  <span style="color: #06c; font-weight: bold;">let</span> res = fix go <span style="color: #06c; font-weight: bold;">in</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a> res
   <span style="color: #06c; font-weight: bold;">where</span>
    go res = <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:minimum"><span style="font-weight: bold;">minimum</span></a> . runWriter $
               traverse <span style="color: green;">&#40;</span>\x -&gt; tell <span style="color: green;">&#91;</span>x<span style="color: green;">&#93;</span> &gt;&gt; pure <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> res<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> xs
&nbsp;</pre>
<p>The next step is to now replace <code>fix</code> by <code>lfix</code>. When we do so, the type of <code>go</code> will no longer be correct. In particular, its argument, <code>res</code> will now be guarded by a <code>Later</code>. So we can no longer apply <code>snd</code> directly to it, but instead have to <code>fmap</code>. The compiler will notice this and yell at us, at which point we make that small tweak as well. In turn, this forces a change to the type signature of the overall function. With that done, everything still checks!</p>
<pre class="haskell">&nbsp;
repMin3 :: <span style="color: green;">&#40;</span>Traversable t, <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> a<span style="color: green;">&#41;</span> =&gt; t a -&gt; t <span style="color: green;">&#40;</span>Later a<span style="color: green;">&#41;</span>
repMin3 xs =
  <span style="color: #06c; font-weight: bold;">let</span> res = lfix go <span style="color: #06c; font-weight: bold;">in</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a> res
   <span style="color: #06c; font-weight: bold;">where</span>
    go res = <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:minimum"><span style="font-weight: bold;">minimum</span></a> . runWriter $
                traverse <span style="color: green;">&#40;</span>\x -&gt; tell <span style="color: green;">&#91;</span>x<span style="color: green;">&#93;</span> &gt;&gt; pure <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> &lt; $&gt; res<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> xs
&nbsp;</pre>
<p>We have now verified that the original <code>repMin1</code> function does not bottom out on finite structures. Further, the "one layer" of <code>Later</code> in the type of <code>repMin3</code> tells us that there was exactly one recursive step invoked in computing the final result!</p>
<p>The astute reader may have noticed a further complication -- to genuinely be in the guarded recursive fragment, we need to make sure all functions in sight have not been written using standard recursion, but only with guarded recursion. But in fact, both <code>minimum</code> and <code>traverse</code> are going to be written recursively! We limited ourselves to considering finite trees to avoid worrying about this for our example. But let's now briefly consider what happens otherwise. By the results in the paper, we can still use a guarded recursive traverse in the writer monad, which will produce a potentially productive stream of results -- one where there may be arbitrarily many <code>Later</code> steps between each result. Further, a guarded recursive <code>minimum</code> on such a stream, or even on a necessarily productive <code>Stream</code> as given above, will necessarily produce a value that is potentially infinitely delayed. So without grinding out the detailed equational substitution, we can conclude that the type signature we would have to produce in the case of a potentially infinite tree would in fact be: <code>(Traversable t, Ord a) => t a -> t (Partial a)</code> -- where a partial value is one that may be delayed behind an arbitrary (including infinite) sequence of <code>Later</code>. This in turns tells us that <code>repMin</code> on a potentially infinite structure would still produce safely the <em>skeleton</em> of the structure we started with. However, at each individual leaf, the value would potentially be bottom. And, in fact, by standard reasoning (it takes an infinite amount of time to find the minimum of an infinite stream), we can conclude that when <code>repMin</code> is run on an infinite structure, then indeed each leaf <em>would</em> be bottom!</p>
<p>We'll now consider one further example, arising from <a href="https://scholarworks.brandeis.edu/esploro/outputs/undergraduate/Getting-A-Quick-Fix-On-Comonads/9923880018001921">work by Kenneth Foner</a> on fixed points of comonads. In their paper, Foner provides an efficient fixed point operator for comonads with an "apply" operator, but also makes reference to an inefficient version which they believe has the same semantics, and was introduced by Dominic Orchard. This latter operator is extremely simple to define, and so an easy candidate for an example. We'll first recall the methods of comonads, and then introduce Orchard's fixed-point:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> 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> w <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
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a> :: w a -&gt; w <span style="color: green;">&#40;</span>w a<span style="color: green;">&#41;</span>
    <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> :: <span style="color: green;">&#40;</span>w a -&gt; b<span style="color: green;">&#41;</span> -&gt; w a -&gt; w b
&nbsp;
cfix f :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; <span style="color: green;">&#40;</span>w a -&gt; a<span style="color: green;">&#41;</span> -&gt; w a
cfix f = fix <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> f<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>So the question is -- when does cfix not bottom out? To answer this, we again just change <code>fix</code> to <code>lfix</code> and let the typechecker tells us what goes wrong. We quickly discover that our code no longer typechecks, because <code>lfix</code> enforces we are given a <code>Later (w a)</code> but the argument to <code>extend f</code> needs to be a plain old <code>w a</code>. We ask ghc for the type of the intermediate conversion function necessary, and arrive at the following:</p>
<pre class="haskell">&nbsp;
lcfix :: <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w =&gt; <span style="color: green;">&#40;</span>Later <span style="color: green;">&#40;</span>w b<span style="color: green;">&#41;</span> -&gt; w a<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>w a -&gt; b<span style="color: green;">&#41;</span> -&gt; w b
lcfix conv f = lfix <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> f . conv<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>So we discover that comonad fix will not bottom when we can provide some <code>conv</code> function that is "like the identity" (so it erases away when we strip out the mucking about with <code>Later</code>) but can send <code>Later (w a) -> w b</code>. If we choose to unify <code>a</code> and <code>b</code>, then this property (of some type to be equipped with an "almost identity" between it and it delayed by a <code>Later</code>) is examined in the paper at some length under the name "stability" -- and our conclusion is that cfix will terminate when the type <code>w a</code> is stable (which is to say that it in one way or another represents a potentially partial value). Also from the paper, we know that one easy way to get stability is when the type <code>w</code> is <code>Predictable</code> -- i.e. when it has an "almost identity" map <code>Later (w a) -> w (Later a)</code> and when <code>a</code> itself is stable. This handles most uses of comonad fix -- since functors of "fixed shape" (otherwise known as representable, or iso to <code>r -> a</code> for a fixed <code>r</code>) are all stable. And the stability condition on the underlying <code>a</code> tells us that even though we'll get out a perfectly good spine, whether or not there will be a bottom value at any given location in the resultant <code>w a</code> depends on the precise function being passed in.</p>
<p>In fact, if we simply start with the idea of predictability in hand, we can specialize the above code in a different way, by taking <code>predict</code> itself to be our conversion function, and unifying <code>b</code> with <code>Later a</code>, which yields the following:</p>
<pre class="haskell">&nbsp;
lcfix2 :: <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> w, Predict w<span style="color: green;">&#41;</span> =&gt; <span style="color: green;">&#40;</span>w <span style="color: green;">&#40;</span>Later a<span style="color: green;">&#41;</span> -&gt; a<span style="color: green;">&#41;</span> -&gt; w a
lcfix2 f = lfix <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extend"><span style="font-weight: bold;">extend</span></a> f . predict<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>This signature is nice because it does not require stability -- i.e. there is no possibility of partial results. Further, it is particularly suggestive -- it looks almost like that of <code>lfix</code> but lifts both the input to the argument and the output of the fixed-point up under a <code>w</code>. This warns us how hard it is to get useful values out of fixing a comonad -- in particular, just as with our <code>lfix</code> itself, we can't directly pattern match on the values we are taking fixed points of, but instead only use them in constructing larger structures.</p>
<p>These examples illustrate both the power of the internal guarded recursion approach, and also some of its limits. It can tell us a lot of high level information about what does and doesn't produce bottoms, and it can produce conditions under which bottoms will never occur. However, there are also cases where we have code that sometimes bottoms, depending on specific functions it is passed -- the fact that it potentially bottoms is represented in the type, but the exact conditions under which bottoms will or will not occur aren't able to be directly "read off". In fact, in the references to the paper, there are much richer variants of guarded recursion that allow more precision in typing various sorts of recursive functions, and of course there is are general metamathematical barriers to going sufficiently far -- a typing system rich enough to say if any integer function terminates is also rich enough to say if e.g. the collatz conjecture is true or not! But with all those caveats in mind, I think this is still a useful tool that doesn't only have theoretical properties, but also practical use. The next time you have a tricky recursive function that you're <em>pretty sure</em> terminates, try these simple steps: 1) rewrite to use explicit fixed points; 2) change those to guarded recursive fixed points; 3) let ghc guide you in fixing the types; 4) see what you learn!</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2022/internalized-guarded-recursion-for-equational-reasoning/feed/</wfw:commentRss>
		<slash:comments>0</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>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>Mirrored Lenses</title>
		<link>http://comonad.com/reader/2012/mirrored-lenses/</link>
		<comments>http://comonad.com/reader/2012/mirrored-lenses/#comments</comments>
		<pubDate>Mon, 25 Jun 2012 03:38:41 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Lenses]]></category>
		<category><![CDATA[accessors]]></category>
		<category><![CDATA[functional references]]></category>
		<category><![CDATA[lens families]]></category>
		<category><![CDATA[van Laarhoven]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=600</guid>
		<description><![CDATA[Lenses are a great way to deal with functional references, but there are two common issues that arise from their use. 

There is a long-standing folklore position that lenses do not support polymorphic updates. This has actually caused a fair bit of embarrassment for the folks who'd like to incorporate lenses in any Haskell record [...]]]></description>
			<content:encoded><![CDATA[<p>Lenses are a great way to deal with functional references, but there are two common issues that arise from their use. </p>
<ol>
<li>There is a long-standing folklore position that lenses do not support polymorphic updates. This has actually caused a fair bit of embarrassment for the folks who'd like to incorporate lenses in any Haskell record system improvement.</li>
<li>Access control. It'd be nice to have read-only or write-only properties -- "one-way" or "mirrored" lenses, as it were. Moreover, lenses are commonly viewed as an all or nothing proposition, in that it is hard to mix them with arbitrary user functions.</li>
<li>Finally there is a bit of a cult around trying to generalize lenses by smashing a monad in the middle of them somewhere, it would be nice to be able to get into a list and work with each individual element in it without worrying about someone mucking up our lens laws, and perhaps avoid the whole generalized lens issue entirely.</li>
</ol>
<p>We'll take a whack at each of these concerns in turn today.<br />
<span id="more-600"></span></p>
<pre lang='haskell'>
   {-# LANGUAGE Rank2Types #-}  -- we'll relax this later
   import Data.Complex -- for complex examples
</pre>
<p>First, let us consider the type of van Laarhoven lenses:</p>
<pre lang='haskell'>
type Lens a b =
  forall f. Functor f =>
  (b -> f b) -> a -> f a
</pre>
<p>with a couple of examples:</p>
<pre class="haskell">&nbsp;
realLens :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:RealFloat"><span style="background-color: #efefbf; font-weight: bold;">RealFloat</span></a> a =&gt; Lens <span style="color: green;">&#40;</span>Complex a<span style="color: green;">&#41;</span> a
realLens f <span style="color: green;">&#40;</span>r :+ i<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>:+ i<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f r<span style="color: green;">&#41;</span>
&nbsp;
imagLens :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:RealFloat"><span style="background-color: #efefbf; font-weight: bold;">RealFloat</span></a> a =&gt; Lens <span style="color: green;">&#40;</span>Complex a<span style="color: green;">&#41;</span> a
imagLens f <span style="color: green;">&#40;</span>r :+ i<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>r :+<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f i<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>These lenses have some very nice properties that we're going to exploit. By far their nicest property is that you can compose them using just <code>(.)</code> and <code>id</code> from the <code>Prelude</code> rather than having to go off and write a <code>Category</code>.</p>
<h2>Lens Families</h2>
<p><a href="http://r6.ca/blog/20120623T104901Z.html">Russell O'Connor recently noted that these lenses permit polymorphic update</a> if you simply generalize their type signature to</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> LensFamily a b c d =
  <span style="color: #06c; font-weight: bold;">forall</span> 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> f =&gt;
  <span style="color: green;">&#40;</span>c -&gt; f d<span style="color: green;">&#41;</span> -&gt; a -&gt; f b
&nbsp;</pre>
<p>I'd like to note that you can't just let these 4 arguments vary with complete impunity, so I'll be referring to these as "lens families" rather than polymorphic lenses, a point that I'll address further below. In short, we want the original lens laws to still hold in spite of the generalized type signature, and this forces some of these types to be related. </p>
<p>As an aside, each of the other lens types admit this same generalization! For instance the <code>Lens</code> type in <a href="http://hackage.haskell.org/package/data-lens">data-lens</a> can be generalized using an indexed store comonad:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Store c d b = Store <span style="color: green;">&#40;</span>d -&gt; b<span style="color: green;">&#41;</span> c
&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>Store c d<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>Store g c<span style="color: green;">&#41;</span> = Store <span style="color: green;">&#40;</span>f . g<span style="color: green;">&#41;</span> c
&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> DataLensFamily a b c d = DataLensFamily <span style="color: green;">&#40;</span>a -&gt; Store c d b<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and we can freely convert back and forth to van Laarhoven lens families:</p>
<pre class="haskell">&nbsp;
dlens :: LensFamily a b c d -&gt; DataLensFamily a b c d
dlens l = DataLensFamily <span style="color: green;">&#40;</span>l <span style="color: green;">&#40;</span>Store <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;
plens :: DataLensFamily a b c d -&gt; LensFamily a b c d
plens <span style="color: green;">&#40;</span>DataLensFamily l<span style="color: green;">&#41;</span> f a = <span style="color: #06c; font-weight: bold;">case</span> l a <span style="color: #06c; font-weight: bold;">of</span>
  Store g c -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> g <span style="color: green;">&#40;</span>f c<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>I leave it as an exercise to the reader to generalize the other lens types, but we'll stick to van Laarhoven lens families almost exclusively below.</p>
<p>As Russell noted, we can define functions to get, modify and set the target of a lens very easily. I'll create local names for <code>Identity</code> and <code>Const</code>, mostly to help give nicer error messages later.</p>
<p>We can read from a lens family:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">8</span> ^.
<span style="color: #06c; font-weight: bold;">newtype</span> Getting b a = Getting <span style="color: green;">&#123;</span> got :: b <span style="color: green;">&#125;</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>Getting 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> _ <span style="color: green;">&#40;</span>Getting b<span style="color: green;">&#41;</span> = Getting b
<span style="color: green;">&#40;</span>^.<span style="color: green;">&#41;</span> :: a -&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; Getting c d<span style="color: green;">&#41;</span> -&gt; a -&gt; Getting c b<span style="color: green;">&#41;</span> -&gt; c
x ^. l = got <span style="color: green;">&#40;</span>l Getting x<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>We can modify the target of the lens:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Setting a = Setting <span style="color: green;">&#123;</span> unsetting :: a <span style="color: green;">&#125;</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> Setting <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>Setting a<span style="color: green;">&#41;</span> = Setting <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">infixr</span> <span style="color: red;">4</span> %=
<span style="color: green;">&#40;</span>%=<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; Setting d<span style="color: green;">&#41;</span> -&gt; a -&gt; Setting b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>c -&gt; d<span style="color: green;">&#41;</span> -&gt; a -&gt; b
l %= f = unsetting . l <span style="color: green;">&#40;</span>Setting . f<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>We can set the target of the lens with impunity:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">infixr</span> <span style="color: red;">4</span> ^=
<span style="color: green;">&#40;</span>^=<span style="color: green;">&#41;</span> :: <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; Setting d<span style="color: green;">&#41;</span> -&gt; a -&gt; Setting b<span style="color: green;">&#41;</span> -&gt; d -&gt; a -&gt; b
l ^= v = l %= <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> v
&nbsp;</pre>
<p>We can build a lens family from a getter/setter pair</p>
<pre class="haskell">&nbsp;
lens :: <span style="color: green;">&#40;</span>a -&gt; c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; d -&gt; b<span style="color: green;">&#41;</span> -&gt; LensFamily a b c d
lens f g h a = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>h <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>or from a family of isomorphisms:</p>
<pre class="haskell">&nbsp;
iso :: <span style="color: green;">&#40;</span>a -&gt; c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>d -&gt; b<span style="color: green;">&#41;</span> -&gt; LensFamily a b c d
iso f g h a = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> g <span style="color: green;">&#40;</span>h <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>With these combinators in hand, we need some actual lens families to play with. Fortunately they are just as easy to construct as simple lenses. The only thing that changes is the type signature.  </p>
<pre class="haskell">&nbsp;
fstLens :: LensFamily <span style="color: green;">&#40;</span>a,c<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>b,c<span style="color: green;">&#41;</span> a b
fstLens f <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span>\x -&gt; <span style="color: green;">&#40;</span>x,b<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
&nbsp;
sndLens :: LensFamily <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>a,c<span style="color: green;">&#41;</span> b c
sndLens f <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>f b<span style="color: green;">&#41;</span>
&nbsp;
swap :: <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>b,a<span style="color: green;">&#41;</span>
swap <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>b,a<span style="color: green;">&#41;</span>
&nbsp;
swapped :: LensFamily <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>c,d<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>b,a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>d,c<span style="color: green;">&#41;</span>
swapped = iso swap swap
&nbsp;</pre>
<p>These can also build 'traditional' lenses:</p>
<pre class="haskell">&nbsp;
negated :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> a =&gt; Lens a a
negated = iso <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:negate"><span style="font-weight: bold;">negate</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:negate"><span style="font-weight: bold;">negate</span></a>
&nbsp;</pre>
<p>And since <code>Lens</code> and <code>LensFamily</code> are both type aliases, we can freely mix and match lenses with lens families:</p>
<pre class="haskell">&nbsp;
ghci&gt; <span style="color: green;">&#40;</span><span style="color: red;">1</span>:<span style="color: red;">+2</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span> ^.fstLens.realLens
<span style="color: red;">1.0</span>
ghci&gt; fstLens . realLens ^= <span style="color: red;">4</span> $ <span style="color: green;">&#40;</span><span style="color: red;">1</span>:<span style="color: red;">+2</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
<span style="color: green;">&#40;</span><span style="color: red;">4.0</span> :+ <span style="color: red;">2.0</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>But, we can now change types with our lens updates!</p>
<pre class="haskell">&nbsp;
ghci&gt; <span style="color: green;">&#40;</span>fstLens . sndLens ^= <span style="color: #3c7331;">&quot;hello&quot;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: red;">1</span>,<span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
<span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: red;">1</span>,<span style="color: #3c7331;">&quot;hello&quot;</span><span style="color: green;">&#41;</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>We can even do things like use the combinator</p>
<pre class="haskell">&nbsp;
traverseLens :: <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; c<span style="color: green;">&#41;</span> -&gt; a -&gt; b<span style="color: green;">&#41;</span> -&gt; a -&gt; b
traverseLens f = f <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a>
&nbsp;</pre>
<p>to project a <code>Functor</code> out through an appropriate lens family:</p>
<pre class="haskell">&nbsp;
ghci&gt; :t traverseLens <span style="color: green;">&#40;</span>fstLens . sndLens<span style="color: green;">&#41;</span>
traverseLens <span style="color: green;">&#40;</span>fstLens . sndLens<span style="color: green;">&#41;</span>
  :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f =&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a, f b<span style="color: green;">&#41;</span>, c<span style="color: green;">&#41;</span> -&gt; f <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>a, b<span style="color: green;">&#41;</span>, c<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>That takes care of polymorphic updates. </p>
<h2>Why is it a Lens Family?</h2>
<p>So, why do I use the term "lens family" rather than "polymorphic lens"?</p>
<p>In order for the lens laws to hold, the 4 types parameterizing our lens family must be interrelated.</p>
<p>In particular you need to be able to put back (with <code>^=</code>) what you get out of the lens (with <code>^.</code>) and put multiple times.</p>
<p>This effectively constrains the space of possible legal lens families to those where there exists an index kind <code>i</code>, and two type families <code>outer :: i -> *</code>, and <code>inner :: i -> *</code>. If this were a viable type signature, then each lens family would actually have 2 parameters, yielding something like:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- pseudo-Haskell</span>
<span style="color: #5d478b; font-style: italic;">-- type LensFamily outer inner =</span>
<span style="color: #5d478b; font-style: italic;">--    forall a b. LensFamily (outer a) (outer b) (inner a) (inner b)</span>
&nbsp;</pre>
<p>but you can't pass in type families as arguments like that, and even if you could, their lack of injectivity doesn't give the type checker enough to work with to compose your lenses. By specifying all 4 type arguments independently, we give the compiler enough to work with. But since the arguments aren't just freely polymorphic and are instead related by these index types, I'm choosing to call them "lens families" rather than "polymorphic lenses".</p>
<h2>Getters</h2>
<p>Note, we didn't use the full polymorphism of the van Laarhoven lenses in the signatures of <code>(^.)</code>, <code>(%=)</code> and <code>(^=)</code> above.</p>
<p>What happens when we restrict the type of <code>Functor</code> we're allowed to pass to our lens?</p>
<p>If we generalize the type of our getter ever so slightly from the type we pass to <code>(^.)</code> to permit composition, we get:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Getter a c = <span style="color: #06c; font-weight: bold;">forall</span> r d b. <span style="color: green;">&#40;</span>c -&gt; Getting r d<span style="color: green;">&#41;</span> -&gt; a -&gt; Getting r b
&nbsp;</pre>
<p>and we can make getters out of arbitrary Haskell functions that we have lying around with</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">-- | build a getting out of a function</span>
getting :: <span style="color: green;">&#40;</span>a -&gt; b<span style="color: green;">&#41;</span> -&gt; Getter a b
getting g f = Getting . got . f . g
&nbsp;</pre>
<p>For example:</p>
<pre class="haskell">&nbsp;
getFst :: Getter <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> a
getFst = getting <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a>
&nbsp;
getSnd :: Getter <span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> b
getSnd = getting <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a>
&nbsp;</pre>
<p>But this is particularly nice for things that <em>can't</em> be made into real lenses or lens families, because of loss of information:</p>
<pre class="haskell">&nbsp;
getPhase :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:RealFloat"><span style="background-color: #efefbf; font-weight: bold;">RealFloat</span></a> a =&gt; Getter <span style="color: green;">&#40;</span>Complex a<span style="color: green;">&#41;</span> a
getPhase = getting phase
&nbsp;
getAbs, getSignum  :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> a =&gt; Getter a a
getAbs = getting <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:abs"><span style="font-weight: bold;">abs</span></a>
getSignum = getting <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:signum"><span style="font-weight: bold;">signum</span></a>
&nbsp;</pre>
<p>Notably, <code>getMagnitude</code> and <code>getPhase</code> can't be legal lenses because when the <code>magnitude</code> is 0, you lose <code>phase</code> information.</p>
<p>These can be mixed and matched with other lenses when dereferencing with <code>(^.)</code></p>
<pre class="haskell">&nbsp;
ghci&gt; <span style="color: green;">&#40;</span><span style="color: red;">0</span>,<span style="color: green;">&#40;</span><span style="color: red;">1</span>:<span style="color: red;">+2</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> ^. getting <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> . fstLens . getting magnitude
<span style="color: red;">2.23606797749979</span>
&nbsp;</pre>
<p>But we get a type error when we attempt to write to a <code>Getter</code>.</p>
<pre class="haskell">&nbsp;
ghci&gt; getting magnitude ^= <span style="color: red;">12</span>
&lt;interactive&gt;:<span style="color: red;">2</span>:<span style="color: red;">1</span>:
    Couldn't match expected <span style="color: #06c; font-weight: bold;">type</span> `Setting d0'
                with actual <span style="color: #06c; font-weight: bold;">type</span> `Getting r0 d1'
    Expected <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>c0 -&gt; Setting d0<span style="color: green;">&#41;</span> -&gt; a1 -&gt; Setting b1
      Actual <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>c0 -&gt; Getting r0 d1<span style="color: green;">&#41;</span> -&gt; a0 -&gt; Getting r0 b0
    In the <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> <span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">of</span> a call <span style="color: #06c; font-weight: bold;">of</span> `getting'
    In the first argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>^=<span style="color: green;">&#41;</span>', namely `getting magnitude'
&lt;/interactive&gt;</pre>
<h2>Setters</h2>
<p>So what about write-only properties?</p>
<p>These have a less satisfying solution. We have to break our lens family structure slightly to make something that can strictly <em>only</em> be written to, by disabling the ability to read our current value entirely. </p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Setter a d b = <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; Setting d<span style="color: green;">&#41;</span> -&gt; a -&gt; Setting b
&nbsp;
setting :: <span style="color: green;">&#40;</span>a -&gt; d -&gt; b<span style="color: green;">&#41;</span> -&gt; Setter a d b
setting f g a = Setting <span style="color: green;">&#40;</span>f a <span style="color: green;">&#40;</span>unsetting <span style="color: green;">&#40;</span>g <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Now we can make setters out of functions that take two arguments:</p>
<pre class="haskell">&nbsp;
plus, times :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> a =&gt; Setter a a a
plus = setting <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span>
times = setting <span style="color: green;">&#40;</span>*<span style="color: green;">&#41;</span>
&nbsp;</pre>
<pre class="haskell">&nbsp;
ghci&gt; setting <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> ^= <span style="color: red;">12</span> $ <span style="color: red;">32</span>
<span style="color: red;">44</span>
ghci&gt; fstLens . setting <span style="color: green;">&#40;</span>*<span style="color: green;">&#41;</span> ^= <span style="color: red;">12</span> $ <span style="color: green;">&#40;</span><span style="color: red;">2</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
<span style="color: green;">&#40;</span><span style="color: red;">24</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>However, these lenses have the unsatisfying property that they can only be placed last in the chain of lenses we're setting. </p>
<pre class="haskell">&nbsp;
ghci&gt; <span style="color: green;">&#40;</span>setting <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> . realLens ^= <span style="color: red;">12</span><span style="color: green;">&#41;</span> <span style="color: red;">1</span>
&lt;interactive&gt;:<span style="color: red;">15</span>:<span style="color: red;">16</span>:
    Couldn't match expected <span style="color: #06c; font-weight: bold;">type</span> `<span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>' with actual <span style="color: #06c; font-weight: bold;">type</span> `Complex d0'
    Expected <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>d0 -&gt; Setting d0<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> -&gt; Setting b0
      Actual <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>d0 -&gt; Setting d0<span style="color: green;">&#41;</span>
                   -&gt; Complex d0 -&gt; Setting <span style="color: green;">&#40;</span>Complex d0<span style="color: green;">&#41;</span>
    In the second argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>.<span style="color: green;">&#41;</span>', namely `realLens'
    In the first argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>^=<span style="color: green;">&#41;</span>', namely `setting <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> . realLens'
&lt;/interactive&gt;</pre>
<p>This isn't surprising, if you consider that to compose <code>data-lens</code> lenses you need to use <code>%=</code> to chain setters.</p>
<h2>Modifiers</h2>
<p>So what do we need to do to make a lens we can only modify but not read?</p>
<p>Lets restore the lens family structure!</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Modifier a b c d = <span style="color: green;">&#40;</span>c -&gt; Setting d<span style="color: green;">&#41;</span> -&gt; a -&gt; Setting b
&nbsp;
modifying :: <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; d<span style="color: green;">&#41;</span> -&gt; a -&gt; b<span style="color: green;">&#41;</span> -&gt; Modifier a b c d
modifying f g a = Setting <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>unsetting . g<span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p><code>modifying</code> makes a modify-only lens family you can modify using local information, but can't tell anyone about the contents of.</p>
<p>This lets us work with a lens over a variable number of elements in a structure, without worrying about a user accidentally "putting back" too many or too few entries.</p>
<pre class="haskell">&nbsp;
ghci&gt; modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map"><span style="font-weight: bold;">map</span></a> %= <span style="color: green;">&#40;</span><span style="color: red;">+1</span><span style="color: green;">&#41;</span> $ <span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">2</span>,<span style="color: red;">3</span><span style="color: green;">&#93;</span>
<span style="color: green;">&#91;</span><span style="color: red;">2</span>,<span style="color: red;">3</span>,<span style="color: red;">4</span><span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>They can be composed with other lenses:</p>
<pre class="haskell">&nbsp;
ghci&gt; modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map"><span style="font-weight: bold;">map</span></a> . sndLens %= <span style="color: green;">&#40;</span><span style="color: red;">+1</span><span style="color: green;">&#41;</span> $ <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;hello&quot;</span>,<span style="color: red;">1</span><span style="color: green;">&#41;</span>,<span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;goodbye&quot;</span>,<span style="color: red;">2</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
<span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;hello&quot;</span>,<span style="color: red;">2</span><span style="color: green;">&#41;</span>,<span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;goodbye&quot;</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>and unlike with a <code>Setter</code>, you can compose a <code>Modifier</code> with a <code>Modifier</code>:</p>
<pre class="haskell">&nbsp;
modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> . modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a>
  :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> 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;
     <span style="color: green;">&#40;</span>c -&gt; Setting d<span style="color: green;">&#41;</span> -&gt; f <span style="color: green;">&#40;</span>g c<span style="color: green;">&#41;</span> -&gt; Setting <span style="color: green;">&#40;</span>f <span style="color: green;">&#40;</span>g d<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>but they cannot be read from directly:</p>
<pre class="haskell">&nbsp;
ghci&gt; <span style="color: green;">&#91;</span><span style="color: red;">1</span>,<span style="color: red;">2</span>,<span style="color: red;">3</span><span style="color: green;">&#93;</span> ^. modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a>
&lt;interactive&gt;:<span style="color: red;">18</span>:<span style="color: red;">12</span>:
    Couldn't match expected <span style="color: #06c; font-weight: bold;">type</span> `Getting c0 d0'
                with actual <span style="color: #06c; font-weight: bold;">type</span> `Setting d1'
    Expected <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>c0 -&gt; Getting c0 d0<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#91;</span>t0<span style="color: green;">&#93;</span> -&gt; Getting c0 b1
      Actual <span style="color: #06c; font-weight: bold;">type</span>: Modifier a0 b0 c0 d1
    In the <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> <span style="color: #06c; font-weight: bold;">type</span> <span style="color: #06c; font-weight: bold;">of</span> a call <span style="color: #06c; font-weight: bold;">of</span> `modifying'
    In the second argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>^.<span style="color: green;">&#41;</span>', namely `modifying <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:map"><span style="font-weight: bold;">map</span></a>'
&lt;/interactive&gt;</pre>
<p>We can map over restricted domains:</p>
<pre class="haskell">&nbsp;
reals :: <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:RealFloat"><span style="background-color: #efefbf; font-weight: bold;">RealFloat</span></a> a, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:RealFloat"><span style="background-color: #efefbf; font-weight: bold;">RealFloat</span></a> b<span style="color: green;">&#41;</span> =&gt; Modifier <span style="color: green;">&#40;</span>Complex a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Complex b<span style="color: green;">&#41;</span> a b
reals = modifying <span style="color: green;">&#40;</span>\f <span style="color: green;">&#40;</span>r :+ i<span style="color: green;">&#41;</span> -&gt; f r :+ f i<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and everything still composes:</p>
<pre class="haskell">&nbsp;
ghci&gt; reals %= <span style="color: green;">&#40;</span><span style="color: red;">+1</span><span style="color: green;">&#41;</span> $  <span style="color: red;">1</span> :+ <span style="color: red;">2</span>
<span style="color: red;">2</span> :+ <span style="color: red;">3</span>
ghci&gt; fstLens . reals %= <span style="color: green;">&#40;</span><span style="color: red;">+1</span><span style="color: green;">&#41;</span> $ <span style="color: green;">&#40;</span><span style="color: red;">1</span> :+ <span style="color: red;">2</span>, <span style="color: red;">4</span><span style="color: green;">&#41;</span>
<span style="color: green;">&#40;</span><span style="color: red;">2.0</span> :+ <span style="color: red;">3.0</span>,<span style="color: red;">4</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>These aren't limited to actions that map over the entire structure, however!</p>
<pre class="haskell">&nbsp;
ghci&gt; :m + Data.Lens
ghci&gt; modifying <span style="color: green;">&#40;</span>`adjust` <span style="color: #3c7331;">&quot;goodbye&quot;</span><span style="color: green;">&#41;</span> %= <span style="color: green;">&#40;</span><span style="color: red;">+1</span><span style="color: green;">&#41;</span> $
      fromList <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;hello&quot;</span>,<span style="color: red;">1</span><span style="color: green;">&#41;</span>,<span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;goodbye&quot;</span>,<span style="color: red;">2</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
fromList <span style="color: green;">&#91;</span><span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;goodbye&quot;</span>,<span style="color: red;">3</span><span style="color: green;">&#41;</span>,<span style="color: green;">&#40;</span><span style="color: #3c7331;">&quot;hello&quot;</span>,<span style="color: red;">1</span><span style="color: green;">&#41;</span><span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>This lets us update potentially nested structures where something may or may not be present , which was fairly tedious to do with earlier lens representations.</p>
<p>Both the former map-like example and the latter update-like behavior were commonly used examples in calls for partial lenses or 'multi-lenses', but here they are able to implemented using a restricted form of a more traditional lens type, and moreover they compose cleanly with other lenses and lens families.</p>
<h2>Rank-1 Lens Families</h2>
<p>At the very start I mentioned that you can dispense with the need for Rank-2 Types. Doing so requires much more tedious type signatures as the <code>LensFamily</code>, <code>Getter</code>, <code>Setter</code> and <code>Lens</code> aliases are no longer legal. Also, if you want to take a lens as an argument and use it in multiple contexts (e.g. as both a getter and a setter), you'll need to clone it to obtain a lens family. For example, this fails:</p>
<pre class="haskell">&nbsp;
ghci&gt; :t \l y -&gt; l ^= y ^. l + <span style="color: red;">1</span> $ y
&lt;interactive&gt;:<span style="color: red;">1</span>:<span style="color: red;">19</span>:
    Couldn't match expected <span style="color: #06c; font-weight: bold;">type</span> `Getting d0 d1'
                with actual <span style="color: #06c; font-weight: bold;">type</span> `Setting d0'
    Expected <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>d0 -&gt; Getting d0 d1<span style="color: green;">&#41;</span> -&gt; a1 -&gt; Getting d0 b1
      Actual <span style="color: #06c; font-weight: bold;">type</span>: <span style="color: green;">&#40;</span>d0 -&gt; Setting d0<span style="color: green;">&#41;</span> -&gt; a0 -&gt; Setting b0
    In the second argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>^.<span style="color: green;">&#41;</span>', namely `l'
    In the first argument <span style="color: #06c; font-weight: bold;">of</span> `<span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span>', namely `y ^. l'
&lt;/interactive&gt;</pre>
<p>But we can clone the supplied monomorphic lens using the composition of <code>dlens</code> and <code>plens</code> above, since the <code>DataLensFamily</code> completely characterizes the <code>LensFamily</code> with:</p>
<pre class="haskell">&nbsp;
clone ::
  <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; Store c d d<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>a -&gt; Store c d b<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> -&gt;
  LensFamily a b c d
clone l f a = <span style="color: #06c; font-weight: bold;">case</span> l <span style="color: green;">&#40;</span>Store <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:id"><span style="font-weight: bold;">id</span></a><span style="color: green;">&#41;</span> a <span style="color: #06c; font-weight: bold;">of</span>
  Store g c -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> g <span style="color: green;">&#40;</span>f c<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and then the following code type checks:</p>
<pre class="haskell">&nbsp;
ghci&gt; :t \l y -&gt; clone l ^= y ^. clone l + <span style="color: red;">1</span> $ y
\l y -&gt; clone l ^= y ^. clone l + <span style="color: red;">1</span> $ y
  :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Num"><span style="background-color: #efefbf; font-weight: bold;">Num</span></a> d =&gt; <span style="color: green;">&#40;</span><span style="color: green;">&#40;</span>c -&gt; Store c d1 d1<span style="color: green;">&#41;</span> -&gt; a -&gt; Store d d b<span style="color: green;">&#41;</span> -&gt; a -&gt; b
&nbsp;</pre>
<p>This means you could implement an entire library to deal with lens families with restricted getters and setters and remain within the confines of Haskell 98. However, the type signatures are considerably less elegant than what becomes available when you simply add Rank2Types.</p>
<h2>Conclusion</h2>
<p>So, we've demonstrated that van Laarhoven lens families let you have lenses that permit polymorphic update, let you offer lenses that are restricted to only allowing the use of getters, setters or modifiers, while granting you easy composition with the existing <code>(.)</code> and <code>id</code> from the <code>Prelude</code>.</p>
<p>I think the practical existence and power of these combinators make a strong case for their use in any serious record reform proposal.</p>
<p>My thanks go to Russell O'Connor. He first noticed that you can generalize van Laarhoven lenses and proposed the <code>clone</code> combinator as a path to Haskell 98/2010 compatibility, while retaining the nicer composition model.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2012/mirrored-lenses/feed/</wfw:commentRss>
		<slash:comments>491</slash:comments>
		</item>
		<item>
		<title>A Parsec Full of Rats, Part 2</title>
		<link>http://comonad.com/reader/2011/a-parsec-full-of-rats-part-2/</link>
		<comments>http://comonad.com/reader/2011/a-parsec-full-of-rats-part-2/#comments</comments>
		<pubDate>Sat, 24 Sep 2011 03:07:32 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Parsing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[packrat]]></category>
		<category><![CDATA[parsec]]></category>
		<category><![CDATA[trifecta]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=397</guid>
		<description><![CDATA[Last time, I showed that we can build a small parsec clone with packrat support.
This time I intend to implement packrat directly on top of Parsec 3.
One of the main topics of discussion when it comes to packrat parsing since Bryan Ford's initial release of Pappy has been the fact that in general you shouldn't [...]]]></description>
			<content:encoded><![CDATA[<p>Last time, I showed that we can build a small parsec clone with packrat support.</p>
<p>This time I intend to implement packrat directly on top of Parsec 3.</p>
<p>One of the main topics of discussion when it comes to packrat parsing since Bryan Ford's initial release of Pappy has been the fact that in general you shouldn't use packrat to memoize every rule, and that instead you should apply Amdahl's law to look for the cases where the lookup time is paid back in terms of repetitive evaluation, computation time and the hit rate. This is great news for us, since, we only want to memoize a handful of expensive combinators.</p>
<p><span id="more-397"></span></p>
<p>First, we'll need to import enough of Parsec to do something interesting.</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# LANGUAGE RecordWildCards, ViewPatterns, FlexibleInstances, MultiParamTypeClasses #-}</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">import</span> Text.Parsec
<span style="color: #06c; font-weight: bold;">import</span> <span style="color: #06c; font-weight: bold;">qualified</span> Text.Parsec.Token <span style="color: #06c; font-weight: bold;">as</span> T
<span style="color: #06c; font-weight: bold;">import</span> Text.Parsec.Token
    <span style="color: green;">&#40;</span>GenLanguageDef<span style="color: green;">&#40;</span>..<span style="color: green;">&#41;</span>, GenTokenParser<span style="color: green;">&#40;</span>TokenParser<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Text.Parsec.Pos <span style="color: green;">&#40;</span>initialPos, updatePosChar<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Data.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>.Identity <span style="color: green;">&#40;</span>Identity<span style="color: green;">&#40;</span>..<span style="color: green;">&#41;</span><span style="color: green;">&#41;</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><span style="color: green;">&#40;</span>&lt; |&gt;<span style="color: green;">&#41;</span><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>.Fix <span style="color: green;">&#40;</span>fix<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Then as before, we'll define PEG-style backtracking:</p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#40;</span>&lt; /&gt;<span style="color: green;">&#41;</span> :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; ParsecT s u m a -&gt; ParsecT s u m a -&gt;
    ParsecT s u m a
p &lt; /&gt; q = try p &lt; |&gt; q
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">3</span> &lt; /&gt;
&nbsp;</pre>
<p>Now we need an analogue to our Result type from last time, which recalled whether or not we had consumed input, and what the current cursor location is. Fortunately, we can recycle the definitions from Parsec to this end.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Result d a = Consumed <span style="color: green;">&#40;</span>Reply d <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>We'll define a combinator to build a parser directly from a field accessor. Last time, this was just the use of the "Rat" constructor. Now it is a bit trickier, because we need to turn <code>Consumed (Reply d () a)</code> into <code>m (Consumed (m (Reply d u a)))</code> by wrapping it in the appropriate monad, and giving the user back his state unmolested. </p>
<pre class="haskell">&nbsp;
rat :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; <span style="color: green;">&#40;</span>d -&gt; Result d a<span style="color: green;">&#41;</span> -&gt; ParsecT d u m a
rat f   = mkPT $ \s0 -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> $
    <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> . patch s0 &lt; $&gt; f <span style="color: green;">&#40;</span>stateInput s0<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  patch <span style="color: green;">&#40;</span>State _ _ u<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Ok a <span style="color: green;">&#40;</span>State s p _<span style="color: green;">&#41;</span> err<span style="color: green;">&#41;</span> = Ok a <span style="color: green;">&#40;</span>State s p u<span style="color: green;">&#41;</span> err
  patch _             <span style="color: green;">&#40;</span>Error e<span style="color: green;">&#41;</span>                = Error e
&nbsp;</pre>
<p>Last time we could go from a parser to a result just by applying the user stream type, but with parsec we also have to supply their notion of a position. This leads to the following combinator. By running in the Identity monad with no user state it should be obvious that we've duplicated the functionality of the previous 'Rat' parser (with the addition of a source position).</p>
<pre class="haskell">&nbsp;
womp :: d -&gt; SourcePos -&gt; ParsecT d <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> Identity a -&gt; Result d a
womp d pos p = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> runIdentity . runIdentity $
    runParsecT p <span style="color: green;">&#40;</span>State d pos <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>The combinator is so named because we needed a big space-rat rather than a little pack-rat to keep with the theme.</p>
<blockquote><p>It's not impossible. I used to bullseye womp rats in my T-16 back home, they're not much bigger than two meters.</p></blockquote>
<p>Now we'll write a bit of annoyingly verbose boilerplate to convince <code>Parsec</code> that we really want a <code>LanguageDef</code> for some monad other than Identity. (As an aside, why <code>Text.Parsec.Language</code> doesn't contain GenLanguageDefs that are parametric in their choice of Monad is beyond me.) </p>
<pre class="haskell">&nbsp;
myLanguageDef :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; T.GenLanguageDef D u m
myLanguageDef = T.LanguageDef
  <span style="color: green;">&#123;</span> commentStart    = <span style="color: #3c7331;">&quot;{-&quot;</span>
  , commentEnd      = <span style="color: #3c7331;">&quot;-}&quot;</span>
  , commentLine     = <span style="color: #3c7331;">&quot;--&quot;</span>
  , nestedComments  = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>
  , identStart      = letter &lt; |&gt; char '_'
  , identLetter     = alphaNum &lt; |&gt; oneOf <span style="color: #3c7331;">&quot;_'&quot;</span>
  , opStart         = opLetter myLanguageDef
  , opLetter        = oneOf <span style="color: #3c7331;">&quot;:!#$%&amp;*+./&lt; =&gt;?@<span style="">\\</span>^|-~&quot;</span>
  , reservedOpNames = <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
  , reservedNames   = <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
  , caseSensitive   = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>
  <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>As a shameless plug, trifecta offers a particularly nice solution to this problem, breaking up the monolithic Token type into separate concerns and letting you layer parser transformers that enrich the parser to deal with things like Haskell-style layout, literate comments, parsing comments in whitespace, etc. </p>
<p>And as one last bit of boilerplate, we'll abuse RecordWildcards once again to avoid the usual 20 lines of boilerplate that are expected of us, so we can get access to parsec's token parsers.</p>
<pre class="haskell">&nbsp;
TokenParser <span style="color: green;">&#123;</span>..<span style="color: green;">&#125;</span> = T.makeTokenParser myLanguageDef
&nbsp;</pre>
<p>Now we're ready to define our incredibly straightforward stream type:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> D = D
  <span style="color: green;">&#123;</span> _add        :: Result D <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>
  , _mult       :: Result D <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>
  , _primary    :: Result D <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>
  , _dec        :: Result D <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>
  , _uncons     :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Maybe"><span style="background-color: #efefbf; font-weight: bold;">Maybe</span></a> <span style="color: green;">&#40;</span><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>, D<span style="color: green;">&#41;</span>
  <span style="color: green;">&#125;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> m =&gt; Stream D m <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> <span style="color: #06c; font-weight: bold;">where</span>
  uncons = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> . _uncons
&nbsp;</pre>
<p>And using the general purpose <code>rat</code> combinator from earlier, we can write some memoized parsers:</p>
<pre class="haskell">&nbsp;
add, mult, primary, dec :: Parsec D u <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>
add     = rat _add
mult    = rat _mult
primary = rat _primary
dec     = rat _dec
&nbsp;</pre>
<p>And finally, we write the code to tie the knot and build the stream:</p>
<pre class="haskell">&nbsp;
parse :: SourceName -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; D
parse n = go <span style="color: green;">&#40;</span>initialPos n<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  go p s = fix $ \d -&gt; <span style="color: #06c; font-weight: bold;">let</span>
    <span style="color: green;">&#40;</span>womp d p -&gt; _add<span style="color: green;">&#41;</span> =
            <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> &lt; $&gt; mult &lt; * reservedOp <span style="color: #3c7331;">&quot;+&quot;</span> &lt;*&gt; add
        &lt; /&gt; mult &lt; ?&gt; <span style="color: #3c7331;">&quot;summand&quot;</span>
    <span style="color: green;">&#40;</span>womp d p -&gt; _mult<span style="color: green;">&#41;</span> =
            <span style="color: green;">&#40;</span>*<span style="color: green;">&#41;</span> &lt; $&gt; primary &lt; * reservedOp <span style="color: #3c7331;">&quot;*&quot;</span> &lt;*&gt; mult
        &lt; /&gt; primary &lt; ?&gt; <span style="color: #3c7331;">&quot;factor&quot;</span>
    <span style="color: green;">&#40;</span>womp d p -&gt; _primary<span style="color: green;">&#41;</span> =
            parens add
        &lt; /&gt; dec &lt; ?&gt; <span style="color: #3c7331;">&quot;number&quot;</span>
    <span style="color: green;">&#40;</span>womp d p -&gt; _dec<span style="color: green;">&#41;</span> = natural
    _uncons = <span style="color: #06c; font-weight: bold;">case</span> s <span style="color: #06c; font-weight: bold;">of</span>
      <span style="color: green;">&#40;</span>x:xs<span style="color: green;">&#41;</span> -&gt; <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>x, go <span style="color: green;">&#40;</span>updatePosChar p x<span style="color: green;">&#41;</span> xs<span style="color: green;">&#41;</span>
      <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>     -&gt; <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: #06c; font-weight: bold;">in</span> D <span style="color: green;">&#123;</span> .. <span style="color: green;">&#125;</span>
&nbsp;
runD :: Parsec D u a -&gt; u -&gt; SourceName -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a> ParseError a
runD p u fn s = runParser p u fn <span style="color: green;">&#40;</span>prep fn s<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>and finally, let it rip:</p>
<pre class="haskell">&nbsp;
eval :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; <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>
eval s = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:either"><span style="font-weight: bold;">either</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> . <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;">&#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> $
    runD <span style="color: green;">&#40;</span>whiteSpace *&gt; add &lt; * eof<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> <span style="color: #3c7331;">&quot;-&quot;</span> s
&nbsp;</pre>
<p>While this approach tends to encourage memoizing fewer combinators than libraries such as frisby, this is exactly what <a href="http://www.mercury.csse.unimelb.edu.au/information/papers/packrat.pdf">current research suggests you probably should do</a> with packrat parsing!</p>
<p>The other purported advantage of packrat parsers is that they <a href="http://www.vpri.org/pdf/tr2007002_packrat.pdf">can deal with left recursion in the grammar</a>. However, that is not the case, hidden left recursion in the presence of the algorithm used in the scala parsing combinator libraries leads to incorrect non-left-most parses <a href="http://tratt.net/laurie/research/publications/papers/tratt__direct_left_recursive_parsing_expression_grammars.pdf">as shown by Tratt</a>.</p>
<p>I leave it as an exercise for the reader to extend this material with the parsec+iteratees approach from my original talk on trifecta to get packrat parsing of streaming input. Either that or you can wait until it is integrated into trifecta.</p>
<p>You can download the source to this (without the spurious spaces inserted by wordpress) <a href="https://github.com/ekmett/trifecta/blob/master/wip/Womprat.hs">here</a>.</p>
<p>If I can find the time, I hope to spend some time addressing Scott and Johnstone's GLL parsers, which actually achieve the O(n^3) worst case bounds touted for Tomita's GLR algorithm (which is actually O(n^4) as it was originally defined despite the author's claims), and how to encode them in Haskell with an eye towards building a memoizing parser combinator library that can parse LL(1) fragments in O(1), deal with arbitrary context-free grammars in O(n^3), and degrade reasonably gracefully in the presence of context-sensitivity, while supporting hidden left recursion as long as such recursion passes through at least one memoized rule. This is important because CFGs are closed under extensions to the grammar, which is a nice property to have if you want to have a language where you can add new statement types easily without concerning yourself overmuch with the order in which you insert the rules or load the different extensions.</p>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/a-parsec-full-of-rats-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A Parsec Full of Rats, Part 1</title>
		<link>http://comonad.com/reader/2011/a-parsec-full-of-rats/</link>
		<comments>http://comonad.com/reader/2011/a-parsec-full-of-rats/#comments</comments>
		<pubDate>Sat, 24 Sep 2011 02:10:06 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Parsing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[packrat]]></category>
		<category><![CDATA[trifecta]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=380</guid>
		<description><![CDATA[You never heard of the Millenium Falcon? It's the ship that made the Kessel Run in 12 parsecs.
I've been working on a parser combinator library called trifecta, and so I decided I'd share some thoughts on parsing. 
Packrat parsing (as provided by frisby, pappy, rats! and the Scala parsing combinators) and more traditional recursive descent [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>You never heard of the Millenium Falcon? It's the ship that made the Kessel Run in 12 parsecs.</p></blockquote>
<p>I've been working on a parser combinator library called <a href="http://hackage.haskell.org/package/trifecta">trifecta</a>, and so I decided I'd share some thoughts on parsing. </p>
<p><a href="http://pdos.csail.mit.edu/~baford/packrat/">Packrat parsing</a> (as provided by <a href="http://hackage.haskell.org/package/frisby">frisby</a>, <a href="http://hackage.haskell.org/package/pappy">pappy</a>, <a href="http://cs.nyu.edu/rgrimm/xtc/">rats!</a> and the Scala parsing combinators) and more traditional recursive descent parsers (like Parsec) are often held up as somehow different. </p>
<p>Today I'll show that you can add monadic parsing to a packrat parser, sacrificing asymptotic guarantees in exchange for the convenient context sensitivity, and conversely how you can easily add packrat parsing to a traditional monadic parser combinator library.</p>
<p><span id="more-380"></span></p>
<p>To keep this post self-contained, I'm going to start by defining a small packrat parsing library by hand, which acts rather like parsec in its backtracking behavior. First, some imports:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# LANGUAGE RecordWildCards, ViewPatterns, DeriveFunctor #-}</span>
<span style="color: #06c; font-weight: bold;">import</span> Control.Applicative
<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: green;">&#40;</span>MonadPlus<span style="color: green;">&#40;</span>..<span style="color: green;">&#41;</span>, guard<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>.Fix <span style="color: green;">&#40;</span>fix<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Data.<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> <span style="color: green;">&#40;</span>isDigit, digitToInt, isSpace<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Second, we'll define a bog simple parser, which consumes an input stream of type d, yielding a possible answer and telling us whether or not it has actually consumed any input as it went.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Rat d a = Rat <span style="color: green;">&#123;</span> runRat :: d -&gt; Result d a <span style="color: green;">&#125;</span>
  <span style="color: #06c; font-weight: bold;">deriving</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Result d a
  = Pure a             <span style="color: #5d478b; font-style: italic;">-- didn't consume anything, can backtrack</span>
  | Commit d a      <span style="color: #5d478b; font-style: italic;">-- consumed input</span>
  | Fail <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a> <span style="color: #5d478b; font-style: italic;">-- failed, flagged if consumed</span>
  <span style="color: #06c; font-weight: bold;">deriving</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>
&nbsp;</pre>
<p>Now, we can finally implement some type classes:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Applicative <span style="color: green;">&#40;</span>Rat d<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure a = Rat $ \ _ -&gt; Pure a
  Rat mf &lt; *&gt; Rat ma = Rat $ \ d -&gt; <span style="color: #06c; font-weight: bold;">case</span> mf d <span style="color: #06c; font-weight: bold;">of</span>
    Pure f      -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f <span style="color: green;">&#40;</span>ma d<span style="color: green;">&#41;</span>
    Fail s c    -&gt; Fail s c
    Commit d' f -&gt; <span style="color: #06c; font-weight: bold;">case</span> ma d' <span style="color: #06c; font-weight: bold;">of</span>
      Pure a       -&gt; Commit d' <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
      Fail s _     -&gt; Fail s <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>
      Commit d'' a -&gt; Commit d'' <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>including an instance of Alternative that behaves like parsec, only backtracking on failure if no input was unconsumed.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Alternative <span style="color: green;">&#40;</span>Rat d<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  Rat ma &lt; |&gt; Rat mb = Rat $ \ d -&gt; <span style="color: #06c; font-weight: bold;">case</span> ma d <span style="color: #06c; font-weight: bold;">of</span>
    Fail _ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> -&gt; mb d
    x            -&gt; x
  empty = Rat $ \ _ -&gt; Fail <span style="color: #3c7331;">&quot;empty&quot;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
&nbsp;</pre>
<p>For those willing to forego the asymptotic guarantees of packrat, we'll offer a monad.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> <span style="color: green;">&#40;</span>Rat d<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 = Rat $ \_ -&gt; Pure a
  Rat m &gt;&gt;= k = Rat $ \d -&gt; <span style="color: #06c; font-weight: bold;">case</span> m d <span style="color: #06c; font-weight: bold;">of</span>
    Pure a -&gt; runRat <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> d
    Commit d' a -&gt; <span style="color: #06c; font-weight: bold;">case</span> runRat <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> d' <span style="color: #06c; font-weight: bold;">of</span>
      Pure b -&gt; Commit d' b
      Fail s _ -&gt; Fail s <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>
      commit -&gt; commit
    Fail s c -&gt; Fail s c
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fail"><span style="font-weight: bold;">fail</span></a> s = Rat $ \ _ -&gt; Fail s <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> MonadPlus <span style="color: green;">&#40;</span>Rat d<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  mplus = <span style="color: green;">&#40;</span>&lt; |&gt;<span style="color: green;">&#41;</span>
  mzero = empty
&nbsp;</pre>
<p>and a Parsec-style "try", which rewinds on failure, so that < |> can try again.</p>
<pre class="haskell">&nbsp;
try :: Rat d a -&gt; Rat d a
try <span style="color: green;">&#40;</span>Rat m<span style="color: green;">&#41;</span> = Rat $ \d -&gt; <span style="color: #06c; font-weight: bold;">case</span> m d <span style="color: #06c; font-weight: bold;">of</span>
  Fail s _ -&gt; Fail s <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
  x        -&gt; x
&nbsp;</pre>
<p>Since we've consumed < |> with parsec semantics. Let's give a PEG-style backtracking (< />).</p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#40;</span>&lt; /&gt;<span style="color: green;">&#41;</span> :: Rat d a -&gt; Rat d a -&gt; Rat d a
p &lt; /&gt; q = try p &lt; |&gt; q
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">3</span> &lt; /&gt;
&nbsp;</pre>
<p>So far nothing we have done involves packrat at all. These are all general purpose recursive descent combinators.</p>
<p>We can define an input stream and a number of combinators to read input.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Stream d <span style="color: #06c; font-weight: bold;">where</span>
  anyChar :: Rat d <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>
&nbsp;
whiteSpace :: Stream d =&gt; Rat d <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
whiteSpace = <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span> &lt; $ many <span style="color: green;">&#40;</span>satisfy isSpace<span style="color: green;">&#41;</span>
phrase :: Stream d =&gt; Rat d a -&gt; Rat d a
phrase m = whiteSpace *&gt; m &lt; * eof
&nbsp;
notFollowedBy :: Rat d a -&gt; Rat d <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
notFollowedBy <span style="color: green;">&#40;</span>Rat m<span style="color: green;">&#41;</span> = Rat $ \d -&gt; <span style="color: #06c; font-weight: bold;">case</span> m d <span style="color: #06c; font-weight: bold;">of</span>
  Fail<span style="color: green;">&#123;</span><span style="color: green;">&#125;</span> -&gt; Pure <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
  _      -&gt; Fail <span style="color: #3c7331;">&quot;unexpected&quot;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
&nbsp;
eof :: Stream d =&gt; Rat d <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
eof = notFollowedBy anyChar
&nbsp;
satisfy :: Stream d =&gt; <span style="color: green;">&#40;</span><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> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Bool"><span style="background-color: #efefbf; font-weight: bold;">Bool</span></a><span style="color: green;">&#41;</span> -&gt; Rat d <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>
satisfy p = try $ <span style="color: #06c; font-weight: bold;">do</span>
  x &lt; - anyChar
  x &lt;$ guard <span style="color: green;">&#40;</span>p x<span style="color: green;">&#41;</span>
&nbsp;
char :: Stream d =&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> -&gt; Rat d <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>
char c = satisfy <span style="color: green;">&#40;</span>c ==<span style="color: green;">&#41;</span>
&nbsp;
lexeme :: Stream d =&gt; Rat d a -&gt; Rat d a
lexeme m = m &lt; * whiteSpace
&nbsp;
symbol :: Stream d =&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> -&gt; Rat d <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>
symbol c = lexeme <span style="color: green;">&#40;</span>char c<span style="color: green;">&#41;</span>
&nbsp;
digit :: Stream d =&gt; Rat d <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>
digit = digitToInt &lt; $&gt; satisfy isDigit
&nbsp;</pre>
<p>And we can of course use a string as our input stream:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Stream <span style="color: green;">&#91;</span><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><span style="color: green;">&#93;</span> <span style="color: #06c; font-weight: bold;">where</span>
  anyChar = Rat $ \s -&gt; <span style="color: #06c; font-weight: bold;">case</span> s <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span>x:xs<span style="color: green;">&#41;</span> -&gt; Commit xs x
    <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> -&gt; Fail <span style="color: #3c7331;">&quot;EOF&quot;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
&nbsp;</pre>
<p>Now that we've built a poor man's Parsec, let's do something more interesting. Instead of just using String as out input stream, let's include slots for use in memoizing the results from our various parsers at each location. To keep things concrete, we'll memoize the ArithPackrat.hs example that Bryan Ford used in his initial packrat presentation enriched with some whitespace handling.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> D = D
  <span style="color: green;">&#123;</span> _add        :: Result D <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>
  , _mult       :: Result D <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>
  , _primary    :: Result D <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>
  , _decimal    :: Result D <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>
  , anyCharD    :: Result D <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>
  <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>If you look at the type of each of those functions you'll see that <code>_add :: D -> Result D Int</code>, which is exactly our Rat newtype expects as its argument, we we can bundle them directly:</p>
<pre class="haskell">&nbsp;
&nbsp;
add, mult, primary, decimal :: Rat D <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>
add     = Rat _add
mult    = Rat _mult
primary = Rat _primary
decimal = Rat _decimal
&nbsp;</pre>
<p>We can similarly juse use the character parse result.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Stream D <span style="color: #06c; font-weight: bold;">where</span>
  anyChar = Rat anyCharD
&nbsp;</pre>
<p>Now we just need to build a D from a String. I'm using view patterns and record wildcards to shrink the amount of repetitive naming.</p>
<pre class="haskell">&nbsp;
parse :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&gt; D
parse s = fix $ \d -&gt; <span style="color: #06c; font-weight: bold;">let</span>
  Rat <span style="color: green;">&#40;</span>dv d -&gt; _add<span style="color: green;">&#41;</span> =
        <span style="color: green;">&#40;</span>+<span style="color: green;">&#41;</span> &lt; $&gt; mult &lt; * symbol '+' &lt;*&gt; add
     &lt; /&gt; mult
  Rat <span style="color: green;">&#40;</span>dv d -&gt; _mult<span style="color: green;">&#41;</span> =
        <span style="color: green;">&#40;</span>*<span style="color: green;">&#41;</span> &lt; $&gt; primary &lt; * symbol '*' &lt;*&gt; mult
    &lt; /&gt; primary
  Rat <span style="color: green;">&#40;</span>dv d -&gt; _primary<span style="color: green;">&#41;</span> =
        symbol '<span style="color: green;">&#40;</span>' *&gt; add &lt; * symbol '<span style="color: green;">&#41;</span>'
    &lt;/&gt; decimal
  Rat <span style="color: green;">&#40;</span>dv d -&gt; _decimal<span style="color: green;">&#41;</span> =
     <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:foldl"><span style="font-weight: bold;">foldl</span></a>' <span style="color: green;">&#40;</span>\b a -&gt; b * <span style="color: red;">10</span> + a<span style="color: green;">&#41;</span> <span style="color: red;">0</span> &lt; $&gt; lexeme <span style="color: green;">&#40;</span>some digit<span style="color: green;">&#41;</span>
  anyCharD = <span style="color: #06c; font-weight: bold;">case</span> s <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span>x:xs<span style="color: green;">&#41;</span> -&gt; Commit <span style="color: green;">&#40;</span>parse xs<span style="color: green;">&#41;</span> x
    <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>     -&gt; Fail <span style="color: #3c7331;">&quot;EOF&quot;</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a>
  <span style="color: #06c; font-weight: bold;">in</span> D <span style="color: green;">&#123;</span> .. <span style="color: green;">&#125;</span>
&nbsp;
dv :: d -&gt; <span style="color: green;">&#40;</span>d -&gt; b<span style="color: green;">&#41;</span> -&gt; b
dv d f = f d
&nbsp;</pre>
<p>Note that we didn't really bother factoring the grammar, since packrat will take care of memoizing the redundant calls!</p>
<p>And with that, we can define an evaluator.</p>
<pre class="haskell">&nbsp;
eval :: <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:String"><span style="background-color: #efefbf; font-weight: bold;">String</span></a> -&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>
eval s = <span style="color: #06c; font-weight: bold;">case</span> runRat <span style="color: green;">&#40;</span>whiteSpace *&gt; add &lt; * eof<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>parse s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">of</span>
  Pure a -&gt; a
  Commit _ a -&gt; a
  Fail s _ -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:error"><span style="font-weight: bold;">error</span></a> s
&nbsp;</pre>
<p>Note that because the input stream D contains the result directly and parse is the only thing that ever generates a D, and it does so when we start up, it should be obvious that the parse results for each location can't depend on any additional information smuggled in via our monad.</p>
<p>Next time, we'll add a packratted Stream type directly to Parsec, which will necessitate some delicate handling of user state.</p>
<p>The small parser implemented here can be <a href="https://github.com/ekmett/trifecta/blob/master/wip/Rat.hs">found on my github account</a>, where it hasn't been adulterated with unnecessary spaces by my blog software.</p>
<p>P.S. To explain the quote, had I thought of it earlier, I could have named my parsing combinator library "Kessel Run" as by the time I'm done with it "it will contain at least 12 parsecs" between its different parser implementations.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/a-parsec-full-of-rats/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Free Modules and Functional Linear Functionals</title>
		<link>http://comonad.com/reader/2011/free-modules-and-functional-linear-functionals/</link>
		<comments>http://comonad.com/reader/2011/free-modules-and-functional-linear-functionals/#comments</comments>
		<pubDate>Mon, 11 Jul 2011 20:58:04 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Linear Algebra]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Monoids]]></category>
		<category><![CDATA[Type Hackery]]></category>

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

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

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

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