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

<channel>
	<title>The Comonad.Reader &#187; Type Theory</title>
	<atom:link href="http://comonad.com/reader/category/type-theory/feed/" rel="self" type="application/rss+xml" />
	<link>http://comonad.com/reader</link>
	<description>types, (co)monads, substructural logic</description>
	<lastBuildDate>Mon, 24 Oct 2022 17:48:27 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Adjoint Triples</title>
		<link>http://comonad.com/reader/2016/adjoint-triples/</link>
		<comments>http://comonad.com/reader/2016/adjoint-triples/#comments</comments>
		<pubDate>Thu, 14 Jan 2016 00:02:33 +0000</pubDate>
		<dc:creator>Dan Doel</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Comonads]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Logic]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Type Theory]]></category>
		<category><![CDATA[Uncategorized]]></category>

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

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

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

colim ⊣ Δ ⊣ lim

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

		<guid isPermaLink="false">http://comonad.com/reader/?p=425</guid>
		<description><![CDATA[As requested, here are the slides from Dan Doel's excellent presentation on Homotopy and Directed Type Theory from this past Monday's Boston Haskell.
]]></description>
			<content:encoded><![CDATA[<p>As requested, here are the slides from Dan Doel's excellent presentation on <a href='http://comonad.com/reader/wp-content/uploads/2011/10/slides.pdf'>Homotopy and Directed Type Theory</a> from this past Monday's <a href="http://groups.google.com/group/bostonhaskell/browse_thread/thread/9892caece9ebb4d4">Boston Haskell</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2011/homotopy-and-directed-type-theory-slides/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generatingfunctorology</title>
		<link>http://comonad.com/reader/2008/generatingfunctorology/</link>
		<comments>http://comonad.com/reader/2008/generatingfunctorology/#comments</comments>
		<pubDate>Wed, 14 May 2008 07:45:38 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Type Theory]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/2008/generatingfunctorology/</guid>
		<description><![CDATA[Ok, I decided to take a step back from my flawed approach in the last post and play with the idea of power series of functors from a different perspective.
I dusted off my copy of Herbert Wilf's generatingfunctionology and switched goals to try to see some well known recursive functors or species as formal power [...]]]></description>
			<content:encoded><![CDATA[<p>Ok, I decided to take a step back from my flawed approach in the <a href="http://comonad.com/reader/2008/towards-formal-power-series-for-functors">last post</a> and play with the idea of power series of functors from a different perspective.</p>
<p>I dusted off my copy of Herbert Wilf's <a href="http://www.math.upenn.edu/~wilf/DownldGF.html">generatingfunctionology</a> and switched goals to try to see some well known recursive functors or <a href="http://www.cas.mcmaster.ca/~carette/species/msfp08_species.pdf">species</a> as formal power series. It appears that we can pick a few things out about the generating functions of polynomial functors.</p>
<p>As an example:</p>
<pre class="haskell">&nbsp;
<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> x = <span style="color: red;">1</span> + x
&nbsp;</pre>
<p>Ok. We're done. Thank you very much. I'll be here all week. Try the veal... </p>
<p>For a more serious example, the formal power series for the list [x] is just a <a href="http://en.wikipedia.org/wiki/Geometric_series">geometric series</a>:</p>
<p><span id="more-58"></span></p>
<pre class="haskell">&nbsp;
<span style="color: green;">&#91;</span>x<span style="color: green;">&#93;</span> = mu y . <span style="color: red;">1</span> + x y  <span style="color: #5d478b; font-style: italic;">-- the mu here is a pleasant fiction, more below</span>
    = <span style="color: red;">1</span> + x <span style="color: green;">&#40;</span><span style="color: red;">1</span> + x <span style="color: green;">&#40;</span><span style="color: red;">1</span> + x <span style="color: green;">&#40;</span>...<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
    = <span style="color: red;">1</span> + x + x^<span style="color: red;">2</span> + x^<span style="color: red;">3</span> + ...
    = <span style="color: red;">1</span>/<span style="color: green;">&#40;</span><span style="color: red;">1</span>-x<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Given the power series of a functor, its nth coefficient * n! tells you how many distinguishable ways its constructors can house n values. If we see that a list of n values can be permuted n! ways this has some interesting possibilities for linearizing the storage of some functors. The list case is boring, we can store a <i>finite</i> list of n elements by supplying the length of the array and an array of n elements, hence (among other reasons) the mu above.</p>
<p>Lets try decorated binary trees:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Tree x = Leaf | Node <span style="color: green;">&#40;</span>Tree x<span style="color: green;">&#41;</span> x <span style="color: green;">&#40;</span>Tree x<span style="color: green;">&#41;</span>
&nbsp;
Tree x = mu y. <span style="color: red;">1</span> + x * y * y
       = <span style="color: red;">1</span> + x * <span style="color: green;">&#40;</span><span style="color: red;">1</span> + x * <span style="color: green;">&#40;</span>...<span style="color: green;">&#41;</span>^<span style="color: red;">2</span><span style="color: green;">&#41;</span>^<span style="color: red;">2</span>
       = <span style="color: red;">1</span> + x + 2x^<span style="color: red;">2</span> + 5x^<span style="color: red;">3</span> + 14x^<span style="color: red;">4</span> + 42x^<span style="color: red;">5</span> + ...
&nbsp;</pre>
<p>It turns out the coefficients of our generating function are the <a href="http://en.wikipedia.org/wiki/Catalan_number">Catalan numbers</a>, <a href="http://www.research.att.com/~njas/sequences/A000108">A000108</a>, commonly denoted C(n), which happen to be well known for among other things, being the number of ways you can build a binary tree of n nodes.</p>
<p>This tells us we could store a tree by storing a number <em>n</em> of nodes it contains, an array of that many nodes, and an index 0 < = i < C(n) to tell you which particular tree you selected. Not that this is likely to be an incredibly time-efficient encoding, but you could then fmap over the tree by just fmapping over your array.</p>
<p>For a formal power series,</p>
<p><img src='http://comonad.com/latex/7b6fb5aa61c9491ac598d6ebbfcfe5c9.png' title='$f(x) = \sum_{i=0}^{\infty} a_n x^n = a_0 + a_1 x + a_2 x^2 + ... $' alt='$f(x) = \sum_{i=0}^{\infty} a_n x^n = a_0 + a_1 x + a_2 x^2 + ... $' align=absmiddle></p>
<p>its derivative is given by differentiating the series term by term:</p>
<p><img src='http://comonad.com/latex/da09bd9c7661fddc0b0d62cfd6f139b8.png' title='$f&#039;(x) = \sum_{i=1}^{\infty} n a_n x^{n - 1} = a_1 + 2 a_2 x + 3 a_3 x^2 + ...$' alt='$f&#039;(x) = \sum_{i=1}^{\infty} n a_n x^{n - 1} = a_1 + 2 a_2 x + 3 a_3 x^2 + ...$' align=absmiddle></p>
<p>Consequently we can take the derivative of a list:</p>
<p>([]') x = 1 + 2x + 3x^2 + ... = 1/(1-x)^2 = ([] :*: []) x</p>
<p>and rederive the notion that a derivative/one hole context of a list can be represented by a pair of lists.</p>
<p>If we step slightly outside of the Haskell users' comfort zone and notion of a Functor and allow other Species, we get (as noted by apfelmus the other day) that Exp a is just a bag of elements with no predetermined order.</p>
<pre class="haskell">&nbsp;
Exp x = <span style="color: red;">1</span> + x + x^<span style="color: red;">2</span>/<span style="color: red;">2</span>! + x^<span style="color: red;">3</span>/<span style="color: red;">3</span>! + ... = Bag x
&nbsp;
Since there are n! ways to order n elements <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:and"><span style="font-weight: bold;">and</span></a> Bag manages to forget that information, we can get a feeling for the meaning <span style="color: #06c; font-weight: bold;">of</span> division <span style="color: #06c; font-weight: bold;">in</span> this setting.
&nbsp;
Similarly we can define:
&lt;pre lang=<span style="color: #3c7331;">&quot;haskell&quot;</span>&gt;
Sinh x = x + x^<span style="color: red;">3</span>/<span style="color: red;">3</span>! + ... <span style="color: #5d478b; font-style: italic;">-- a Bag of some odd number of elements.</span>
Cosh x = <span style="color: red;">1</span> + x^<span style="color: red;">2</span>/<span style="color: red;">2</span>! + ... <span style="color: #5d478b; font-style: italic;">--  a Bag of some even number of elements.</span>
&nbsp;</pre>
<p>Then by construction:</p>
<pre class="haskell">&nbsp;
Exp = Cosh :+: Sinh
&nbsp;</pre>
<p>The derivative of Exp is Exp, of Cosh is Sinh, of Sinh is Cosh, all as you would expect.</p>
<p>We can handle other species as well:</p>
<pre class="haskell">&nbsp;
Cycle a = <span style="color: red;">1</span> + x^<span style="color: red;">2</span>/<span style="color: red;">2</span> + x^<span style="color: red;">3</span>/<span style="color: red;">3</span> + x^<span style="color: red;">4</span>/<span style="color: red;">4</span> + ... <span style="color: #5d478b; font-style: italic;">-- cycles</span>
Cycle_n a = x^n/n <span style="color: #5d478b; font-style: italic;">-- cycles of n elements</span>
Bag_n a = x^n/n!  <span style="color: #5d478b; font-style: italic;">-- bags of n elements</span>
&nbsp;</pre>
<p>That said, there seem to be some problems, not every functor is well behaved in this way. Lets take for instance the type of natural numbers given by the functor:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Nat a = S <span style="color: green;">&#40;</span>Nat a<span style="color: green;">&#41;</span> | Z
&nbsp;</pre>
<p>Then the recurrence blows up, the coefficient for 0 is <img src='http://comonad.com/latex/05337ee7dbe333d118d371bc95c44f7a.png' title='$\aleph_0$' alt='$\aleph_0$' align=absmiddle>!</p>
<p>Similarly, if we parameterized a functor on another value we have to deal with the number of cases that other value can denote.</p>
<pre class="haskell">&nbsp;
<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 x = |a| + x
<span style="color: green;">&#40;</span>a,x<span style="color: green;">&#41;</span> = |a| x
&nbsp;</pre>
<p>This is both good and bad, using the above, we can quickly establish an isomorphism between Either () and the Maybe Functor, but we blow up again for Either Integer. This gets even worse if we allow 'functors in space.' (i.e. functors that can contain functions)</p>
<p>On the other extreme, we might modify our tree example and remove the leaves, yielding infinite decorated cotrees.</p>
<pre class="haskell">&nbsp;
Tree x = nu y. x * y * y
       = x * <span style="color: green;">&#40;</span>x * <span style="color: green;">&#40;</span>...<span style="color: green;">&#41;</span>^<span style="color: red;">2</span><span style="color: green;">&#41;</span>^<span style="color: red;">2</span>
       = <span style="color: red;">0</span> + 0x + 0x^<span style="color: red;">2</span> + 0x^<span style="color: red;">3</span> + ...
&nbsp;</pre>
<p>Then a_n = 0 for all n in the natural numbers, so you can't use the coefficients of the generating function to tell you about the behavior of an infinite structure! It would appear that the generating function of a functor does not capture what happens in the greatest fixed point case, so we can only use generating functions to describe the behavior of data defined with mu, not in general codata defined by nu.</p>
<p>The Bags and Cycles above are nice examples, but if we wanted to rule out the non-polynomial Functors (from the Haskell perspective) in the above then we can simply limit ourselves to <a href="http://en.wikipedia.org/wiki/Generating_function#Ordinary_generating_function_2">ordinary generating functions</a> with natural number coefficients, that is to say generating functions of the form:</p>
<p><img src='http://comonad.com/latex/7b6fb5aa61c9491ac598d6ebbfcfe5c9.png' title='$f(x) = \sum_{i=0}^{\infty} a_n x^n = a_0 + a_1 x + a_2 x^2 + ... $' alt='$f(x) = \sum_{i=0}^{\infty} a_n x^n = a_0 + a_1 x + a_2 x^2 + ... $' align=absmiddle></p>
<p>To choose to admit bags,  cycles and other species etc. then you need merely also permit <a href="http://en.wikipedia.org/wiki/Generating_function#Exponential_generating_function_2">exponential generating functions</a> with natural coefficients, that is to say, generating functions of the form:</p>
<p><img src='http://comonad.com/latex/c30686528791fe1a38720bf5006b81a3.png' title='$f(x) = \sum_{i=0}^{\infty} a_n x^n / n! = a_0 + a_1 x / 1! + a_2 x^2 / 2! + ... $' alt='$f(x) = \sum_{i=0}^{\infty} a_n x^n / n! = a_0 + a_1 x / 1! + a_2 x^2 / 2! + ... $' align=absmiddle></p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2008/generatingfunctorology/feed/</wfw:commentRss>
		<slash:comments>59</slash:comments>
		</item>
		<item>
		<title>Towards Formal Power Series for Functors</title>
		<link>http://comonad.com/reader/2008/towards-formal-power-series-for-functors/</link>
		<comments>http://comonad.com/reader/2008/towards-formal-power-series-for-functors/#comments</comments>
		<pubDate>Tue, 13 May 2008 09:22:19 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Category Theory]]></category>
		<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Mathematics]]></category>
		<category><![CDATA[Type Theory]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/2008/towards-formal-power-series-for-functors/</guid>
		<description><![CDATA[The post below will only compile on a version of GHC >= 6.9, since it uses type families.

There has been a lot of posting recently about automatic differentiation in Haskell, and I wanted to try the same thing with functors in the spirit of Conor McBride's Clowns to the Left of me, Jokers to the [...]]]></description>
			<content:encoded><![CDATA[<p>The post below will only compile on a version of GHC >= 6.9, since it uses type families.</p>
<p><span id="more-57"></span></p>
<p>There has been a lot of posting recently about automatic differentiation in Haskell, and I wanted to try the same thing with functors in the spirit of Conor McBride's <a href="http://strictlypositive.org/CJ.pdf">Clowns to the Left of me, Jokers to the Right</a> and <a href="http://citeseer.ist.psu.edu/472190.html">The derivative of a regular type is its type of one hole contexts</a>, figuring that a Power Series could fully generalize Christophe Poucet's <a href="http://notvincenz.blogspot.com/2007/07/higher-order-zippers.html">Higher Order Zippers</a>, and might provide me with a neat extension to the zipper comonadic automata I've been aluding to recently.</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-# OPTIONS -fglasgow-exts -fallow-undecidable-instances -fallow-overlapping-instances #-}</span>
<span style="color: #06c; font-weight: bold;">module</span> Derivatives <span style="color: #06c; font-weight: bold;">where</span>
<span style="color: #06c; font-weight: bold;">import</span> Control.<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Monad"><span style="background-color: #efefbf; font-weight: bold;">Monad</span></a>.Identity
<span style="color: #06c; font-weight: bold;">import</span> Control.Arrow <span style="color: green;">&#40;</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>,<span style="color: green;">&#40;</span>&amp;&amp;&amp;<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">import</span> Data.Monoid
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">9</span> :.:
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">7</span> :*:
<span style="color: #06c; font-weight: bold;">infixl</span> <span style="color: red;">6</span> :+:
&nbsp;</pre>
<p>To avoid importing <a href="http://hackage.haskell.org/cgi-bin/hackage-scripts/package/category-extras-0.44.4">category-extras</a> and keep this post self-contained (modulo GHC 6.9!), we'll define some preliminaries such as Bifunctors:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> Bifunctor f <span style="color: #06c; font-weight: bold;">where</span>
	bimap :: <span style="color: green;">&#40;</span>a -&gt; c<span style="color: green;">&#41;</span> -&gt; <span style="color: green;">&#40;</span>b -&gt; d<span style="color: green;">&#41;</span> -&gt; f a b -&gt; f c d
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Bifunctor <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	bimap f g ~<span style="color: green;">&#40;</span>a,b<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>f a, g b<span style="color: green;">&#41;</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Bifunctor <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a> <span style="color: #06c; font-weight: bold;">where</span>
	bimap f _ <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Left"><span style="font-weight: bold;">Left</span></a> a<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Left"><span style="font-weight: bold;">Left</span></a> <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span>
	bimap _ g <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a> b<span style="color: green;">&#41;</span> = <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:Right"><span style="font-weight: bold;">Right</span></a> <span style="color: green;">&#40;</span>g b<span style="color: green;">&#41;</span>
&nbsp;</pre>
<p>Constant functors:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">data</span> Void
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a> Void <span style="color: #06c; font-weight: bold;">where</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:show"><span style="font-weight: bold;">show</span></a> _ = <span style="color: #3c7331;">&quot;Void&quot;</span>
<span style="color: #06c; font-weight: bold;">newtype</span> Const k a = Const <span style="color: green;">&#123;</span> runConst :: k <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:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a><span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">type</span> Zero = Const Void
<span style="color: #06c; font-weight: bold;">type</span> One = Const <span style="color: green;">&#40;</span><span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Const k<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f = Const . runConst
&nbsp;</pre>
<p>and functor products and coproducts:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> Lift p f g a = Lift <span style="color: green;">&#123;</span> runLift ::  p <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
<span style="color: #06c; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:+:<span style="color: green;">&#41;</span> = Lift <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Either"><span style="background-color: #efefbf; font-weight: bold;">Either</span></a>
<span style="color: #06c; font-weight: bold;">type</span> <span style="color: green;">&#40;</span>:*:<span style="color: green;">&#41;</span> = Lift <span style="color: green;">&#40;</span>,<span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">instance</span> <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a> <span style="color: green;">&#40;</span>p <span style="color: green;">&#40;</span>f a<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span>g a<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a> <span style="color: green;">&#40;</span>Lift p f g a<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:show"><span style="font-weight: bold;">show</span></a> <span style="color: green;">&#40;</span>Lift x<span style="color: green;">&#41;</span> = <span style="color: #3c7331;">&quot;(Lift (&quot;</span> ++ <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:show"><span style="font-weight: bold;">show</span></a> x ++ <span style="color: #3c7331;">&quot;))&quot;</span>
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Bifunctor p, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> g<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>Lift p f g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f = Lift . bimap <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> . runLift
&nbsp;</pre>
<p>and finally functor composition</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> <span style="color: green;">&#40;</span>f :.: g<span style="color: green;">&#41;</span> a = Comp <span style="color: green;">&#123;</span> runComp :: f <span style="color: green;">&#40;</span>g 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:Show"><span style="background-color: #efefbf; font-weight: bold;">Show</span></a><span style="color: green;">&#41;</span>
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> g<span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>f :.: g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f = Comp . <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> . runComp
&nbsp;</pre>
<p>So then, an ideal type for repeated differentiation would look something like the following, for some definition of D.</p>
<p>[Edit: sigfpe pointed out, quite rightly, that this is just repeated differentiation, and apfelmus pointed out that it not a power series, because I have no division!]</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">newtype</span> AD f a  = AD <span style="color: green;">&#123;</span> runAD :: <span style="color: green;">&#40;</span>f a,  AD <span style="color: green;">&#40;</span>D f<span style="color: green;">&#41;</span> a<span style="color: green;">&#41;</span> <span style="color: green;">&#125;</span>
&nbsp;</pre>
<p>As a first crack at D, you might be tempted to just go with a type family:</p>
<pre class="haskell">&nbsp;
<span style="color: #5d478b; font-style: italic;">{-
type family D (f :: * -&gt; *) :: * -&gt; *
type instance D Identity = One
type instance D (Const k) = Zero
type instance D (f :+: g) = D f :+: D g
type instance D (f :*: g) = f :*: D g :+: D f :*: g
type instance D (f :.: g) = (D f :.: g) :*: D g
-}</span>
&nbsp;</pre>
<p>This could take you pretty far, but unfortunately doesn't adequately provide you with any constraints on the type so that we can treat AD f as a functor.</p>
<p>So, we'll go with:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">class</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>D f<span style="color: green;">&#41;</span>, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> f<span style="color: green;">&#41;</span> =&gt; Derivable <span style="color: green;">&#40;</span>f :: * -&gt; *<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D f :: * -&gt; *
&nbsp;</pre>
<p>and cherry pick the instances necessary to handle the above cases:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Derivable Identity <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D Identity = One
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> Derivable <span style="color: green;">&#40;</span>Const k<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D <span style="color: green;">&#40;</span>Const k<span style="color: green;">&#41;</span> = Zero
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Derivable f, Derivable g<span style="color: green;">&#41;</span> =&gt; Derivable <span style="color: green;">&#40;</span>f :+: g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D <span style="color: green;">&#40;</span>f :+: g<span style="color: green;">&#41;</span> = D f :+: D g 
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Derivable f, Derivable g<span style="color: green;">&#41;</span> =&gt; Derivable <span style="color: green;">&#40;</span>f :*: g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D <span style="color: green;">&#40;</span>f :*: g<span style="color: green;">&#41;</span> = f :*: D g :+: D f :*: g
&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Derivable f, Derivable g<span style="color: green;">&#41;</span> =&gt; Derivable <span style="color: green;">&#40;</span>f :.: g<span style="color: green;">&#41;</span> <span style="color: #06c; font-weight: bold;">where</span>
	<span style="color: #06c; font-weight: bold;">type</span> D <span style="color: green;">&#40;</span>f :.: g<span style="color: green;">&#41;</span> = <span style="color: green;">&#40;</span>D f :.: g<span style="color: green;">&#41;</span> :*: D g
&nbsp;</pre>
<p>With those instances in hand, we can define the definition of a Functor for the automatic differentiation of a Functor built out of these primitives:</p>
<pre class="haskell">&nbsp;
<span style="color: #06c; font-weight: bold;">instance</span> <span style="color: green;">&#40;</span>Derivable f, <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>AD <span style="color: green;">&#40;</span>D f<span style="color: green;">&#41;</span><span style="color: green;">&#41;</span><span style="color: green;">&#41;</span> =&gt; <a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#t:Functor"><span style="background-color: #efefbf; font-weight: bold;">Functor</span></a> <span style="color: green;">&#40;</span>AD 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 = Power . bimap <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> <span style="color: green;">&#40;</span><a href="http://haskell.org/ghc/docs/latest/html/libraries/base/Prelude.html#v:fmap"><span style="font-weight: bold;">fmap</span></a> f<span style="color: green;">&#41;</span> . runPower
&nbsp;</pre>
<p>Unfortunately, here is where I run out of steam, because any attempt to actually use the construct in question blows the context stack because the recursion for Functor (AD f) isn't well founded and my attempts to force it to be so through overlapping-instances have thus-far failed.</p>
<p>Thoughts?</p>
<p>[<a href="http://comonad.com/haskell/Derivatives.hs">Source Code</a>]</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2008/towards-formal-power-series-for-functors/feed/</wfw:commentRss>
		<slash:comments>458</slash:comments>
		</item>
		<item>
		<title>Parameterized Monads in Haskell</title>
		<link>http://comonad.com/reader/2007/parameterized-monads-in-haskell/</link>
		<comments>http://comonad.com/reader/2007/parameterized-monads-in-haskell/#comments</comments>
		<pubDate>Fri, 13 Jul 2007 07:46:15 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Haskell]]></category>
		<category><![CDATA[Monads]]></category>
		<category><![CDATA[Type Theory]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/2007/parameterized-monads-in-haskell/</guid>
		<description><![CDATA[Recently Eric Kidd and Dan Piponi have used a bit of type hackery by Oleg Kiselyov and -fno-implicit-prelude to build some interesting restricted monads, like the Wadler Set and Bag monads.
There is another interesting monad variation - a parameterized monad - where the monad carries around an additional parameter at the type level such as [...]]]></description>
			<content:encoded><![CDATA[<p>Recently <a href="http://www.randomhacks.net/articles/2007/03/15/data-set-monad-haskell-macros">Eric Kidd</a> and <a href="http://sigfpe.blogspot.com/2007/06/how-to-write-tolerably-efficient.html">Dan Piponi</a> have used a bit of <a href="http://okmij.org/ftp/Haskell/types.html#restricted-datatypes">type hackery by Oleg Kiselyov</a> and -fno-implicit-prelude to build some interesting restricted monads, like the Wadler Set and Bag monads.</p>
<p>There is another interesting monad variation - a parameterized monad - where the monad carries around an additional parameter at the type level such as a type-level set of effects. One really good example of this is the separation logic monad in <a href="http://www.eecs.harvard.edu/~aleks/papers/hoarelogic/jfpsep07.pdf">Hoare Type Theory</a>. The pre- and post- conditions can be viewed as the parameter carried around on that monad. <a href="http://citeseer.ist.psu.edu/254302.html">Wadler and Thiemann</a>, <a href="type.http://citeseer.ist.psu.edu/273929.html">Jean-Christophe Filliâtre</a> and others have explore this notion for encoding effects.</p>
<p><span id="more-41"></span></p>
<p>This prompts the question of if parameterized monads can be implemented directly in Haskell. Indeed they can, but a simple version fails with the signature:</p>
<p><code type="haskell"><br />
class BadHaskell m p p' p'' | p p' -> p'' where<br />
    return :: a -> m p a<br />
    fail :: a -> m p a<br />
    (>>=) :: m p a -> (a -> m p' a) -> m p'' a<br />
</code></p>
<p>This of course runs afoul of the fact that all of the parameters are not mentioned in return, so we have to break it apart into two or three classes.</p>
<p><code type="haskell"><br />
class Return m p where<br />
    return :: a -> m p a</p>
<p>class Fail m p where<br />
    fail :: String -> m p a</p>
<p>class Bind m p p' p'' | p p' -> p'' where<br />
    (>>=) :: m p a -> (a -> m p' a) -> m p'' a<br />
</code></p>
<p>By splitting off fail, we can make it so that it is illegal to use an incomplete pattern on certain monads, a small win, but it may be useful in a later post.</p>
<p>However, there turns out to be quite some awkwardness from the perspective of type inference with this type. In particular we are used to the types of our monads being able to be inferred from the type of their results, but we lose this inference on return. Moreover, we can't just use existing monads under this syntax, we'd have to lift them into a newtype that accepted the additional parameter. </p>
<p>Ignoring the problems with existing monads, and correcting the type inference problem directly by adding fundeps doesn't help as </p>
<p><code type="haskell"><br />
class Bind m p p' p''<br />
  | p -> p' p''<br />
  , p' -> p p''<br />
  , p'' -> p p'<br />
  where<br />
    (>>=) :: m p a -> (a -> m p' a) -> m p'' a<br />
</code></p>
<p>is too restrictive and could be shown that under a strict interpretation of the laws, would never be able to be made to satisfy the monad laws except in the base case, because of the inability to construct an associative operation combining the parameters that isn't trivial.</p>
<p>As an aside, speaking of failing monad laws, it is interesting to note that the Set restricted monad actually fails a monad law given that functions in haskell need not respect equality, since <img src='http://comonad.com/latex/897b3c5aa597494b81ac92874455d7af.png' title='x = y =&gt; f x = f y' alt='x = y =&gt; f x = f y' align=absmiddle> fails to hold in general for user defined equality as used by the Set monad, as noted by Andrea Vezzosi on #haskell, the order of association can make a difference as to the result of the computation. This is arguably a minor quibble as you wouldn't be using it unless you knew the type you were going to pass around and how your functions worked on it with respect to its notion of equality.</p>
<p>Turning back to the issue of being unable to pass traditional monads into this type, we realize that having a separate m and p parameters to the type class is redundant as you can generate an equivalent notion by letting m vary.</p>
<p><code type="haskell"><br />
class Return m where<br />
    return :: a -> m a</p>
<p>class Fail m where<br />
    fail :: String -> m a</p>
<p>class Bind m m' m'' | m m' -> m'' where<br />
    (>>=) :: m a -> (a -> m' a) -> m'' a<br />
</code></p>
<p>This still has the problem that the type of return is not inferable, but now at least we can derive instances of these classes for instances of Monad. Of course, if we create a generic instance for </p>
<p><code type="haskell"><br />
import qualified Control.Monad as Old<br />
instance Old.Monad m => Bind m m m where (>>=) = (Old.>>=)<br />
...<br />
</code></p>
<p>we then run afoul of the fact that we can't define any other interesting instances because the compiler won't know which way to go with type class inference.</p>
<p>However, even without that we can import each monad in turn, and define some interesting interfaces between them:</p>
<p><code type="haskell"><br />
instance Bind Maybe [] [] where<br />
    Just a >>= f = f a<br />
    Nothing >>= _ = []</p>
<p>-- testMaybeList :: [Int] = [2,4]<br />
testMaybeList = Just 2 >>= \x -> [x*1,x*2]<br />
</code></p>
<p>Admittedly there is an <img src='http://comonad.com/latex/6595d679e306a127a3fe53268bcaddb2.png' title='n^2' alt='n^2' align=absmiddle> combinatorial explosion of combinations and not all of them have clear semantics, but we can choose to implement only the ones that have an unambiguous interpretation and leave off the rest and pay as we go, implementing them as needed. A more mature version of this might provide an interesting alternative/supplement to the MTL approach and can be viewed as a limited fragment of <a href="http://citeseer.ist.psu.edu/619712.html">Lüth and Ghani's monad composition through coproducts</a>.</p>
<p>However, we still haven't solved the return problem, but it turns out that monad laws can come to the rescue. </p>
<p>If we start to implement a number of these we notice a pattern when it comes to the Identity monad. In general we can define instances of Bind for the Identity monad for any monad presuming we can liftM, to handle the case on the right, but since liftM requires a sort of circular dependency loop, we choose to make Bind enforce the availability of fmap, allow overlapping instances, and then define:</p>
<p><code type="haskell"><br />
class (Functor m, Functor m', Functor m'') => Bind m m' m''<br />
 | m m' -> m''<br />
  where<br />
    (>>=) :: m a -> (a -> m' b) -> (m'' b)<br />
    (>>)  :: m a -> m' b -> m'' b<br />
    m >> k = m >>= const k</p>
<p>instance Functor a => Bind Identity a a where<br />
    m >>= f = f (runIdentity m)</p>
<p>instance Functor a => Bind a Identity a where<br />
    m >>= f = fmap (runIdentity . f) m</p>
<p>-- and to disambiguate between the above instances...<br />
instance Bind Identity Identity Identity where<br />
    m >>= f = f (runIdentity m)<br />
</code></p>
<p>The correctness of this is in fact enforced by the monad laws as these instances can be read as the familiar laws once you remove the noise of the Identity monad:</p>
<p><code type="haskell"><br />
     return m >>= f = f m<br />
     m >>= return . f = fmap f m<br />
     return m >>= f = f m<br />
</code></p>
<p>This gives us a single natural notion of return for all monads that we can use and still glue together via >>=:</p>
<p><code type="haskell"><br />
class Return m where<br />
    returnM :: a -> m a</p>
<p>return :: a -> Identity a<br />
return = Old.return<br />
</code></p>
<p>Now the problem is if you write a statement like <code type="haskell">return 2 >>= \x -> return (x+1)</code>, you can have the Identity type percolate out of your monad expression, even when you were expecting a ListT or State monad or something more interesting, so we need a way to transform values from the Identity monad to an arbitrary monad for use when you want its type to conform to an external signature. </p>
<p><code type="haskell"><br />
class Go n m where<br />
        go :: n a -> m a</p>
<p>instance Return a => Go Identity a where<br />
    go = returnM . runIdentity<br />
instance Go a a where<br />
    go = id<br />
</code></p>
<p>So, now we can tell our code to <code type="haskell">go (do something)</code> and it will transform any lingering Identities to whatever monadic type is inferred for the go statement in its current context.</p>
<p>This has the advantage that pure fragments in our monadic sugar can avoid carrying around the rest of the monadic plumbing, even though they use the same bind operator to string it all together.</p>
<p>We can perform similar surgery on the MonadPlus class, tearing it apart into two pieces, breaking out a canonical mzero implementation as a trivial monad that just projects everything to bottom, and having Go erase any lingering mzeros that percolate out of our expression. Rather than reproduce it here, I point to a darcs repository that I just created. You can use darcs to get <a href="http://comonad/com/haskell/monad-param">http://comonad/com/haskell/monad-param</a> or pull the package from hackage. The interesting bits are in Control.Monad.Parameterized and <a href="http://comonad.com/haskell/monad-param/dist/doc/html/Control-Monad-Parameterized.html">HTML documentation is available</a>.</p>
<p>This package re-exports the MTL and STM monads to avoid the requirement that the end user explicitly import Control.Monad.* masking off the members of Control.Monad each time and it provides some interesting mixins. </p>
<p>Caveat: It appears that GHC enforces the fact that the arguments and results of (>>=) must have a signature like</p>
<p><code type="haskell">(>>=) :: forall m a. (...) => m a -> (a -> m b) -> m b</code></p>
<p>insofar as when you use the do-sugar, your types will not be able to vary. Ideally it should be able to get by with a more liberal signature, but it seems like no one has needed it before now.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2007/parameterized-monads-in-haskell/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Overloaded Functions with Subtyping</title>
		<link>http://comonad.com/reader/2006/overloaded-functions-with-subtyping/</link>
		<comments>http://comonad.com/reader/2006/overloaded-functions-with-subtyping/#comments</comments>
		<pubDate>Wed, 01 Nov 2006 08:35:30 +0000</pubDate>
		<dc:creator>Edward Kmett</dc:creator>
				<category><![CDATA[Type Theory]]></category>

		<guid isPermaLink="false">http://comonad.com/reader/2006/overloaded-functions-with-subtyping/</guid>
		<description><![CDATA[Was reading Castagna, Ghelli, and Longo's 1995 paper on "A Calculus for Overloaded Functions with Subtyping" today and in it they have to jump through some hoops to index their '&#038;' types to keep them well behaved under &#946;-reduction.
It seems to me, at least from my back-of-the-envelope scribblings, that if you CPS transform the calculus [...]]]></description>
			<content:encoded><![CDATA[<p>Was reading Castagna, Ghelli, and Longo's 1995 paper on "<a href="http://citeseer.ist.psu.edu/125897.html">A Calculus for Overloaded Functions with Subtyping</a>" today and in it they have to jump through some hoops to index their '&' types to keep them well behaved under &beta;-reduction.</p>
<p>It seems to me, at least from my back-of-the-envelope scribblings, that if you <a href="/reader/wiki?item=CPS+transformation">CPS transform</a> the calculus before, that the main technical innovation (overloaded functions using the tighter run-time type information) remains intact, but the need for this technical trick goes away. In this case you know what the reduction will evaluate out to regardless of call-by-value or call-by-need (just bottom), and if the specification changes during evaluation it is still sound, so no need for an index.</p>
<div class="codeblock">
<p align="center"><img src='http://comonad.com/latex/63ee3379bf761ad7074f3bb895da57d5.png' title=' \inference{\Gamma \vdash M:W_1 \leq \lbrace\neg U_i\rbrace_{i\leq(n-1)} &amp; \Gamma \vdash N : W_2 \leq \neg U_n}{\Gamma \vdash (M \binampersand N) : \lbrace \neg U_i \rbrace_{i \leq n }}[$\lbrace\rbrace$-I]' alt=' \inference{\Gamma \vdash M:W_1 \leq \lbrace\neg U_i\rbrace_{i\leq(n-1)} &amp; \Gamma \vdash N : W_2 \leq \neg U_n}{\Gamma \vdash (M \binampersand N) : \lbrace \neg U_i \rbrace_{i \leq n }}[$\lbrace\rbrace$-I]' align=absmiddle></p>
<p align="center"><img src='http://comonad.com/latex/b5ad9c35b4aeb655526d34f61cc0b770.png' title=' \inference{\Gamma \vdash M : \lbrace \neg U_i \rbrace_{i \in I} &amp; \Gamma \vdash N : U &amp; U_j = \min_{i \in I} \lbrace U_i \vert U \leq U_i \rbrace } {\Gamma \vdash M \bullet N : \perp }[$\lbrace\rbrace$-E]' alt=' \inference{\Gamma \vdash M : \lbrace \neg U_i \rbrace_{i \in I} &amp; \Gamma \vdash N : U &amp; U_j = \min_{i \in I} \lbrace U_i \vert U \leq U_i \rbrace } {\Gamma \vdash M \bullet N : \perp }[$\lbrace\rbrace$-E]' align=absmiddle></p>
</div>
<p>The above then would requires explicit continuations and might interfere with rederiving tupling from the overloading mechanism alone, but seems to eliminate some of the barriers they mention to the higher order case. However, I'm not convinced it is a net win regardless, because it would require a notion of typecase.</p>
]]></content:encoded>
			<wfw:commentRss>http://comonad.com/reader/2006/overloaded-functions-with-subtyping/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
