<?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</title>
	<atom:link href="http://comonad.com/reader/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>Computational Quadrinitarianism (Curious Correspondences go Cubical)</title>
		<link>http://comonad.com/reader/2018/computational-quadrinitarianism-curious-correspondences-go-cubical/</link>
		<comments>http://comonad.com/reader/2018/computational-quadrinitarianism-curious-correspondences-go-cubical/#comments</comments>
		<pubDate>Tue, 16 Jan 2018 23:17:03 +0000</pubDate>
		<dc:creator>Gershom Bazerman</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=1135</guid>
		<description><![CDATA[Back in 2011, in an influential blog post [1], Robert Harper coined the term  "computational trinitarianism" to describe an idea that had been around a long time — that the connection between programming languages, logic, and categories, most famously expressed in the Curry-Howard-Lambek correspondence — should guide the practice of researchers into computation. In [...]]]></description>
			<content:encoded><![CDATA[<p>Back in 2011, in an influential blog post [<a href="#1">1</a>], Robert Harper coined the term  "computational trinitarianism" to describe an idea that had been around a long time — that the connection between programming languages, logic, and categories, most famously expressed in the Curry-Howard-Lambek correspondence — should guide the practice of researchers into computation. In particular "any concept arising in one aspect should have meaning from the perspective of the other two". This was especially satisfying to those of us trying learning categorical semantics and often finding it disappointing how little it is appreciated in the computer science community writ large.</p>
<h4>1. Categories</h4>
<p>Over the years I've thought about trinitarianism a lot, and learned from where it fails to work as much as where it succeeds. One difficulty is that learning to read a logic like a type theory, or vice versa, is almost a definitional trick, because it occurs at the level of reinterpretation of syntax. With categories it is  typically not so easy. (There is a straightforward version of categorical semantics like this — yielding "syntactic categories" — but it is difficult to connect it to the broader world of categorical semantics, and often it is sidestepped in favor of deeper models.)</p>
<p>One thing I came to realize is that there is no one notion of categorical semantics — the way in which the simply typed lambda calculus takes models in cartesian closed categories is fundamentally unlike the way in which linear logics take models in symmetric monoidal categories. If you want to study models of dependent type theories, you have a range of approaches, only some of which have been partially unified by Ahrens, Lumsdaine and Voevodsky in particular [<a href="#2">2</a>]. And then there are the LCCC models pioneered by Seely for extensional type theory, not to mention the approach that takes semantics directly in toposes, or in triposes (the latter having been invented to unify a variety of structures, and in the process giving rise to still more questions). And then there is the approach that doesn't use categories at all, but multicategories.</p>
<p>Going the other way, we also run into obstacles: there is a general notion, opposite to the "syntactic category" of a type theory, which is the "internal logic" of a category. But depending on the form of category, "internal logic" can take many forms. If you are in a topos, there is a straightforward internal logic called the Mitchell–Bénabou language. In this setting, most "logical" operations factor through the truth-lattice of the subobject classifier. This is very convenient, but if you don't have a proper subobject classifier, then you are forced to reach for other interpretations. As such, it is not infrequently the case that we have a procedure for deriving a category from some logical theory, and a procedure for constructing a logical theory from some category, but there is no particular reason to expect that where we arrive, when we take the round-trip, is close to, much less precisely, where we began.</p>
<h4>2. Spaces, Logics</h4>
<p>Over the past few years I've been in a topos theory reading group. In the course of this, I've realized at least one problem with all the above (by no means the only one) — Harper's holy trinity is fundamentally incomplete. There is another structure of interest — of equal weight to categories, logics, and languages — which it is necessary to understand to see how everything fits. This structure is <i>spaces</i>. I had thought that it was a unique innovation of homotopy type theory to consider logics (resp. type theories) that took semantics in spaces. But it turns out that I just didn't know the history of constructive logic very well. In fact, in roughly the same period that Curry was exploring the relationship of combinatory algebras to logic, Alfred Tarski and Marshall Stone were developing <i>topological</i> models for intuitionistic logic, in terms of what we call Heyting Algebras [<a href="#3">3</a>] [<a href="#4">4</a>]. And just as, as Harper explained, logic, programming and category theory give us insights into implication in the form of entailment, typing judgments, and morphisms, so to, as we will see, do spaces.</p>
<p>A Heyting algebra is a special type of distributive lattice (partially ordered set, equipped with meet and join operations, such that meet and join distribute over one another) which has an implication operation that satisfies curry/uncurry adjointness — i.e. such that c ∧ a ≤ b < -> c ≤ a → b. (Replace meet here by "and" (spelled "*"), and ≤ by ⊢ and we have the familiar type-theoretic statement that c * a ⊢ b < -> c ⊢ a → b).</p>
<p>If you haven't encountered this before, it is worth unpacking. Given a set, we equip it with a partial order by specifying a "≤" operation, such that a ≤ a, if a ≤ b and b ≤ a, then a = b, and finally that if a ≤ b and b ≤ c, then a ≤ c. We can think of such things as Hasse diagrams — a bunch of nodes with some lines between them that only go upwards. If a node b is reachable from a node a by following these upwards lines, then a ≤ b. This "only upwards" condition is enough to enforce all three conditions. We can define ∨ (join) as a binary operation that takes two nodes, and gives a node a ∨ b that is greater than either node, and furthermore is the <i>uniquely least</i> node greater than both of them. (Note: A general partial order may have many pairs of nodes that do not have any node greater than both of them, or may that may have more than one incomparable node greater than them.) We can define ∧ (meet) dually, as the uniquely greatest node less than both of them. If all elements of a partially ordered set have a join and meet, we have a lattice.</p>
<p>It is tempting to read meet and join as "and" and "or" in logic. But these logical connectives satisfy an additional important property — distributivity: a & (b | c) = (a & b) | (a & c). (By the lattice laws, the dual property with and swapped with or is also implied). Translated for lattices this reads: a ∧ (b ∨ c) = (a ∧ b) ∨ (a ∧ c). Rather than thinking just about boolean logic, we can think about lattices built from sets — with meets as union, join as intersection, and ≤ given by inclusion. It is easy to verify that such lattices are distributive. Furthermore, every distributive lattice can be given (up to isomorphism) as one built out of sets in this way. While a partially ordered set can have a Hasse diagram of pretty arbitrary shape, a lattice is more restrictive — I imagine it as sort of the tiled diamonds of an actual lattice like one might use in a garden, but with some nodes and edges possibly removed.</p>
<p>Furthermore, there's an amazing result that you can tell if a lattice is distributive by looking for just two prototypical non-distributive lattices as sublattices. If neither is contained in the original lattice, then the lattice is distributed. These tell us how distribution can fail in two canonical ways. The first is three incomparable elements, all of which share a common join (the top) and meet (the bottom). The join of anything but their bottom element with them is therefore the top. Hence if we take the meet of two joins, we still get the top. But the meet of any two non-top elements is the bottom and so, if we take the join of any element with the meet of any other two, we get back to the first element, not all the way to the top, and the equality fails. The second taboo lattice is constructed by having two elements in an ordered relationship, and another incomparable to them — again  augmented with a bottom and top. A similar argument shows that if you go one way across the desired entity, you pick out the topmost of the two ordered elements, and the other way yields the bottommost. (The <a href="https://en.wikipedia.org/wiki/Distributive_lattice#Characteristic_properties">wikipedia article on distributive lattices</a> has some very good diagrams to visualize all this). So a distributive lattice has even more structure than before — incomparable elements must have enough meets and joins to prevent these sublattices from appearing, and this forces even more the appearance of a tiled-diamond like structure.</p>
<p>To get us to a Heyting algebra, we need more structure still — we need implication, which is like an internal function arrow, or an internal ≤ relation. Recall that the equation we want to satisfy is "c ∧ a ≤ b < -> c ≤ a → b". The idea is that we should be able to read ≤ itself as an "external implication" and so if c and a taken together imply b, "a implies b" is the portion of that implication if we "only have" c. We can see it as a partial application of the external implication. If we have a lattice that permits infinite joins (or just a finite lattice such that we don't need them), then it is straightforward to see how to construct this. To build a → b, we just look at <i>every possible</i> choice of c that satisfies c ∧ a ≤ b, and then take the join of all of them to be our object a → b. Then, by construction, a → b is necessarily greater than or equal to any c that satisfies the left hand side of the equation. And conversely, any element that a → b is greater than is necessarily one that satisfies the left hand side, and the bi-implication is complete. (This, by the way, gives a good intuition for the definition of an exponential in a category of presheaves). Another way to think of a → b is as the greatest element of the lattice such that a → b ∧ a ≤ b (exercise: relate this to the first definition). It is also a good exercise to explore what happens in certain simple cases — what if a is 0 (false)? What if it is 1? The same as b? Now ask the same questions of b.</p>
<p>So why is a Heyting algebra a <i>topological</i> construct? Consider any topological space as given by a collection of open sets, satisfying the usual principles (including the empty set and the total set, and closed under union and finite intersection). These covers have a partial ordering, given by containment. They have unions and intersections (all joins and meets), a top and bottom element (the total space, and the null space). Furthermore, they have an implication operation as described above. As an open set, a → b is given by the meet of all opens c for which a ∧ c ≤ b. (We can think of this as "the biggest context, for which a ⊢ b"). In fact, the axioms for open sets feel almost exactly like the rules we've described for Heyting algebras. It turns out this is only half true — open sets always give Heyting algebras, and we can turn every Heyting algebra into a space. However, in both directions the round trip may take us to somewhere slightly different than where we started. Nonetheless it turns out that if we take complete Heyting algebras where finite meets distribute over infinite joins, we get something called "frames." And the opposite category of frames yields "locales" — a suitable generalization of topological spaces, first named by John Isbell in 1972 [<a href="#5">5</a>].  Spaces that correspond precisely to locales are called <i>sober</i>, and locales that correspond precisely to spaces are said to have "enough points" or be "spatial locales".</p>
<p>In fact, we don't need to fast-forward to 1972 to get some movement in the opposite direction. In 1944, McKinsey and Tarski embarked on a program of "The Algebra of Topology" which sought to describe topological spaces in purely algebraic (axiomatic) terms [<a href="#6">6</a>]. The resultant closure algebras (these days often discussed as their duals, interior algebras) provided a semantics for S4 modal logic. [<a href="#7">7</a>] A further development in this regard came with Kripke models for logic [<a href="#8">8</a>] (though arguably they're really Beth models [<a href="#9">9</a>]).</p>
<p>Here's an easy way to think about Kripke models. Start with any partial ordered set. Now, for each object, instead consider instead all morphisms into it. Since each morphism from any object a to any object b exists only if a ≤ b, and we consider such paths unique (if there are two "routes" showing a ≤ b, we consider them the same in this setting) this amounts to replacing each element a with the set of all elements ≤ a. (The linked pdf does this upside down, but it doesn't really matter). Even though the initial setting may not have been Heyting algebra, this transformed setting <i>is</i> a Heyting algebra. (In fact, by a special case of the Yoneda lemma!). This yields Kripke models.</p>
<p>Now consider "collapsings" of elements in the initial partial order — monotone downwards maps taken by sending some elements to other elements less than them in a way that doesn't distort orderings. (I.e. if f(a) ≤ f(b) in the collapsed order, then that means that a ≤ b in the original order). Just as we can lift elements from the initial partial order into their downsets (sets of elements less than them) in the kripkified Heyting Algebra, we can lift our collapsing functions into collapsing functions in our generated Heyting Algebra. With a little work we can see that collapsings in the partial order also yield collapsings in the Heyting Algebra.</p>
<p>Furthermore, it turns out, more or less, that you can generate every closure algebra in this way. Now if we consider closure algebras a bit (and this shouldn't surprise us if we know about S4), we see that we can always take a to Ca, that if we send a → b, then we can send Ca → Cb, and furthermore that CCa → Ca in a natural way (in fact, they're equal!). So closure algebras have the structure of an idempotent monad. (Note: the arrows here should not be seen as representing internal implication — as above they represent the logical turnstile ⊢ or perhaps, if you're really in a Kripke setting, the forcing turnstile ⊩).</p>
<p>Now we have a correspondence between logic and computation (Curry-Howard), logic and categories (Lambek-Scott), and logic and spaces (Tarski-Stone). So maybe, instead of Curry-Howard-Lambek, we should speak of Curry-Howard-Lambek-Scott-Tarski-Stone! (Or, if we want to actually bother to say it, just Curry-Howard-Lambek-Stone. Sorry, Tarski and Scott!) Where do the remaining correspondences arise from? A cubical Kan operation, naturally! But let us try to sketch in a few more details.</p>
<h4>3. Spaces, Categories</h4>
<p>All this about monads and Yoneda suggests that there's something categorical going on. And indeed, there is. A poset is, in essence, a "decategorified category" — that is to say, a category where any two objects have at most one morphism between them. I think of it as if it were a balloon animal that somebody let all the air out of. We can pick up the end of our poset and blow into it, inflating the structure back up, and allowing multiple morphisms between each object. If we do so, something miraculous occurs — our arbitrary posets turn into arbitrary categories, and the induced Heyting algebra from their opens turns into the induced category of set-valued presheaves of that category. The resultant structure is a presheaf topos. If we "inflate up" an appropriate notion of a closure operator we arrive at a Grothendieck topos! And indeed, the internal language of a topos is higher-order intuitionistic type theory [<a href="#10">10</a>].</p>
<h4>4. Spaces, Programming Languages</h4>
<p>All of this suggests a compelling story: logic describes theories via algebraic syntax. Equipping these theories with various forms of structural operations produces categories of one sort or another, in the form of fibrations. The intuition is that types are spaces, and contexts are <i>also</i> spaces. And furthermore, types are <i>covered</i> by the contexts in which their terms may be derived. This is one sense in which we it seems possible to interpret the Meillies/Zeilberger notion of a type refinement system as a functor [<a href="#11">11</a>].</p>
<p>But where do programming languages fit in? Programming languages, difficult as it is to sometimes remember, are more than their type theories. They have a semantic of computation as well. For example, a general topos does not have partial functions, or a fixed point combinator. But computations, often, do. This led to one of the first applications of topology to programming languages — the introduction of domain theory, in which terms are special kinds of spaces — directed complete partial orders — and functions obey a special kind of continuity (preservation of directed suprema) that allows us to take their fixed points. But while the category of dcpos is cartesian closed, the category of dcpos with only appropriately continuous morphisms is <i>not</i>. Trying to resolve this gap, one way or another, seems to have been a theme of research in domain theory throughout the 80s and 90s [<a href="#12">12</a>].</p>
<p>Computations can also be concurrent. Topological and topos-theoretic notions again can play an important role. In particular, to consider two execution paths to be "the same" one needs a notion of equivalence. This equivalence can be seen, stepwise, as a topological "two-cell" tracing out at each step an equivalence between the two execution paths. One approach to this is in Joyal, Nielson and Winskel's treatment of open maps [<a href="#13">13</a>]. I've also just seen Patrick Schultz and David I. Spivak's "Temporal Type Theory" which seems very promising in this regard  [<a href="#14">14</a>].</p>
<p>What is the general theme? Computation starts somewhere, and then goes somewhere else. If it stayed in the same place, it would not "compute". A computation is necessarily a path in some sense. Computational settings describe ways to take maps between spaces, under a suitable notion of topology. To describe the spaces themselves, we need a language — that language is a logic, or a type theory. Toposes are a canonical place (though not the only one) where logics and spaces meet (and where, to a degree, we can even distinguish their "logical" and "spatial" content). That leaves categories as the ambient language in which all this interplay can be described and generalized.</p>
<h4>5. Spaces, Categories</h4>
<p>All the above only sketches the state of affairs up to roughly the mid '90s. The connection to spaces starts in the late 30s, going through logic, and then computation. But the categorical notion of spaces we have is in some sense impoverished. A topos-theoretic generalization of a space still only describes, albeit in generalized terms, open sets and their lattice of subobject relations. Spaces have a whole other structure built on top of that. From their topology we can extract algebraic structures that describe their shape — this is the subject of algebraic topology. In fact, it was in axiomatizing a branch of algebraic topology (homology) that category theory was first compelled to be invented. And the "standard construction" of a monad was first constructed in the study of homology groups (as the Godement resolution).</p>
<p>What happens if we turn the tools of categorical generalization of algebraic topology on categories themselves? This corresponds to another step in the "categorification" process described above. Where to go from "0" to "1" we took a partially ordered set and allowed there to be multiple maps between objects, to go from "1" to "2" we can now take a category, where such multiple maps exist, and allow there to be multiple maps <i>between maps</i>.  Now two morphisms, say "f . g" and "h" need not merely be equal or not, but they may be "almost equal" with their equality given by a 2-cell. This is just as two homotopies between spaces may themselves be homotopic. And to go from "2" to "3" we can continue the process again. This yields n-categories. An n-category with all morphisms at every level invertible is an (oo,0)-category, or an infinity groupoid. And in many setups this is the same thing as a topological space (and the question of which setup is appropriate falls under the name "homotopy hypothesis" [<a href="#15">15</a>]). When morphisms at the first level (the category level) can have direction (just as in normal categories) then those are (oo,1)-categories, and the correspondence between groupoids and spaces is constructed as an equivalence of such categories. These too have direct topological content, and one setting in which this is especially apparent is that of quasi-categories, which are (oo,1)-categories that are built directly from simplicial sets — an especially nice categorical model of spaces (the simplicial sets at play here are those that satisfy a "weak" Kan condition, which is a way of asking that composition behave correctly).</p>
<p>It is in these generalized (oo,1)-toposes that homotopy type theory takes its models. And, it is hypothesized that a suitable version of HoTT should in fact be the initial model (or "internal logic") of an "elementary infinity topos" when we finally figure out how to describe what such a thing is.</p>
<p>So perhaps it is not that we should be computational trinitarians, or quadrinitarians. Rather, it is that the different aspects which we examine — logic, languages, categories, spaces — only appear as distinct manifestations when viewed at a low dimensionality. In the untruncated view of the world, the modern perspective is, perhaps, topological pantheism — spaces are in all things, and through spaces, all things are made as one.</p>
<p><i>Thanks to James Deikun and Dan Doel for helpful technical and editorial comments</i></p>
<p>[<a name="1"></a>1] <a href="https://existentialtype.wordpress.com/2011/03/27/the-holy-trinity/">https://existentialtype.wordpress.com/2011/03/27/the-holy-trinity/<br />
[</a><a name="2"></a>2] <a href="https://arxiv.org/abs/1705.04310">https://arxiv.org/abs/1705.04310</a><br />
[<a name="3"></a>3] <a href="http://www.sciacchitano.it/Tempo/Aussagenkalk%C3%BCl%20Topologie.pdf">http://www.sciacchitano.it/Tempo/Aussagenkalk%C3%BCl%20Topologie.pdf</a><br />
[<a name="4"></a>4] <a href="https://eudml.org/doc/27235">https://eudml.org/doc/27235</a><br />
[<a name="5"></a>5] <a href="http://www.mscand.dk/article/view/11409">http://www.mscand.dk/article/view/11409</a><br />
[<a name="6"></a>6] <a href="https://www.dimap.ufrn.br/~jmarcos/papers/AoT-McKinsey_Tarski.pdf">https://www.dimap.ufrn.br/~jmarcos/papers/AoT-McKinsey_Tarski.pdf</a><br />
[<a name="7"></a>7] <a href="https://logic.berkeley.edu/colloquium/BezhanishviliSlides.pdf">https://logic.berkeley.edu/colloquium/BezhanishviliSlides.pdf</a><br />
[<a name="8"></a>8] <a href="www2.math.uu.se/~palmgren/tillog/heyting3.pdf">www2.math.uu.se/~palmgren/tillog/heyting3.pdf</a><br />
[<a name="9"></a>9] <a href="http://festschriften.illc.uva.nl/j50/contribs/troelstra/troelstra.pdf">http://festschriften.illc.uva.nl/j50/contribs/troelstra/troelstra.pdf</a><br />
[<a name="10"></a>10] <a href="http://www.sciencedirect.com/science/article/pii/0022404980901024">http://www.sciencedirect.com/science/article/pii/0022404980901024</a><br />
[<a name="11"></a>11] <a href="https://arxiv.org/abs/1310.0263">https://arxiv.org/abs/1310.0263</a><br />
[<a name="12"></a>12] <a href="https://www.dpmms.cam.ac.uk/~martin/Research/Oldpapers/synthetic91.pdf">https://www.dpmms.cam.ac.uk/~martin/Research/Oldpapers/synthetic91.pdf</a><br />
[<a name="13"></a>13] <a href="http://www.brics.dk/RS/94/7/index.html">http://www.brics.dk/RS/94/7/index.html</a><br />
[<a name="14"></a>14] <a href="https://arxiv.org/abs/1710.10258">https://arxiv.org/abs/1710.10258</a><br />
[<a name="15"></a>15] <a href="https://ncatlab.org/nlab/show/homotopy+hypothesis">https://ncatlab.org/nlab/show/homotopy+hypothesis</a></p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2018/computational-quadrinitarianism-curious-correspondences-go-cubical/feed/</wfw:commentRss>
		<slash:comments>103</slash:comments>
		</item>
		<item>
		<title>The State Comonad</title>
		<link>http://comonad.com/reader/2018/the-state-comonad/</link>
		<comments>http://comonad.com/reader/2018/the-state-comonad/#comments</comments>
		<pubDate>Sat, 06 Jan 2018 15:50:11 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[functional programming]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=1139</guid>
		<description><![CDATA[Is there a State Comonad?]]></description>
			<content:encoded><![CDATA[<p>Is <code>State</code> a <code>Comonad</code>? </p>
<p>Not <code>Costate</code> or rather, <code>Store</code> as we tend to call it today, but actually <code>State s</code> itself?</p>
<p>Let's see!</p>
<p><span id="more-1139"></span></p>
<p>Recently there was a <a href="https://www.reddit.com/r/haskell/comments/7oav51/i_made_a_monad_that_i_havent_seen_before_and_i/">post to reddit</a> in which the author <code>King_of_the_Homeless</code> suggested that he might have a <code>Monad</code> for <code>Store</code>. Moreover, it is one that is compatible with the existing <code>Applicative</code> and <code>ComonadApply</code> instances. My <a href="https://www.reddit.com/r/haskell/comments/7oav51/i_made_a_monad_that_i_havent_seen_before_and_i/ds81x2a/">knee-jerk reaction</a> was to disbelieve the result, but I'm glad I stuck with playing with it over the last day or so.</p>
<p>In a much older post, I showed how to use the <code>Co</code> <a href="http://comonad.com/reader/2011/monads-from-comonads/">comonad-to-monad-transformer</a> to convert <code>Store s</code> into <code>State s</code>, but this is a different beast, it is a monad directly on <code>Store s</code>.</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# language DeriveFunctor #-}</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a>
<span style="color: #06c; font-weight: bold;">import</span> Data.Semigroup
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Store s a = Store
  <span style="color: green;">&#123;</span> peek :: s -&gt; a, pos :: s <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;">instance</span> <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#t:Comonad"><span style="background-color: #efefbf; font-weight: bold;">Comonad</span></a> <span style="color: green;">&#40;</span>Store s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> <span style="color: green;">&#40;</span>Store f s<span style="color: green;">&#41;</span> = f s
  <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a> <span style="color: green;">&#40;</span>Store f s<span style="color: green;">&#41;</span> = Store <span style="color: green;">&#40;</span>Store f<span style="color: green;">&#41;</span> s
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span>
 <span style="color: green;">&#40;</span>Semigroup s, Monoid s<span style="color: green;">&#41;</span> =&gt;
 Applicative <span style="color: green;">&#40;</span>Store s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure a = Store <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:const"><span style="font-weight: bold;">const</span></a> a<span style="color: green;">&#41;</span> mempty
  Store f s &lt; *&gt; Store g t = Store <span style="color: green;">&#40;</span>\m -&gt; f m <span style="color: green;">&#40;</span>g m<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>mappend s t<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span>
 Semigroup s =&gt;
 ComonadApply <span style="color: green;">&#40;</span>Store s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  Store f s &lt; @&gt; Store g t = Store <span style="color: green;">&#40;</span>\m -&gt; f m <span style="color: green;">&#40;</span>g m<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>s &lt;&gt; t<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span>
 <span style="color: green;">&#40;</span>Semigroup s, Monoid s<span style="color: green;">&#41;</span> =&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>Store s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> = pure
  m &gt;&gt;= k = Store
    <span style="color: green;">&#40;</span>\s -&gt; peek <span style="color: green;">&#40;</span>k <span style="color: green;">&#40;</span>peek m s<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> s<span style="color: green;">&#41;</span>
    <span style="color: green;">&#40;</span>pos m `mappend` pos <span style="color: green;">&#40;</span>k <span style="color: green;">&#40;</span>peek m mempty<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>My apologies for the <code>Semigroup</code> vs. <code>Monoid</code>, noise, as I'm still using GHC 8.2 locally. This will get a bit cleaner in a couple of months.</p>
<p>Also, <code>peek</code> here is flipped relative to the version in <code>Control.Comonad.Store.Class</code> so that I can use it directly as a field accessor.</p>
<p>As I noted, at first I was hesitant to believe it could work, but then I realized I'd <a href="https://hackage.haskell.org/package/streams-3.3/docs/Data-Stream-Infinite-Functional-Zipper.html">already implemented</a> something like this for a special case of Store, in the 'streams' library, which got me curious. Upon reflection, this feels like the usual Store comonad is using the ability to distribute <code>(->) e</code> out or <code>(,) e</code> in using a "comonoid", which is always present in Haskell, just like how the State monad does. But the type above seems to indicate we can go the opposite direction with a monoid.</p>
<p>So, in the interest of exploring duality, let's see if we can build a comonad instance for `State s`!</p>
<p>Writing down the definition for state:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> State s a = State
  <span style="color: green;">&#123;</span> runState :: s -&gt; <span style="color: green;">&#40;</span>a, s<span style="color: green;">&#41;</span> <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;">instance</span> Applicative <span style="color: green;">&#40;</span>State s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  pure a = State $ \s -&gt; <span style="color: green;">&#40;</span>a, s<span style="color: green;">&#41;</span>
  State mf &lt; *&gt; State ma = State $ \s -&gt; <span style="color: #06c; font-weight: bold;">case</span> mf s <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span>f, s'<span style="color: green;">&#41;</span> -&gt; <span style="color: #06c; font-weight: bold;">case</span> ma s' <span style="color: #06c; font-weight: bold;">of</span>
      <span style="color: green;">&#40;</span>a, s''<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>f a, s''<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <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>State s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> = pure
  State m &gt;&gt;= k = State $ \s -&gt; <span style="color: #06c; font-weight: bold;">case</span> m s <span style="color: #06c; font-weight: bold;">of</span>
    <span style="color: green;">&#40;</span>a, s'<span style="color: green;">&#41;</span> -&gt; runState <span style="color: green;">&#40;</span>k a<span style="color: green;">&#41;</span> s'
&nbsp;</pre>
<p>Given a monoid for out state, extraction is pretty obvious:</p>
<pre>
instance
 Monoid s =>
 Comonad (State s) where
  extract m = fst $ runState m mempty
</pre>
<p>But the first stab we might take at how to duplicate, doesn't work.</p>
<pre class="haskell">&nbsp;
  <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> m = State $ \s -&gt;
   <span style="color: green;">&#40;</span>State $ \t -&gt; runState m <span style="color: green;">&#40;</span>mappend s t<span style="color: green;">&#41;</span>
   , s
   <span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>It passes the `extract . duplicate = id` law easily:</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> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a> m<span style="color: green;">&#41;</span>
= <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> $ State $ \s -&gt; <span style="color: green;">&#40;</span>State $ \t -&gt; runState m <span style="color: green;">&#40;</span>mappend s t<span style="color: green;">&#41;</span>, s<span style="color: green;">&#41;</span>
= State $ \t -&gt; runState m <span style="color: green;">&#40;</span>mappend s mempty<span style="color: green;">&#41;</span>
= State $ \t -&gt; runState m t
= State $ runState m
= m
&nbsp;</pre>
<p>But fails the second law:</p>
<pre class="haskell">&nbsp;
<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> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a> 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://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> $ State $ \s -&gt; <span style="color: green;">&#40;</span>State $ \t -&gt; runState m <span style="color: green;">&#40;</span>mappend s t<span style="color: green;">&#41;</span>, s<span style="color: green;">&#41;</span>
= State $ \s -&gt; <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> $ State $ \t -&gt; runState m <span style="color: green;">&#40;</span>mappend s t<span style="color: green;">&#41;</span>, s<span style="color: green;">&#41;</span>
= State $ \s -&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a> $ runState m <span style="color: green;">&#40;</span>mappend s mempty<span style="color: green;">&#41;</span>, s<span style="color: green;">&#41;</span>
= State $ \s -&gt; <span style="color: green;">&#40;</span>evalState m s, s<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>because it discards the changes in the state.</p>
<p>But the <code>King_of_the_Homeless</code>'s trick from that post (and the Store code above) can be modified to this case. All we need to do is ensure that we modify the output state 's' as if we'd performed the action unmolested by the inner monoidal state that we can't see.</p>
<pre class="haskell">&nbsp;
  <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> m = State $ \s -&gt;
    <span style="color: green;">&#40;</span> State $ \t -&gt; runState m <span style="color: green;">&#40;</span>mappend s t<span style="color: green;">&#41;</span>
    , <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> $ runState m s
    <span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Now:</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> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a> m<span style="color: green;">&#41;</span>
= <a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> $ State $ \s -&gt; <span style="color: green;">&#40;</span>State $ \t -&gt; runState m <span style="color: green;">&#40;</span>mappend s t<span style="color: green;">&#41;</span>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> $ runState m s<span style="color: green;">&#41;</span>
= State $ \t -&gt; runState m <span style="color: green;">&#40;</span>mappend mempty t<span style="color: green;">&#41;</span>
= State $ \t -&gt; runState m t
= State $ runState m
= m
&nbsp;</pre>
<p>just like before, but the inner extraction case now works out and performs the state modification as expected:</p>
<pre class="haskell">&nbsp;
<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> <span style="color: green;">&#40;</span><a href="http://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:duplicate"><span style="font-weight: bold;">duplicate</span></a> 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://comonad.com/haskell/category-extras/dist/doc/html/category-extras/Control-Comonad.html#v:extract"><span style="font-weight: bold;">extract</span></a> $ State $ \s -&gt; <span style="color: green;">&#40;</span>State $ \t -&gt; runState m <span style="color: green;">&#40;</span>mappend s t<span style="color: green;">&#41;</span>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> $ runState m s<span style="color: green;">&#41;</span>
= State $ \s -&gt; <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> $ State $ \t -&gt; runState m <span style="color: green;">&#40;</span>mappend s t<span style="color: green;">&#41;</span>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> $ runState m s<span style="color: green;">&#41;</span>
= State $ \s -&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a> $ runState m <span style="color: green;">&#40;</span>mappend s mempty<span style="color: green;">&#41;</span>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> $ runState m s<span style="color: green;">&#41;</span>
= State $ \s -&gt; <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fst"><span style="font-weight: bold;">fst</span></a> $ runState m s, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:snd"><span style="font-weight: bold;">snd</span></a> $ runState m s<span style="color: green;">&#41;</span>
= State $ \s -&gt; runState m s
= State $ runState m
= m
&nbsp;</pre>
<p>This is still kind of a weird beast as it performs the state action twice with different states, but it does pass at least the left and right unit laws.</p>
<p>Some questions:</p>
<p>1. Proving associativity is left as an exercise. It passes visual inspection and my gut feeling, but I haven't bothered to do all the plumbing to check it out. I've been wrong enough before, it'd be nice to check!</p>
<p>[Edit: Simon Marechal (bartavelle) has a <a href="http://lpaste.net/361413">coq proof</a> of the associativity and other axioms.] </p>
<p>2. Does this pass the <code>ComonadApply</code> laws?</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Monoid s =&gt; ComonadApply <span style="color: green;">&#40;</span>State s<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  <span style="color: green;">&#40;</span>&lt; @&gt;<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>&lt; *&gt;<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>[Edit: <a href="https://www.reddit.com/r/haskell/comments/7ojy6x/the_comonadreader_the_state_comonad/dsabeij/">No</a>.]</p>
<p>3. The streams code above suggests at least one kind of use-case, something like merging together changes of position in a stream, analogous to the "zipping monad" you have on infinite streams. But now the positions aren't just Integers, they are arbitrary values taken from any monoid you want. What other kind of spaces might we want to "zip" in this manner?</p>
<p>4. Is there an analogous construction possible for an <a href="https://www.schoolofhaskell.com/user/edwardk/heap-of-successes#update-vs--state">"update monad"</a> or "coupdate comonad"? Does it require a monoid that acts on a monoid rather than arbitrary state like the <a href="https://www.youtube.com/watch?v=Txf7swrcLYs">semi-direct product of monoids</a> or a <a href="https://www.cse.iitk.ac.in/users/ppk/research/publication/Conference/2016-09-22-How-to-twist-pointers.pdf">"twisted functor"</a>? Is the result if it exists a twisted functor?</p>
<p>5. Does `Co` translate from this comonad to the monad on `Store`?</p>
<p>6. Is there a (co)monad transformer version of these?</p>
<p>Link: <a href="https://gist.github.com/ekmett/1d8029a19546278adab92ebd3057f4b2">Gist</a></p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2018/the-state-comonad/feed/</wfw:commentRss>
		<slash:comments>49</slash:comments>
		</item>
		<item>
		<title>Adjoint Triples</title>
		<link>http://comonad.com/reader/2016/adjoint-triples/</link>
		<comments>http://comonad.com/reader/2016/adjoint-triples/#comments</comments>
		<pubDate>Thu, 14 Jan 2016 00:02:33 +0000</pubDate>
		<dc:creator>Dan Doel</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Type Theory]]></category>
		<category><![CDATA[Uncategorized]]></category>

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

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

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

colim ⊣ Δ ⊣ lim

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

		<guid isPermaLink="false">http://comonad.com/reader/?p=1105</guid>
		<description><![CDATA[I recently attended RDP in Warsaw, where there was quite a bit of work on Homotopy Type Theory, including a special workshop organized to present recent and ongoing work. The organizers of all the events did a fantastic job and there was a great deal of exciting work. I should add that I will not [...]]]></description>
			<content:encoded><![CDATA[<p>I recently attended <a href="http://rdp15.mimuw.edu.pl/">RDP</a> in Warsaw, where there was quite a bit of work on Homotopy Type Theory, including a special workshop organized to present recent and ongoing work. The organizers of all the events did a fantastic job and there was a great deal of exciting work. I should add that I will not be able to go to RDP next year, as the two constituent central conferences (RTA — Rewriting Techniques and Applications and TLCA — Typed Lambda Calculus and Applications) have merged and changed names. Next year it will now be called FSCD — Formal Structures for Computation and Deduction. So I very much look forward to attending FSCD instead.</p>
<p>In any case, one of the invited speakers was Vladimir Voevodsky, who gave an invited talk on his recent work relating to univalent foundations titled "From Syntax to Semantics of Dependent Type Theories — Formalized”. This was a very clear talk that helped me understand his current research direction and the motivations for it. I also had the benefit of some very useful conversations with others involved in collaboration with some of this work, who patiently answered my questions. The notes below are complimentary to the <a href="http://hott-uf.gforge.inria.fr/HOTTUF_Vladimir.pdf">slides from his talk</a>.</p>
<p>I had sort of understood what the motivation for studying “C-Systems” was, but I had not taken it on myself to look at Voevodsky’s <a href="http://arxiv.org/abs/1410.5389">“B-Systems</a>” before, nor had I grasped how his research programme fit together. Since I found this experience enlightening, I figured I might as well write up what I think I understand, with all the usual caveats. Also note, in all the below, by “type theory” I invariably mean the intensional sort. So all the following is in reference to the B-systems paper that Voevodsky has posted on arXiv (<a href="http://arxiv.org/abs/1410.5389">arXiv:1410.5389</a>).</p>
<p>That said, if anything I describe here strikes you as funny, it is more likely that I am not describing things right than that the source material is troublesome — i.e. take this with a grain of salt. And bear in mind that I am not attempting to directly paraphrase Voevodsky himself or others I spoke to, but rather I am giving an account of where what they described resonated with me, and filtered through my own examples, etc. Also, if all of the “why and wherefore” is already familiar to you, feel free to skip directly to the “B-Systems” section where I will just discuss Voevodsky’s paper on this topic, and my attempts to understand portions of it. And if you already understand B-Systems, please do reply and explain all the things I’m sure I’m missing!</p>
<p><span id="more-1105"></span><br />
<strong>Some Review</strong></p>
<p>We have a model of type theory in simiplicial sets that validates the univalence axiom (and now a few other models that validate this axiom as well). This is to say, it is a model with not only higher dimensional structure, but higher structure of a very “coherent” sort. The heart of this relates to our construction of a “universe”. In our categorical model, all our types translate into objects of various sorts. The “universe,” aka the type-of-types, translates into a very special object, one which “indexes” all other objects. A more categorical way of saying this is that all other types are “fibered over” the universe — i.e. that from every other type there is a map back to a specific point within the universe. The univalence axiom can be read as saying that all equivalent types are fibered over points in the universe that are connected (i.e. there is a path between those points).</p>
<p>Even in a relatively simple dependent type theory, equivalence of types quickly becomes undecidable in general, as it is a superset of the problem of deciding type inhabitation, which in turn corresponds to the decidability of propositions in the logic corresponding to a type theory, and then by any number of well-known results cannot be resolved in general for most interesting theories. This in turn means that the structure of a univalent universe is “describable”  but it is not fully enumerable, and is very complex.</p>
<p>We also have a line of work dating back to before the introduction of univalence, which investigated the higher groupoid structure (or, if you prefer, higher topological structure or quillen model structure) induced by identity types. But without either univalence or higher-inductive types, this higher groupoid structure is unobservable internally. This is to say, models were possible that would send types to things with higher structure, but no particular use would be made of this higher structure. So, such models could potentially be used to demonstrate that certain new axioms were not conservative over the existing theory, but on their own they did not provide ideas about how to extend the theory.</p>
<p>How to relate this higher groupoid structure to universes? Well, in a universe, one has paths. Without univalence, these are just identity paths. But regardless, we now get a funny “completion” as our identity paths must <em>themselves</em> be objects in our universe, and so too the paths between them, etc. In models without higher structure, we might say “there is only one path from each object to itself” and then we need not worry too much about this potential explosion of paths at each level. But by enforcing the higher groupoid structure, this means that our universe now blossoms with all the potentially distinct paths at each level. However, with the only way in our syntax to create such “extra paths” as reflexivity, any such path structure in our model remains “latent”, and can be added or removed without any effect.</p>
<p>The univalence axiom relies on these higher groupoid structures, but it cannot be reduced to them. Rather, in the model, we must have a fibration over the universe with identity lifting along this fibration to reach the next step — to then modify the universe by forcing paths other than identity paths — those between equivalent types. This is in a sense a further “higher completion” of our universe, adding in first all the possible paths between types, but then the paths between those paths, and so on up. Because, by univalence, we <em>can</em> state such paths, then in our model we <em>must</em> include all<br />
 of them.</p>
<p><strong>The Problem</strong></p>
<p>All along I have been saying “models of type theory”. And it is true enough. We do know how to model type theories of various sorts categorically (i.e. representing the translation from their syntax into their semantics as functorial). But we do not have full models of "fully-featured" type theories; i.e. if we view type theories as pizzas we have models of cheese slices, and perhaps slices with olives and slices with pepperoni, etc. But we do not have models of pizzas with "all the toppings". Here, by "toppings" I mean things such as the addition of "all inductive types," "some coinductive types," "certain higher-inductive types," "pattern matching," "induction-induction," "induction-recursion," "excluded middle as an axiom," "choice as an axiom," "propositional resizing as an axiom," etc. </p>
<p>Rather, we have a grab bag of tricks, as well as a few slightly different approaches — Categories with Attributes, Categories with Families, and so forth. One peculiar feature of these sorts of models, as opposed to the models of extensional type theory, is that these models are not indexed by types, but by “lists of types” that directly correspond to the contexts in which we make typing judgments in intensional theories.</p>
<p>In any case, these models are usually used in an ad-hoc fashion. If you want to examine a particular feature of a language, you first pick from one of these different but related sorts of models. Then you go on to build a version with the minimal set of what you need — so maybe identity types, maybe sigma types, maybe natural numbers, and then you introduce your new construction or generate your result or the like.</p>
<p>So people may say “we know how to work with these things, and we know the tricks, so given a theory, we can throw together the facts about it pretty quickly.” Now of course there are maybe only a hundred people on the planet (myself not among them) who can <em>really</em> just throw together a categorical model of some one or another dependent type theory at the drop of a hat.</p>
<p>But there’s a broader problem. How can we speak about the mutual compatibility of different extensions and features if each one is validated independently in a different way? This is a problem very familiar to us in the field of programming languages — you have a lot of “improvements” to your language, all of a similar form. But then you put such “improvements” together and now something goes wrong. In fact, the famous “newtype deriving bug” in GHC some years back, which opened a big hole in the type system, was of exactly that form — two extensions (in that case, newtype deriving and type families) that are on their own safe and useful, together have an unexpected bad effect. It is also possible to imagine bad interactions occuring only when three extensions exist together, and soforth. So as the number of extensions increases, the number of interactions to check spirals upwards in a very difficult fashion.</p>
<p>So the correct way to have confidence in the coexistence of these various extensions is to have a general model that contains the sort of theory we actually want to work in, rather than these toy theories that let us look at portions in isolation. And this certainly involves having a theory that lets us validate all inductive types at once in the model, rather than extending it over and over for each new type we add. Additionally, people tend to model things with at most one universe. And when we are not looking at universes, it is often omitted altogether, or done “incorrectly” as an inhabitant of itself, purely for the sake of convenience.</p>
<p>So now, if I tell someone with mathematical experience what my theory “means” and they say “is this actually proven” I’m in the embarrassing position of saying “no, it is not. but the important bits all are and we know how to put them together.” So here I am, trying to advocate the idea of fully formal verification, but without a fully top-to-bottom formally verified system myself — not even codewise, but in even the basic mathematical sense.</p>
<p>Univalence makes this problem more urgent. Without univalence, we can often get away with more hand-wavy arguments, because things are “obvious”. Furthermore, they relate to the way things are done elsewhere. So logic can be believed by analogy to how people usually think about logic, numbers by analogy to the peano system, which people already “believe in,” and soforth. Furthermore, without univalence, most operations are “directly constructive” in the sense that you can pick your favorite “obvious” and non-categorical model, and they will tend to hold in that as well — so you can think of your types as sets, and terms as elements of sets. Or you can think of your types as classifying computer programs and your terms as runnable code, etc. In each case, the behavior leads to basically what you would expect.</p>
<p>But in none of these “obvious” models does univalence hold. And furthermore, it is “obviously” wrong in them.</p>
<p>And that is just on the “propaganda” side as people say. For the same reasons, univalence tends to be incompatible with many “obvious” extensions — for example, not only “uniqueness of identity proofs” has to go, but pattern matching had to be rethought so as not to imply it, and furthermore it is not known if it is sound in concert with many other extensions such as general coinductive types, etc. (In fact, the newtype deriving bug itself can be seen as a "very special case" of the incompatibility of univalence with Uniqueness of Identity Proofs, as I have been discussing with people informally for quite some time).</p>
<p>Hence, because univalence interacts with so many other extensions, it feels even more urgent to have a full account. Unlike prior research, which really focused on developing and understanding type systems, this is more of an engineering problem, although a proof-engineering problem to be sure.</p>
<p><strong>The Approach</strong></p>
<p>Rather than just giving a full account of “one important type system,” Voevodsky seems to be aiming for a generally smooth way to develop such full accounts even as type systems change. So he is interested in reusable technology, so to speak. One analogy may be that he is interested in building the categorical semantics version of a logical framework. His tool for doing this is what he calls a “<a href="http://arxiv.org/abs/1410.5389">C-system</a>”, which is a slight variant of Cartmell’s Categories with Attributes mentioned above. One important aspect of C-systems seems to be that that they stratify types and terms in some fashion, and that you can see them as generated by some “data” about a ground set of types, terms, and relations. To be honest, I haven’t looked at them more closely than that, since I saw at least some of the “point” of them and know that to really understand the details I'll have to study categorical semantics more generally, which is ongoing.</p>
<p>But the plan isn’t just to have a suitable categorical model of type theories. Rather it is to give a description of how one goes from the “raw terms” as syntax trees all the way through to how typing judgments are passed on them and then to their full elaborations in contexts and finally to their eventual “meaning” as categorically presented.</p>
<p>Of course, most of these elements are well studied already, as are their interactions. But they do not live in a particularly compatible formulation with categorical semantics. This then makes it difficult to prove that “all the pieces line up” and in particular, a pain to prove that a given categorical semantics for a given syntax is the “initial” one — i.e. that if there is any other semantics for that syntax, it can be arrived at by first “factoring through” the morphism from syntax to the initial semantics. Such proofs can be executed, but again it would be good to have “reusable technology” to carry them out in general.</p>
<p><strong>pre-B-Systems</strong></p>
<p>Now we move into the proper notes on <a href="http://arxiv.org/abs/1410.5389">Voevodsky's "B-Systems" paper</a>. </p>
<p>If C-systems are at the end-point of the conveyor belt, we need the pieces in the middle. And that is what a B-system is. Continuing the analogy with the conveyor belt, what we get out at the end is a “finished piece” — so an object in a C-system is a categorified version of a “type in-context” capturing the “indexing” or “fibration” of that type over its “base space” of types it may depend on, and also capturing the families of terms that may be formed in various different contexts of other terms with other types.</p>
<p>B-systems, which are a more “syntactic” presentation, have a very direct notion of “dynamics” built in — they describe how objects and contexts may be combined and put together, and directly give, by their laws, which slots fit into which tabs, etc. Furthermore, B-systems are to be built by equipping simpler systems with successively more structure. This gives us a certain sort of notion of how to talk about the distinction between things closer to "raw syntax" (not imbued with any particular meaning) and that subset of raw syntactic structures which have certain specified actions.</p>
<p>So enough prelude. What precisely is a B-system? We start with a pre-B-system, as described below (corresponding to Definition 2.1 in the paper).</p>
<p>First there is a family of sets, indexed by the natural numbers. We call it <code>B_n</code>. <code>B_0</code> is to be thought of as the empty context. <code>B_1</code> as the set of typing contexts with one element, <code>B_2</code> as the set with two elements, where the second may be indexed over the first, etc. Elements of <code>B_3</code> thus can be thought of as looking like "<code>x_1 : T_1, x_2 : T_2(x_1), x_3 : T_3(x_1,x_2)</code>" where <code>T_2</code> is a type family over one type, <code>T_3</code> a type family over two types, etc.</p>
<p>For all typing contexts of at least one element, we can also interpret them as simply the _type_ of their last element, but as indexed by the types of all their prior elements. Conceptually, <code>B_n</code> is the set of "types in context, with no more than n-1 dependencies".</p>
<p>Now, we introduce another family of sets, indexed by the natural numbers starting at 1. We call this set <code>˜B_n</code>. <code>˜B_1</code> is to be thought of as the set of all values that may be drawn from any type in the set B_1, and soforth. Thus, each set <code>˜B_n </code>is to be thought of as fibered over <code>B_n</code>. We think of this as "terms in context, whose types have no more than n-1 dependencies". Elements of <code>˜B_3</code> can be though of as looking like "<code>x_1 : T_1, x_2 : T_2(x_1), x_3 : T_3(x_1,x_2) ⊢ y : x</code>". That is to say, elements of <code>B_n</code> for some n look like "everything to the left of the turnstile" and elements of ˜B_n for some n look like "the left and right hand sides of the turnstile together."</p>
<p>We now, for each n, give a map:</p>
<p><code>∂ : ˜B_n+1 -> B_n+1.</code></p>
<p>This map is the witness to this fibration. Conceptually, it says "give me an element of some type of dependency level n, and I will pick out which type this is an element of". We can call ∂ the "type of" operator.</p>
<p>We add a second basic map:</p>
<p><code>ft : B_n+1 -> B_n</code></p>
<p>This is a witness to the fact that all our higher <code>B_n</code> are built as extensions of smaller ones. It says "Give me a context, and I will give you the smaller context that has every element except the final one". Alternately, it reads "Give me a type indexed over a context, and I will throw away the type and give back just the context." Or, "Give me a type that may depend on n+1 things, and I will give the type it depends on that may only depend on n things. We can call ft the "context of" operator.</p>
<p>Finally, we add a number of maps to correspond to weakening and substitution -- four in all. In each case, we take m >= n. we denote the i-fold application of <code>ft</code> by <code>ft_i</code>.</p>
<p>1) T (type weakening).</p>
<p><code>T : (Y : B_n+1) -> (X : B_m+1) -> ft(Y) = ft_(m+1-n)(X) -> B_m+2<br />
</code><br />
This reads: Give me two types-in-context, X and Y. Now, if the context for Y agrees with the context for X in the initial segment (i.e. discarding the elements of the context of X which are "longer" than the context for Y), then I can give you back X again, but now in an extended context that includes Y as well.</p>
<p>2) ˜T (term weakening).</p>
<p><code>˜T : (Y : B_n+1) -> (r : ˜B_m+1) -> ft(Y)=ft_(m+1-n)(∂(r)) -> ˜B_m+2</code></p>
<p>This reads: Give me a type-in-context Y, and a term-in-context r. Now, if the context of Y agrees with the context for the type of r as above, then I can give you back r again, but now as a term-in-context whose type has an extended context that includes Y as well.</p>
<p>3) S (type substitution).</p>
<p><code>S : (s : ˜B_n+1) -> (X : B_m+2) -> ∂(s) = ft_(m+1-n)(X) -> B_m+1</code></p>
<p>This reads: give me a term-in-context s, and a type-in-context X. Now, if the context of the type of s agrees with the context of the X in the initial segment, we may then produce a new type, which is X with one less element in its context (because we have substituted the explicit term s for where the prior dependency data was recorded).</p>
<p>4) ˜S (term substitution).</p>
<p><code>˜S : (s : ˜B_n+1) -> (r : ˜B_m+2) -> ∂(s) = ft_(m+1-n)(∂(r)) -> ˜B_m+1</code></p>
<p>This reads: give me two terms-in-context, r and s. Now given the usual compatibility condition on contexts, we can produce a new term, which is like r, but where the context has one less dependency (because we have substituted the explicit term s for everywhere where there was dependency data prior).</p>
<p>Let us now review what we have: We have dependent terms and types, related by explicit maps between them. For every term we have its type, and for every type we have its context. Furthermore, we have weakening by types of types and terms -- so we record where "extra types" may be introduced into contexts without harm. We also have substitution of terms into type and terms -- so we record where reductions may take place, and the resulting effect on the dependency structure.</p>
<p><strong>Unital pre-B-systems</strong></p>
<p>We now introduce a further piece of data, which renders a pre-B-system a _unital_ pre-B-system, corresponding to Definition 2.2 in the paper. For each n we add an operation:</p>
<p><code>δ : B_n+1 -> ˜B_n+2</code></p>
<p>This map "turns a context into a term". Conceptually it is the step that equips a pre-B-system with a universe, as it is what allows types to transform into terms. I find the general definition a bit confusing, but I believe it can be rendered syntactically for for B_2, it can be as something like the following: "<code>x_1 : T_1, x_2 : T_2(x_1) -> x_1 : T_1, x_2 : T_2(x_1), x_3 : U  ⊢ x_2 : x_3</code>". That is to say, given any context, we now have a universe <code>U</code> that gives the type of "universes of types", and we say that the type itself is a term that is an element of a universe. Informally, one can think of <code>δ</code> as the "term of" operator.</p>
<p>But this specific structure is not indicated by any laws yet on δ. Indeed, the next thing we do is to introduce a "B0-system" which adds some further coherence conditions to restrict this generality.</p>
<p><strong>B0-systems</strong></p>
<p>The following are my attempt to "verbalize" the B0 system conditions (as restrictions on non-unital pre-B-systems) as covered in definition 2.5. I do not reproduce here the actual formal statements of these conditions, for which one should refer to the paper and just reason through very carefully.</p>
<p>1. The context of a weakening of a type is the same as the weakening of the context of a type.</p>
<p>2. The type of the weakening of a term is the same as the weakening of the type of a term.</p>
<p>3. The context of a substitution into a type is the same as the substitution into a context of a type</p>
<p>4. The type of a substitution into a term is the same as a substitution into the type of a term.</p>
<p>Finally, we "upgrade" a non-unital B0-system to a unital B0-system with one further condition:</p>
<p>5. <code>∂(δ(X)) =T(X,X).</code></p>
<p>I read this to say that, "for any type-in-context X, the type of the term of X is the same as the weakening of the context of X by the assumption of X itself." This is to say, if I create a term for some type X, and then discard that term, this is the same as extending the context of X by X again.</p>
<p>Here, I have not even gotten to "full" B-systems yet, and am only on page 5 of a seventeen page paper. But I have been poking at these notes for long enough without posting them, so I'll leave off for now, and hopefully, possibly, when time permits, return to at least the second half of section 2.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2015/some-rough-notes-on-univalent-foundations-and-b-systems-part-i/feed/</wfw:commentRss>
		<slash:comments>423</slash:comments>
		</item>
		<item>
		<title>On the unsafety of interleaved I/O</title>
		<link>http://comonad.com/reader/2015/on-the-unsafety-of-interleaved-io/</link>
		<comments>http://comonad.com/reader/2015/on-the-unsafety-of-interleaved-io/#comments</comments>
		<pubDate>Wed, 22 Jul 2015 15:29:59 +0000</pubDate>
		<dc:creator>Dan Doel</dc:creator>
				<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/?p=1056</guid>
		<description><![CDATA[One area where I'm at odds with the prevailing winds in Haskell is lazy I/O. It's often said that lazy I/O is evil, scary and confusing, and it breaks things like referential transparency. Having a soft spot for it, and not liking most of the alternatives, I end up on the opposite side when the [...]]]></description>
			<content:encoded><![CDATA[<p>One area where I'm at odds with the prevailing winds in Haskell is lazy I/O. It's often said that lazy I/O is evil, scary and confusing, and it breaks things like referential transparency. Having a soft spot for it, and not liking most of the alternatives, I end up on the opposite side when the topic comes up, if I choose to pick the fight. I usually don't feel like I come away from such arguments having done much good at giving lazy I/O its justice. So, I thought perhaps it would be good to spell out my whole position, so that I can give the best defense I can give, and people can continue to ignore it, without costing me as much time in the future. :)</p>
<p>So, what's the argument that lazy I/O, or <code>unsafeInterleaveIO</code> on which it's based, breaks referential transparency? It usually looks something like this:</p>
<pre class="haskell">&nbsp;
swap <span style="color: green;">&#40;</span>x, y<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>y, x<span style="color: green;">&#41;</span>
&nbsp;
setup = <span style="color: #06c; font-weight: bold;">do</span>
  r1 &lt; - newIORef <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>
  r2 &lt;- newIORef <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:True"><span style="font-weight: bold;">True</span></a>
  v1 &lt;- unsafeInterleaveIO $ <span style="color: #06c; font-weight: bold;">do</span> writeIORef r2 <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> ; readIORef r1
  v2 &lt;- unsafeInterleaveIO $ <span style="color: #06c; font-weight: bold;">do</span> writeIORef r1 <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:False"><span style="font-weight: bold;">False</span></a> ; readIORef r2
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> <span style="color: green;">&#40;</span>v1, v2<span style="color: green;">&#41;</span>
&nbsp;
main = <span style="color: #06c; font-weight: bold;">do</span>
  p1 &lt;- setup
  p2 &lt;- setup
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:print"><span style="font-weight: bold;">print</span></a> p1
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:print"><span style="font-weight: bold;">print</span></a> . swap $ p2
&nbsp;</pre>
<p>I ran this, and got:</p>
</pre>
<pre>
(True, False)
(True, False)
</pre>
<p>So this is supposed to demonstrate that the pure values depend on evaluation order, and we have broken a desirable property of Haskell.</p>
<p>First a digression. Personally I distinguish the terms, "referential transparency," and, "purity," and use them to identify two desirable properties of Haskell. The first I use for the property that allows you to factor your program by introducing (or eliminating) named subexpressions. So, instead of:</p>
<pre class="haskell">&nbsp;
f e e
&nbsp;</pre>
<p>we are free to write:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">let</span> x = e <span style="color: #06c; font-weight: bold;">in</span> f x x
&nbsp;</pre>
<p>or some variation. I have no argument for this meaning, other than it's what I thought it meant when I first heard the term used with respect to Haskell, it's a useful property, and it's the best name I can think of for the property. I also (of course) think it's better than some of the other explanations you'll find for what people mean when they say Haskell has referential transparency, since it doesn't mention functions or "values". It's just about equivalence of expressions.</p>
<p>Anyhow, for me, the above example is in no danger of violating referential transparency. There is no factoring operation that will change the meaning of the program. I can even factor out <code>setup</code> (or inline it, since it's already named):</p>
<pre class="haskell">&nbsp;
main = <span style="color: #06c; font-weight: bold;">let</span> m = setup
        <span style="color: #06c; font-weight: bold;">in</span> <span style="color: #06c; font-weight: bold;">do</span> p1 &lt; - m
              p2 &lt;- m
              <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:print"><span style="font-weight: bold;">print</span></a> p1
              <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:print"><span style="font-weight: bold;">print</span></a> . swap $ p2
&nbsp;</pre>
<p>This is the way in which <code>IO</code> preserves referential transparency, unlike side effects, in my view (note: the embedded language represented by <code>IO</code> does not have this property, since otherwise <code>p1</code> could be used in lieu of <code>p2</code>; this is why you shouldn't spend much time writing <code>IO</code> stuff, because it's a bad language embedded in a good one).</p>
<p>The other property, "purity," I pull from Amr Sabry's paper, <a href="http://www.cs.indiana.edu/~sabry/papers/purelyFunctional.ps">What is a Purely Functional Language?</a> There he argues that a functional language should be considered "pure" if it is an extension of the lambda calculus in which there are no contexts which observe differences in evaluation order. Effectively, evaluation order must only determine whether or not you get an answer, not change the answer you get.</p>
<p>This is slightly different from my definition of referential transparency earlier, but it's also a useful property to have. Referential transparency tells us that we can freely refactor, and purity tells us that we can change the order things are evaluated, both without changing the meaning of our programs.</p>
<p>Now, it would seem that the original interleaving example violates purity.  Depending on the order that the values are evaluated, opponents of lazy I/O say, the values change. However, this argument doesn't impress me, because I think the proper way to think about <code>unsafeInterleaveIO</code> is as concurrency, and in that case, it isn't very strange that the results of running it would be non-deterministic. And in that case, there's not much you can do to prove that the evaluation order is affecting results, and that you aren't simply very unlucky and always observing results that happen to correspond to evaluation order.</p>
<p>In fact, there's something I didn't tell you. I didn't use the <code>unsafeInterleaveIO</code> from base. I wrote my own. It looks like this:</p>
</pre>
<pre class="haskell">&nbsp;
unsafeInterleaveIO :: <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 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
unsafeInterleaveIO action = <span style="color: #06c; font-weight: bold;">do</span>
  iv &lt; - new
  forkIO $
    randomRIO <span style="color: green;">&#40;</span><span style="color: red;">1</span>,<span style="color: red;">5</span><span style="color: green;">&#41;</span> &gt;&gt;= threadDelay . <span style="color: green;">&#40;</span>*<span style="color: red;">1000</span><span style="color: green;">&#41;</span> &gt;&gt;
    action &gt;&gt;= write iv
  <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:read"><span style="font-weight: bold;">read</span></a> $ iv
&nbsp;</pre>
<p><code>iv</code> is an <code>IVar</code> (I used <a href="https://hackage.haskell.org/package/ivar-simple">ivar-simple</a>). The pertinent operations on them are:</p>
<pre class="haskell">&nbsp;
new :: <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>IVar a<span style="color: green;">&#41;</span>
write :: IVar a -&gt; a -&gt; <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: green;">&#41;</span>
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:read"><span style="font-weight: bold;">read</span></a> :: IVar a -&gt; a
&nbsp;</pre>
<p><code>new</code> creates an empty <code>IVar</code>, and we can <code>write</code> to one only once; trying to write a second time will throw an exception. But this is no problem for me, because I obviously only attempt to write once. <code>read</code> will block until its argument is actually is set, and since that can only happen once, it is considered safe for <code>read</code> to not require <code>IO</code>. [1]</p>
<p>Using this and <code>forkIO</code>, one can easily write something like <code>unsafeInterleaveIO</code>, which accepts an <code>IO a</code> argument and yields an <code>IO a</code> whose result is guaranteed to be the result of running the argument at some time in the future. The only difference is that the real <code>unsafeInterleaveIO</code> schedules things just in time, whereas mine schedules them in a relatively random order (I'll admit I had to try a few times before I got the 'expected' lazy IO answer).</p>
<p>But, we could even take this to be the specification of interleaving. It runs <code>IO</code> actions concurrently, and you will be fine as long as you aren't attempting to depend on the exact scheduling order (or whether things get scheduled at all in some cases).</p>
<p>In fact, thinking of lazy I/O as concurrency turns most spooky examples into threading problems that I would expect most people to consider rather basic. For instance:</p>
<ul>
<li>Don't pass a handle to another thread and close it in the original.</li>
<li>Don't fork more file-reading threads than you have file descriptors.</li>
<li>Don't fork threads to handle files if you're concerned about the files being closed deterministically.</li>
<li>Don't read from the same handle in multiple threads (unless you don't care about each thread seeing a random subsequence of the stream).</li>
</ul>
<p>And of course, the original example in this article is just non-determinism introduced by concurrency, but not of a sort that requires fundamentally different explanation than fork. The main pitfall, in my biased opinion, is that the scheduling for interleaving is explained in a way that encourages people to try to guess exactly what it will do. But the presumption of purity (and the reordering GHC actually does based on it) actually means that you cannot assume that much more about the scheduling than you can about my scheduler, at least in general.</p>
<p>This isn't to suggest that lazy I/O is appropriate for every situation. Sometimes the above advice means that it is not appropriate to use concurrency. However, in my opinion, people are over eager to ban lazy I/O even for simple uses where it is the nicest solution, and justify it based on the 'evil' and 'confusing' ascriptions. But, personally, I don't think this is justified, unless one does the same for pretty much all concurrency.</p>
<p>I suppose the only (leading) question left to ask is which should be declared unsafe, fork or ivars, since together they allow you to construct a(n even less deterministic) <code>unsafeInterleaveIO</code>?</p>
<p>[1] Note that there are other implementations of <code>IVar</code>. I'd expect the most popular to be in <a href="https://hackage.haskell.org/package/monad-par">monad-par</a> by Simon Marlow. That allows one to construct an operation like <code>read</code>, but it is actually <em>less</em> deterministic in my construction, because it seems that it will not block unless perhaps you write and read within a single 'transaction,' so to speak.</p>
<p>In fact, this actually breaks referential transparency in conjunction with <code>forkIO</code>:</p>
<pre class="haskell">&nbsp;
deref = runPar . get
&nbsp;
randomDelay = randomRIO <span style="color: green;">&#40;</span><span style="color: red;">1</span>,<span style="color: red;">10</span><span style="color: green;">&#41;</span> &gt;&gt;= threadDelay . <span style="color: green;">&#40;</span><span style="color: red;">1000</span>*<span style="color: green;">&#41;</span>
&nbsp;
myHandle m = m `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:catch"><span style="font-weight: bold;">catch</span></a>` \<span style="color: green;">&#40;</span>_ :: SomeExpression<span style="color: green;">&#41;</span> -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:putStrLn"><span style="font-weight: bold;">putStrLn</span></a> <span style="color: #3c7331;">&quot;Bombed&quot;</span>
&nbsp;
mySpawn :: <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 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>IVar a<span style="color: green;">&#41;</span>
mySpawn action = <span style="color: #06c; font-weight: bold;">do</span>
  iv &lt; - runParIO new
  forkIO $ randomDelay &gt;&gt; action &gt;&gt;= runParIO . put_ iv
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:return"><span style="font-weight: bold;">return</span></a> iv
&nbsp;
main = <span style="color: #06c; font-weight: bold;">do</span>
  iv &lt; - mySpawn <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> <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;">&#41;</span>
  myHandle . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:print"><span style="font-weight: bold;">print</span></a> $ deref iv
  randomDelay
  myHandle . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:print"><span style="font-weight: bold;">print</span></a> $ deref iv
&nbsp;</pre>
<p>Sometimes this will print "Bombed" twice, and sometimes it will print "Bombed" followed by "True". The latter will never happen if we factor out the <code>deref iv</code> however. The blocking behavior is essential to <code>deref</code> maintaining referential transparency, and it seems like monad-par only blocks within a single <code>runPar</code>, not across multiples. Using ivar-simple in this example always results in "True" being printed twice.</p>
<p>It is also actually possible for <code>unsafeInterleaveIO</code> to break referential transparency if it is implemented incorrectly (or if the optimizer mucks with the internals in some bad way). But I haven't seen an example that couldn't be considered a bug in the implementation rather than some fundamental misbehavior. And my reference implementation here (with a suboptimal scheduler) suggests that there is no break that isn't just a bug.</pre>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2015/on-the-unsafety-of-interleaved-io/feed/</wfw:commentRss>
		<slash:comments>474</slash:comments>
		</item>
		<item>
		<title>Categories of Structures in Haskell</title>
		<link>http://comonad.com/reader/2015/categories-of-structures-in-haskell/</link>
		<comments>http://comonad.com/reader/2015/categories-of-structures-in-haskell/#comments</comments>
		<pubDate>Tue, 26 May 2015 01:32:49 +0000</pubDate>
		<dc:creator>Dan Doel</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Data Structures]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Kan Extensions]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Type Hackery]]></category>
		<category><![CDATA[Uncategorized]]></category>

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

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

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

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

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

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

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

		<guid isPermaLink="false">http://comonad.com/reader/?p=956</guid>
		<description><![CDATA[Emil Axelsson and Koen Claessen wrote a functional pearl last year about Using Circular Programs for Higher-Order Syntax.
About 6 months ago I had an opportunity to play with this approach in earnest, and realized we can speed it up a great deal. This has kept coming up in conversation ever since, so I've decided to [...]]]></description>
			<content:encoded><![CDATA[<p>Emil Axelsson and Koen Claessen wrote a functional pearl last year about <a href="http://www.cse.chalmers.se/~emax/documents/axelsson2013using.pdf">Using Circular Programs for Higher-Order Syntax</a>.</p>
<p>About 6 months ago I had an opportunity to play with this approach in earnest, and realized we can speed it up a great deal. This has kept coming up in conversation ever since, so I've decided to write up an article here.</p>
<p>In my <a href="http://hackage.haskell.org/package/bound">bound</a> library I exploit the fact that monads are about substitution to make a monad transformer that manages substitution for me.</p>
<p>Here I'm going to take a more coupled approach.</p>
<p>To have a type system with enough complexity to be worth examining, I'll adapt Dan Doel's <a href="http://hub.darcs.net/dolio/upts">UPTS</a>, which is a pure type system with universe polymorphism. I won't finish the implementation here, but from where we get it should be obvious how to finish the job.</p>
<p><span id="more-956"></span></p>
<p>Unlike Axelsson and Claessen I'm not going to bother to abstract over my name representation.</p>
<p>To avoid losing the original name from the source, we'll just track names as strings with an integer counting the number of times it has been 'primed'. The name is purely for expository purposes, the real variable identifier is the number. We'll follow the Axelsson and Claessen convention of having the identifier assigned to each binder be larger than any one bound inside of it. If you don't need he original source names you can cull them from the representation, but they can be useful if you are representing a syntax tree for something you parsed and/or that you plan to pretty print later.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Name = Name <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:Int"><span style="background-color: #efefbf; font-weight: bold;">Int</span></a>
   <span style="color: #06c; font-weight: bold;">deriving</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Read"><span style="background-color: #efefbf; font-weight: bold;">Read</span></a><span style="color: green;">&#41;</span>
&nbsp;
hint :: Name -&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>
hint <span style="color: green;">&#40;</span>Name n _<span style="color: green;">&#41;</span> = n
&nbsp;
nameId :: Name -&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>
nameId <span style="color: green;">&#40;</span>Name _ i<span style="color: green;">&#41;</span> = i
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Eq"><span style="background-color: #efefbf; font-weight: bold;">Eq</span></a> Name <span style="color: #06c; font-weight: bold;">where</span>
  <span style="color: green;">&#40;</span>==<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>==<span style="color: green;">&#41;</span> `on` nameId
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Ord"><span style="background-color: #efefbf; font-weight: bold;">Ord</span></a> Name <span style="color: #06c; font-weight: bold;">where</span>
  <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:compare"><span style="font-weight: bold;">compare</span></a> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:compare"><span style="font-weight: bold;">compare</span></a> `on` nameId
&nbsp;
prime :: <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> -&gt; Name
prime n i = Name n <span style="color: green;">&#40;</span>i + <span style="color: red;">1</span><span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>So what is the language I want to work with?</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">type</span> Level = <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>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Constant
  = Level
  | LevelLiteral <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Level
  | Omega
  <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:Eq"><span style="background-color: #efefbf; font-weight: bold;">Eq</span></a>,<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 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 href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Read"><span style="background-color: #efefbf; font-weight: bold;">Read</span></a>,Typeable<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Term a
  = Free a
  | Bound <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Name
  | Constant !Constant
  | Term a :+ <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Level
  | Max  <span style="color: green;">&#91;</span>Term a<span style="color: green;">&#93;</span>
  | Type !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Lam   <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Name !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Pi    <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Name !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Sigma <span style="color: #5d478b; font-style: italic;">{-# UNPACK #-}</span> !Name !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | App !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Fst !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Snd !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span>
  | Pair !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> !<span style="color: green;">&#40;</span>Term a<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:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a>,<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Read"><span style="background-color: #efefbf; font-weight: bold;">Read</span></a>,<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 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 href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a>,Foldable,Traversable,Typeable<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>That is perhaps a bit paranoid about remaining strict, but it seemed like a good idea at the time.</p>
<p>We can define capture avoiding substitution on terms:</p>
<pre class="haskell">&nbsp;
subst :: <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 =&gt; a -&gt; Term a -&gt; Term a -&gt; Term a
subst a x y = y &gt;&gt;= \a' -&gt;
  <span style="color: #06c; font-weight: bold;">if</span> a == a'
    <span style="color: #06c; font-weight: bold;">then</span> x
    <span style="color: #06c; font-weight: bold;">else</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'
&nbsp;</pre>
<p>Now we finally need to implement Axelsson and Claessen's circular programming trick. Here we'll abstract over terms that allow us to find the highest bound value within them:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Bindable t <span style="color: #06c; font-weight: bold;">where</span>
  bound :: t -&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>
&nbsp;</pre>
<p>and instantiate it for our <code>Term</code> type</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Bindable <span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
  bound Free<span style="color: green;">&#123;</span><span style="color: green;">&#125;</span>        = <span style="color: red;">0</span>
  bound Bound<span style="color: green;">&#123;</span><span style="color: green;">&#125;</span>       = <span style="color: red;">0</span> <span style="color: #5d478b; font-style: italic;">-- intentional!</span>
  bound Constant<span style="color: green;">&#123;</span><span style="color: green;">&#125;</span>    = <span style="color: red;">0</span>
  bound <span style="color: green;">&#40;</span>a :+ _<span style="color: green;">&#41;</span>      = bound a
  bound <span style="color: green;">&#40;</span>Max xs<span style="color: green;">&#41;</span>      = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:foldr"><span style="font-weight: bold;">foldr</span></a> <span style="color: green;">&#40;</span>\a r -&gt; bound a `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` r<span style="color: green;">&#41;</span> <span style="color: red;">0</span> xs
  bound <span style="color: green;">&#40;</span>Type t<span style="color: green;">&#41;</span>      = bound t
  bound <span style="color: green;">&#40;</span>Lam b t _<span style="color: green;">&#41;</span>   = nameId b `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` bound t
  bound <span style="color: green;">&#40;</span>Pi b t _<span style="color: green;">&#41;</span>    = nameId b `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` bound t
  bound <span style="color: green;">&#40;</span>Sigma b t _<span style="color: green;">&#41;</span> = nameId b `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` bound t
  bound <span style="color: green;">&#40;</span>App x y<span style="color: green;">&#41;</span>     = bound x `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>`  bound y
  bound <span style="color: green;">&#40;</span>Fst t<span style="color: green;">&#41;</span>       = bound t
  bound <span style="color: green;">&#40;</span>Snd t<span style="color: green;">&#41;</span>       = bound t
  bound <span style="color: green;">&#40;</span>Pair t x y<span style="color: green;">&#41;</span>  = bound t `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` bound x `<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:max"><span style="font-weight: bold;">max</span></a>` bound y
&nbsp;</pre>
<p>As in the original pearl we avoid traversing into the body of the binders, hence the _'s in the code above.</p>
<p>Now we can abstract over the pattern used to create a binder in the functional pearl, since we have multiple binder types in this syntax tree, and the code would get repetitive.</p>
<pre class="haskell">&nbsp;
binder :: Bindable t =&gt;
  <span style="color: green;">&#40;</span>Name -&gt; t<span style="color: green;">&#41;</span> -&gt;
  <span style="color: green;">&#40;</span>Name -&gt; t -&gt; r<span style="color: green;">&#41;</span> -&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; <span style="color: green;">&#40;</span>t -&gt; t<span style="color: green;">&#41;</span> -&gt; r
binder bd c n e = c b body <span style="color: #06c; font-weight: bold;">where</span>
  body = e <span style="color: green;">&#40;</span>bd b<span style="color: green;">&#41;</span>
  b = prime n <span style="color: green;">&#40;</span>bound body<span style="color: green;">&#41;</span>
&nbsp;
lam, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:pi"><span style="font-weight: bold;">pi</span></a>, sigma :: <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; Term a -&gt; <span style="color: green;">&#40;</span>Term a -&gt; Term a<span style="color: green;">&#41;</span> -&gt; Term a
lam s t   = binder Bound <span style="color: green;">&#40;</span>`Lam` t<span style="color: green;">&#41;</span> s
<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:pi"><span style="font-weight: bold;">pi</span></a> s t    = binder Bound <span style="color: green;">&#40;</span>`Pi` t<span style="color: green;">&#41;</span> s
sigma s t = binder Bound <span style="color: green;">&#40;</span>`Sigma` t<span style="color: green;">&#41;</span> s
&nbsp;</pre>
<p>We may not always want to give names to the variables we capture, so let's define:</p>
<pre>
lam_, pi_, sigma_ :: Term a -> (Term a -> Term a) -> Term a
lam_   = lam "_"
pi_    = pi "_"
sigma_ = sigma "_"
</pre>
<p>Now, here's the interesting part. The problem with Axelsson and Claessen's original trick is that every substitution is being handled separately. This means that if you were to write a monad for doing substitution with it, it'd actually be quite slow. You have to walk the syntax tree over and over and over.</p>
<p>We can fuse these together by making a single pass:</p>
<pre class="haskell">&nbsp;
instantiate :: Name -&gt; t -&gt; IntMap t -&gt; IntMap t
instantiate = IntMap.insert . nameId
&nbsp;
rebind :: IntMap <span style="color: green;">&#40;</span>Term b<span style="color: green;">&#41;</span> -&gt; Term a -&gt; <span style="color: green;">&#40;</span>a -&gt; Term b<span style="color: green;">&#41;</span> -&gt; Term b
rebind env xs0 f = go xs0 <span style="color: #06c; font-weight: bold;">where</span>
  go = \<span style="color: #06c; font-weight: bold;">case</span>
    Free a       -&gt; f a
    Bound b      -&gt; env IntMap.! nameId b
    Constant c   -&gt; Constant c
    m :+ n       -&gt; go m :+ n
    Type t       -&gt; Type <span style="color: green;">&#40;</span>go t<span style="color: green;">&#41;</span>
    Max xs       -&gt; Max <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> go xs<span style="color: green;">&#41;</span>
    Lam b t e    -&gt; lam   <span style="color: green;">&#40;</span>hint b<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go t<span style="color: green;">&#41;</span> $ \v -&gt;
      rebind <span style="color: green;">&#40;</span>instantiate b v env<span style="color: green;">&#41;</span> e f
    Pi b t e     -&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:pi"><span style="font-weight: bold;">pi</span></a>    <span style="color: green;">&#40;</span>hint b<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go t<span style="color: green;">&#41;</span> $ \v -&gt;
      rebind <span style="color: green;">&#40;</span>instantiate b v env<span style="color: green;">&#41;</span> e f
    Sigma b t e  -&gt; sigma <span style="color: green;">&#40;</span>hint b<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go t<span style="color: green;">&#41;</span> $ \v -&gt;
      rebind <span style="color: green;">&#40;</span>instantiate b v env<span style="color: green;">&#41;</span> e f
    App x y      -&gt; App <span style="color: green;">&#40;</span>go x<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go y<span style="color: green;">&#41;</span>
    Fst x        -&gt; Fst <span style="color: green;">&#40;</span>go x<span style="color: green;">&#41;</span>
    Snd x        -&gt; Snd <span style="color: green;">&#40;</span>go x<span style="color: green;">&#41;</span>
    Pair t x y   -&gt; Pair <span style="color: green;">&#40;</span>go t<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go x<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>go y<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Note that the <code>Lam</code>, <code>Pi</code> and <code>Sigma</code> cases just extend the current environment.</p>
<p>With that now we can upgrade the pearl's encoding to allow for an actual Monad in the same sense as <code>bound</code>.</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Applicative Term <span style="color: #06c; font-weight: bold;">where</span>
  pure = Free
  <span style="color: green;">&#40;</span>&lt; *&gt;<span style="color: green;">&#41;</span> = ap
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a> Term <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> = Free
  <span style="color: green;">&#40;</span>&gt;&gt;=<span style="color: green;">&#41;</span> = rebind IntMap.empty
&nbsp;</pre>
<p>To show that we can work with this syntax tree representation, let's write an evaluator from it to weak head normal form:</p>
<p>First we'll need some helpers:</p>
<pre class="haskell">&nbsp;
apply :: Term a -&gt; <span style="color: green;">&#91;</span>Term a<span style="color: green;">&#93;</span> -&gt; Term a
apply = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:foldl"><span style="font-weight: bold;">foldl</span></a> App
&nbsp;
rwhnf :: IntMap <span style="color: green;">&#40;</span>Term a<span style="color: green;">&#41;</span> -&gt;
  <span style="color: green;">&#91;</span>Term a<span style="color: green;">&#93;</span> -&gt; Term a -&gt; Term a
rwhnf env stk     <span style="color: green;">&#40;</span>App f x<span style="color: green;">&#41;</span>
  = rwhnf env <span style="color: green;">&#40;</span>rebind env x Free:stk<span style="color: green;">&#41;</span> f
rwhnf env <span style="color: green;">&#40;</span>x:stk<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>Lam b _ e<span style="color: green;">&#41;</span>
  = rwhnf <span style="color: green;">&#40;</span>instantiate b x env<span style="color: green;">&#41;</span> stk e
rwhnf env stk <span style="color: green;">&#40;</span>Fst e<span style="color: green;">&#41;</span>
  = <span style="color: #06c; font-weight: bold;">case</span> rwhnf env <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> e <span style="color: #06c; font-weight: bold;">of</span>
  Pair _ e' _ -&gt; rwhnf env stk e'
  e'          -&gt; Fst e'
rwhnf env stk <span style="color: green;">&#40;</span>Snd e<span style="color: green;">&#41;</span>
  = <span style="color: #06c; font-weight: bold;">case</span> rwhnf env <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span> e <span style="color: #06c; font-weight: bold;">of</span>
  Pair _ _ e' -&gt; rwhnf env stk e'
  e'          -&gt; Snd e'
rwhnf env stk e
  = apply <span style="color: green;">&#40;</span>rebind env e Free<span style="color: green;">&#41;</span> stk
&nbsp;</pre>
<p>Then we can start off the <code>whnf</code> by calling our helper with an initial starting environment:</p>
<pre class="haskell">&nbsp;
whnf :: Term a -&gt; Term a
whnf = rwhnf IntMap.empty <span style="color: green;">&#91;</span><span style="color: green;">&#93;</span>
&nbsp;</pre>
<p>So what have we given up? Well, <code>bound</code> automatically lets you compare terms for alpha equivalence by quotienting out the placement of "F" terms in the syntax tree. Here we have a problem in that the identifiers we get assigned aren't necessarily canonical.</p>
<p>But we can get the same identifiers out by just using the monad above:</p>
<pre class="haskell">&nbsp;
alphaEq :: <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 =&gt; Term a -&gt; Term 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>
alphaEq = <span style="color: green;">&#40;</span>==<span style="color: green;">&#41;</span> `on` liftM <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>It makes me a bit uncomfortable that our monad is only up to alpha equivalence and that <code>liftM</code> swaps out the identifiers used throughout the entire syntax tree, and we've also lost the ironclad protection against exotic terms.</p>
<p>But overall, this is a much faster version of Axelsson and Claessen's trick and it can be used as a drop-in replacement for something like <code>bound</code> in many cases, and unlike bound, it lets you use HOAS-style syntax for constructing <code>lam</code>, <code>pi</code> and <code>sigma</code> terms.</p>
<p>With pattern synonyms you can prevent the user from doing bad things as well. Once 7.10 ships you'd be able to use a bidirectional pattern synonym for <code>Pi</code>, <code>Sigma</code> and <code>Lam</code> to hide the real constructors behind. I'm not yet sure of the "best practices" in this area.</p>
<p>Here's the code all in one place:</p>
<p>[<a href='http://comonad.com/reader/wp-content/uploads/2014/12/Circular.hs'>Download Circular.hs</a>]</p>
<p>Happy Holidays,<br />
-Edward</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2014/fast-circular-substitution/feed/</wfw:commentRss>
		<slash:comments>48</slash:comments>
		</item>
	</channel>
</rss>
