<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>Jonathan Sterling RSS feed.</title>
        <link>http://www.jonmsterling.com</link>
        <description><![CDATA[]]></description>
        <atom:link href="http://www.jonmsterling.com/rss.xml" rel="self"
                   type="application/rss+xml" />
        <lastBuildDate>Sun, 20 Sep 2009 00:00:00 UT</lastBuildDate>
        <item>
    <title>Writing Mac OS X applications in Smalltalk</title>
    <link>http://www.jonmsterling.com/posts/2009-09-20-writing-mac-os-x-applications-in-smalltalk.html</link>
    <description><![CDATA[<p>After having seen the work on <a href="http://etoileos.com/">Etoilé</a> under GNUstep, I began to fantasize over writing applications for Mac OS X in Smalltalk. Unfortunately, all of the full Smalltalk solutions I have scene are really weird and childish (yeah, I’m looking at you, <a href="http://wiki.squeak.org/squeak/uploads/683/squeak32.png">Squeak</a>), and totally impractical for distributing applications that fit in with Mac OS (yeah, you too, <a href="http://www.pharo-project.org/pictures/48/9qjfrljb2j66j23n8m966oqpakb3u1/image_2-720.png">Pharo</a>).</p>
<p>What I really wanted was a version of Smalltalk that used the same object modal as Objective-C, like Pragmatic Smalltalk of Etoilé, or even MacRuby on Mac OS. Most of all, I wanted it to treat me like an adult: I don’t need a class browser, thank you, I’m more comfortable working with plain-old files. The persistent image construct in Smalltalk really makes me uncomfortable.</p>
<!--MORE-->

<p>Eventually, I found <a href="http://www.fscript.org/">F-Script</a>, a scripting environment for Mac OS based on Smalltalk. It is not really meant for developing full applications, but with a little work, I was able to make this work.</p>
<p>First, we will need a bare-bones Xcode project for an Objective-C application with a XIB. Remove all of the instance variables, outlets and properties from your application delegate. Before we go any further, we’ll need to create class in F-Script, which we will call <code>WindowController</code>. Create a new file <code>WindowController.st</code> in your <code>Resources</code> group. You may consider using <a href="http://www.macromates.com">TextMate</a> for editing, because there are is an <a href="http://github.com/textmate/f-script.tmbundle">F-Script bundle</a> you can use, whereas Xcode does not support highlighting of Smalltalk.</p>
<h2 id="writing-the-smalltalk-component">Writing the Smalltalk component</h2>
<p>We need to define a class and its instance variables (I apologize for the mis-coloring of some code; my highlighter isn’t built for F-Script’s dialect of Smalltalk):</p>
<script src="http://gist.github.com/419547.js?file=WindowController1.st"></script>

<p>Note that comments are made by putting double-quotes around text.</p>
<p>Now, we can start writing the instance methods for this class. As always, we start with an initializer:</p>
<script src="http://gist.github.com/419547.js?file=WindowController2.st"></script>

<p>It doesn’t appear that F-Script supports making your own symbolic constants like Ruby, so I used instance variables set in <code>-init</code> instead.</p>
<p>Next, we need to have it create and present our window. The following code will show you how some plain C constructs used in Objective-C (like Cocoa graphics structs, &amp;c.) map into F-Script:</p>
<script src="http://gist.github.com/419547.js?file=WindowController3.st"></script>

<p>At the end of <code>-loadWindow</code> we have a call to <code>windowDidLoad</code>, which is implemented as follows:</p>
<script src="http://gist.github.com/419547.js?file=WindowController4.st"></script>

<p>There were a few calls in <code>-windowDidLoad</code> to methods we need to implement. These will be a good example of the block-based control structures of Smalltalk, where <code>-ifTrue</code>, <code>-ifFalse</code> is a method:</p>
<script src="http://gist.github.com/419547.js?file=WindowController5.st"></script>

<p>Finally, we can’t forget to end our class: <code>}.</code>.</p>
<h2 id="some-notes-on-syntax">Some notes on syntax</h2>
<p>To declare local variables, we surround them in bars: <code>| localVar1 localVar2 |</code>. Note that like in Ruby, mathematical operators are really messages sent to the objects behind them.</p>
<p>Statements are ended with a period (<code>.</code>), but the semicolon (<code>;</code>) does something entirely different. In Objective-C, we might do the following:</p>
<script src="http://gist.github.com/419547.js?file=Objective-C-Syntax.m"></script>

<p>in a Smalltalk variant, we can do this instead:</p>
<script src="http://gist.github.com/419547.js?file=Smalltalk-Syntax.st"></script>



<h2 id="linking-windowcontroller-with-our-application.">Linking <code>WindowController</code> with our application.</h2>
<p>This is the last and most important part of this tutorial. We cannot use our Smalltalk code without somehow loading it from the Objective-C portion of our application.</p>
<p>F-Script includes a framework that facilitates executing blocks of F-Script code, and that is how we will combine our Smalltalk <code>WindowController</code> class with our Cocoa application. First, add <code>FScript.framework</code> to your Xcode project. Then, make sure your <code>AppDelegate.h</code> file imports it.</p>
<p>Now, in <code>-applicationDidFinishLaunching:</code>, you need to load our code into an <code>FSBlock</code>:</p>
<script src="http://gist.github.com/419547.js?file=AppDelegate.m"></script>

<p>Now, you can create an instance of <code>WindowController</code> and use it (note that you must type your instance <code>id</code>, because this sort of hackery will not allow specific typing):</p>
<script src="http://gist.github.com/419547.js?file=AppDelegate2.m"></script>

<p>The beautiful thing here is that we called several methods (<code>+alloc</code>, <code>-init</code>, and <code>-loadWindow</code>) in Objective-C from a class created in Smalltalk. All this should make a window pop up that functions as we would expect it to:</p>
<img src="http://emberapp.com/jonsterling/images/smalltalk-demo/sizes/m.png" style="width:90%" title="Demo App">
<h3 id="making-it-even-easier">Making it even easier!</h3>
<p>Of course, if you have many Smalltalk classes to load, all this loading code can be quite a pain; naturally, I wrote a <code>#define</code> directive for it:</p>
<script src="http://gist.github.com/419547.js?file=Macro.m"></script>


<h2 id="caveats">Caveats</h2>
<p>Unless you somehow encode your Smalltalk files and then decode them at runtime, the code for the Smalltalk portion of your application will be available to any user smart enough to open your application package. Also, if you use the <code>#define</code> I gave you above, you must make each <code>.st</code> file have only one class, and have that class’s name match the name of the file.</p>
<h2 id="conclusion">Conclusion</h2>
<p>I hope that this information and code brings joy not only to my fellow Smalltalk enthusiasts, but also to those Objective-C programmers who want an insight into the origins of their language.</p>]]></description>
    <pubDate>Sun, 20 Sep 2009 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2009-09-20-writing-mac-os-x-applications-in-smalltalk.html</guid>
</item>
<item>
    <title>Diamonds Wait For No Man</title>
    <link>http://www.jonmsterling.com/posts/2010-08-17-diamonds-wait-for-no-man.html</link>
    <description><![CDATA[<p>I know people. Some of them are even reading this. You know who you are. The ones who sighed in relief when it became cool to be a geek, when the International Baccalaureate became a source of pride and mutual camaraderie. You’re one of the new generation of movers, shakers and future-makers; but what’s this? You’re hiding?</p>
<!--MORE-->

<p>Where is it that you really belong? You know you don’t belong here, and your worst fear is that everyone else knows this too. Everyone around you is comfortable, confident and excited for the future, and you’re living a dream. Someone else’s dream, one you can only watch others fulfill. As the years go by, the expectations of a high-schooler are proved to be justified, just not by you. By the people you used to hang out with, row boats with, study with.</p>
<p>Where is he? He’s moving and shaking simultaneously, so hard he can barely hear you. Every once in a while, he passes through your life; “You were going to be a scientist, right? That’s so cool,” he says. You don’t have the courage to tell him that you ended up becoming a paralegal, or a nurse’s assistant in Just Nine Months™, that your grand dreams for the future had to be put aside for whatever reason: you had a kid, you didn’t think you were good enough, you couldn’t afford the future.</p>
<p>Then he rides off in his motorcycle that he bought “because he felt like it”. Part of you wants to shave his trendy stubble with a chain-saw, but the other part wants to ask him how he got where he is, what you did wrong fifteen years ago. But as always, you don’t. You don’t ask him anything, you just say, “Man, it was so cool to see you again! We should get the old gang back together some day, talk about old times…”</p>
<p>“Yeah, man, that would be really cool. Well, I’ve gotta run. <strong>Diamonds wait for no man.</strong>” <em>There is opportunity for the taking in Africa; you just have to see it!</em> And you know you won’t see him again for another few years (unless stalking him on the Internet counts).</p>
<hr />
<p>Like I said, you know who you are. Your problem is that you stole another man’s path, and were surprised when he took it back; I carved out my own. You don’t need to hide in a throng of geeks to be well-liked.</p>]]></description>
    <pubDate>Tue, 17 Aug 2010 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2010-08-17-diamonds-wait-for-no-man.html</guid>
</item>
<item>
    <title>JSBag: A Modern Class Cluster</title>
    <link>http://www.jonmsterling.com/posts/2010-12-10-jsbag-a-modern-class-cluster.html</link>
    <description><![CDATA[<p>I’ve long been frustrated by the complexity of the Class Cluster pattern, and feel that in most cases, it can be replaced with something cleaner and more flexible. <code>JSBag</code> is an example of a new collection class with mutable and immutable variants that is implemented with a pattern similar to the Class Cluster, but far less coupled. I do this using Traits.</p>
<p><em>A ‘bag’ is a multiset, or a set which can contain duplicate objects. <code>CoreFoundation</code> includes <code>CFBag</code>, which is the same concept; for reasons of simplicity, <code>JSBag</code> was implemented on top of <code>NSArray</code> instead of <code>CFBag</code>, but it certainly would be possible if better performance were desired.</em></p>
<!--MORE-->

<h2 id="traits">Traits</h2>
<p>Really, they’re just protocols that have concrete implementations. The way this works is that when a <code>JSBag</code> object is created, the traits (such as mutability) that it needs to have are specified; there are default implementations of each of these traits included (the implementation is in the form of a class adopting the trait’s protocol), but these can be switched out for alternate implementations. You can even add your own traits.</p>
<p>The way this all works is that when the <code>JSBag</code> object receives a message, it looks through its enabled traits until it finds the one which declares a corresponding method; then, it will look through its traits-to-implementation-class map to find the class that implements that method. Then, it grabs the <code>IMP</code> from that class and applies it to <code>self</code> with whichever arguments are necessary.</p>
<p>Whereas in the traditional Class Cluster, the abstract superclass tends to spend a lot of time jiggering about how to delegate its unimplemented tasks, and the concrete subclasses tend to duplicate a lot of functionality among themselves, this system allows pluggable implementations for traits that can easily be turned on and off. So, the <code>JSMutableBag</code> subclass of <code>JSBag</code> actually only implements one method, which is to override the enabled traits to include <code>@protocol(JSMutableBag)</code>. Other similar subclasses of <code>JSBag</code> could be created which add support for more, user-defined traits.</p>
<h2 id="drawbacks">Drawbacks</h2>
<p>The idea of this is not to use alternate implementations that carry down abstract bits from a superclass: the idea is to compose functionality by registering implementations of traits, and then dispatching tasks dynamically to them. That means that a few benefits of the traditional Class Cluster are lost, namely the ability for implementations to have alternative instance-variable layouts.</p>
<p>In the end, I think that the performance gain from that sort of optimization is going to be minimal for most things (remember, <em>YAGNI</em>). So, I believe that in many cases, a trait-composition design like that shown in <code>JSBag</code> could be useful.</p>
<h2 id="design">Design</h2>
<p>You may note that I’ve avoided using specific types of collections in my interface, because in most cases, all that matters is that they can be iterated over. Hence, instead of taking parameters of type <code>NSArray*</code> or <code>NSSet*</code> for some things, I’ve generalized to <code>id &lt;NSFastEnumeration&gt;</code>. Since <code>JSBag</code> adopts <code>&lt;NSFastEnumeration&gt;</code>, that means that methods which take collections as parameters can also take <code>JSBag</code> objects. This is incredibly useful, as it makes having methods like <code>+bagWithArray:</code>, <code>+bagWithSet:</code>, <code>+bagWithBag:</code>, etc. actually redundant:</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec">+ (id)bagWithCollection:(id &lt;NSFastEnumeration&gt;)enumerable;</code></pre>
<p>will handle all of this for us. This made implementing <code>&lt;NSCopying&gt;</code>, <code>&lt;NSMutableCopying&gt;</code>, and several other key bits absolutely trivial:</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec">- (id)copyWithZone:(NSZone *)zone {
  <span class="kw">return</span> [[JSBag allocWithZone:zone] initWithCollection:<span class="kw">self</span>];
}

- (id)mutableCopyWithZone:(NSZone *)zone {
  <span class="kw">return</span> [[JSMutableBag allocWithZone:zone] initWithCollection:<span class="kw">self</span>];
}</code></pre></td></tr></table>
<p>Remember that messaging <code>JSMutableBag</code> vs. <code>JSBag</code> for in this case only changes the default enabled traits from <code>{&lt;JSBasicBag&gt;}</code> to <code>{&lt;JSBasicBag&gt;,&lt;JSMutableBag&gt;}</code>. That’s pretty cool.</p>
<h2 id="moving-forward">Moving Forward</h2>
<p>I believe that this trait-composition approach could be generalized to be usable in many contexts. As I improve it, and make it more flexible, I hope to find neat uses for it. In the meanwhile, clone or fork <code>JSBag</code> <a href="https://github.com/jonsterling/JSBag/">on Github</a>!</p>]]></description>
    <pubDate>Fri, 10 Dec 2010 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2010-12-10-jsbag-a-modern-class-cluster.html</guid>
</item>
<item>
    <title>Making your web app not suck</title>
    <link>http://www.jonmsterling.com/posts/2011-02-04-making-your-web-app-not-suck.html</link>
    <description><![CDATA[<p>In the past, I have railed against companies who choose to write mobile web applications instead of native apps. Having recently tried the mobile version of <a href="http://m.pinboard.in/">Pinboard</a>, as well as the new <a href="http://basecamphq.com/mobile">Basecamp mobile version</a>, I must slightly revise my opinion.</p>
<!--MORE-->

<h2 id="hence-my-new-shitlist.">Hence, my new shitlist.</h2>
<ol style="list-style-type: decimal">
<li><p>Never embed your web application in a native application; that is to say, do not slap a webview above a <code>UITabBarController</code> and call it good. This is a sin.</p></li>
<li><p>Never use controls which attempt to mimic those of the substrate platfom: the bullshit interaction of your iPhone-y navigation bar will only serve to highlight your incompetence to experienced users, and confuse inexperienced ones.</p></li>
<li><p>Do not make some sort of header attempt to hover at the top of your view, unless you have coded your own scrolling system (like in PastryKit). All the time, I see bullshit websites that have some sort of terrible navigation bar that sits at the top of the view, no matter how far down you are scrolled; but because it is bullshit, when you start dragging to scroll, the header disappears, and reappears when scrolling has stopped. This is bullshit.</p></li>
<li><p>Don’t overuse animation. WebKit has some neat stuff these days, and in an attempt to make web apps feel at home, some devs insist of using view animations (like in an iOS navigation controller). Don’t do this: it’s often laggy, and takes away from the speed of a transition that ought to be instant! When I do something in a native navigation controller, I expect some animation-feedback; when I tap a link in a website, I expect to brought <strong>immediately</strong> to my destination.</p></li>
<li><p>Don’t, for the love of God, try to make it look like iOS. The whole reason for web applications is that your don’t have to spend resources building a separate app for each platform. If you are content to force all users, regardless of their platform, to use an app that looks like you disemboweled iOS and filled her with bullshit, then you ought to just make a nice native app for iOS and ignore the other platforms.</p></li>
</ol>
<blockquote>
<p><strong>Note:</strong> <a href="http://twitter.com/stevestreza">@stevestreza</a>, the creator of the awesome web app <a href="http://swearch.me/">Swearch</a>, informs me that it’s possible to make WebKit animations 60fps on iPhone 3GS and up, if you code them the hell properly. The problem is that most developers do a poor job at this, I suppose.</p>
</blockquote>
<h2 id="what-you-must-do.">What you must do.</h2>
<p>If you must make a mobile web app, make it as simply as possible, without lots of custom controls. In fact, just try to make it exactly like Pinboard; 37signals also did a great job with Basecamp (though I disagree with their use of animated transitions). Last thing: for the sake of iOS users, please make sure that your app is capable of being clipped to the home screen and opening in its own chromeless browser.</p>]]></description>
    <pubDate>Fri, 04 Feb 2011 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2011-02-04-making-your-web-app-not-suck.html</guid>
</item>
<item>
    <title>More useful snapping for NSSlider</title>
    <link>http://www.jonmsterling.com/posts/2011-11-13-more-useful-snapping-for-nsslider.html</link>
    <description><![CDATA[<p>If you want an <code>NSSlider</code> to snap on certain intervals, your option out-of-the-box is to give it tick marks (using <code>-setNumberOfTickMarks:</code>), and then enforce that it can only be set to values coinciding with a tick mark (using <code>setAllowsTickMarkValuesOnly:</code>). This is great, if you only want to accept values at certain intervals; but it’s not very helpful if you simply want to <em>snap to</em> values at key points (like quarters, or thirds).</p>
<!--MORE-->

<p>I’ve seen a few solutions to this problem; <a href="http://stackoverflow.com/questions/5843699/hot-to-create-custom-nsslider-like-start-screen-saver-slider-in-system-prefer">the one that came closest</a> ended up overriding</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec">-[NSSliderCell startTrackingAt:inView:],
-[NSSliderCell continueTracking:at:inView:]</code></pre></td></tr></table>
<p>and cleverly switching <code>allowsTickMarkValuesOnly</code> on and off at opportune moments. This worked visually, but the data that was streamed from the slider didn’t actually snap until after tracking ended. This is obviously a non-starter, if you’re showing continuous feedback for your slider.</p>
<h2 id="my-solution">My solution</h2>
<p>So, I’ve come up with a simpler and slightly more clever solution, which behaves just as one would expect it to.</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">@interface</span> JSSnappingSliderCell : NSSliderCell
<span class="kw">@end</span>

<span class="kw">@implementation</span> JSSnappingSliderCell
<span class="dt">static</span> <span class="dt">const</span> CGFloat kSnappingZone = <span class="fl">10.</span>0f;

- (BOOL)continueTracking:(NSPoint)lastPoint at:(NSPoint)currentPoint inView:(NSView *)controlView
{
  CGPoint snapToPoint = currentPoint;

  <span class="kw">for</span> (NSUInteger i = <span class="dv">0</span>; i &lt; <span class="kw">self</span>.numberOfTickMarks; i++)
  {
    NSRect tickMarkRect = [<span class="kw">self</span> rectOfTickMarkAtIndex:i];
    <span class="kw">if</span> (ABS(tickMarkRect.origin.x - currentPoint.x) &lt;= kSnappingZone)
    {
      snapToPoint = [<span class="kw">self</span> rectOfTickMarkAtIndex:i].origin;
      <span class="kw">break</span>;
    }
  }

  <span class="kw">return</span> [<span class="kw">super</span> continueTracking:lastPoint at:snapToPoint inView:controlView];
}

<span class="kw">@end</span></code></pre></td></tr></table>
<p>Enjoy, and <a href="http://www.twitter.com/jonsterling">do let me know</a> if you have a better idea!</p>]]></description>
    <pubDate>Sun, 13 Nov 2011 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2011-11-13-more-useful-snapping-for-nsslider.html</guid>
</item>
<item>
    <title>Expressing Church Pairs with Types</title>
    <link>http://www.jonmsterling.com/posts/2011-12-28-expressing-church-pairs-with-types.html</link>
    <description><![CDATA[<p>It’s easy to express pairs in the untyped lambda calculus; adding types makes it somewhat more complex to get a correct encoding. In this article, I explain how we can build a pair with typesafe accessors in a polymorphically typed lambda calculus with type operators (System <span class="math"><em>F</em><sub><em>ω</em></sub></span>), and demonstrate it in Haskell. This document is Literate Haskell: simply copy and paste it into an <code>.lhs</code> file, and you can feed it into GHCI.</p>
<!--MORE-->
<p>In the untyped lambda calculus, a pair <span class="math">(<em>x</em>, <em>y</em>)</span> is encoded as a function which takes two values <span class="math"><em>x</em></span>, <span class="math"><em>y</em></span>, yielding a new function that takes an accessor function <span class="math"><em>f</em></span> as its argument (that is, <span class="math"><em>f</em></span> selects either the left or the right argument):</p>
<p><span class="math">$\begin{aligned} \textbf{pair} &amp;:= \lambda xyf. f\,xy\\ \textbf{fst} &amp;:= \lambda p. p\, (\lambda xy. x)\\ \textbf{snd} &amp;:= \lambda p. p\, (\lambda xy. y) \end{aligned}$</span></p>
<p>So, the following reductions can occur:</p>
<p><span class="math">$\begin{aligned} \textbf{pair}\; ab &amp;\equiv (\lambda xyf. f\,xy)\; ab\\ &amp;\to \lambda f. f\,ab\\ \textbf{fst}\; (\textbf{pair}\; ab) &amp;\equiv \textbf{fst}\; (\lambda f. f\,ab)\\ &amp;\to (\lambda p. p\, (\lambda xy. x))\; (\lambda f. f\,ab)\\ &amp;\to (\lambda f. f\,ab)\; (\lambda xy. x)\\ &amp;\to (\lambda xy. x)\; ab\\ &amp;\to a\\ \textbf{snd}\; (\textbf{pair}\; ab) &amp;\equiv \textbf{snd}\; (\lambda f. f\,ab)\\ &amp;\to (\lambda p. p\, (\lambda xy. y))\; (\lambda f. f\,ab)\\ &amp;\to (\lambda f. f\,ab)\; (\lambda xy. y)\\ &amp;\to (\lambda xy. y)\; ab\\ &amp;\to b\\ \end{aligned}$</span></p>
<p>Translating our untyped example into the typed lambda calculus naïvely doesn’t change much of anything. The main features of this new calculus are polymorphic types (<span class="math"><em>α</em>, <em>β</em>, <em>γ</em></span>…), and type-level functions corresponding to universal quantification. Types are abstracted over using a capital lambda.</p>
<p><span class="math">$\begin{aligned} \textbf{pair} &amp;:= \Lambda\alpha\beta\gamma. \lambda (x : \alpha) (y : \beta) (f : \alpha\to\beta\to\gamma). f\,xy\\ \textbf{fst} &amp;:= \Lambda\alpha\beta\gamma. \lambda (p : {(\alpha\to\beta\to\alpha)\to\gamma}). p (\lambda (x : \alpha) (y : \beta). x)\\ \textbf{snd} &amp;:= \Lambda\alpha\beta\gamma. \lambda (p : {(\alpha\to\beta\to\beta)\to\gamma}). p (\lambda (x:\alpha) (y:\beta). y) \end{aligned}$</span></p>
<p>However, this is problematic. What this definition of <span class="math"><strong>pair</strong></span> ends up saying is that <em>for all</em> types <span class="math"><em>α</em>, <em>β</em>, <em>γ</em></span>, there is a function that will retrieve a value in <span class="math"><em>γ</em></span> from a pair in <span class="math">(<em>α</em>, <em>β</em>)</span>. This, however, is only true inasmuch as <span class="math"><em>γ</em></span> is either <span class="math"><em>α</em></span> or <span class="math"><em>β</em></span>. Thus, our current definition will allow more incorrect programs than is acceptable in a typed (but not dependently-typed) language. What we really need is to constrain <span class="math"><em>γ</em></span>:</p>
<p><span class="math">$\begin{aligned} \textbf{pair} &amp;:= \Lambda\alpha\beta. \lambda (x:\alpha) (y:\beta) (f:{\alpha\to\beta\to(\alpha\lor\beta)}). f\,xy\\ \textbf{fst} &amp;:= \Lambda\alpha\beta. \lambda (p:{(\alpha\to\beta\to\alpha)\to\alpha}). p (\lambda (x:\alpha)(y:\beta). x)\\ \textbf{snd} &amp;:= \Lambda\alpha\beta. \lambda (p:{(\alpha\to\beta\to\beta)\to\beta}). p (\lambda (x:\alpha)(y:\beta). y) \end{aligned}$</span></p>
<p>So, we have created a typed encoding of the Church Pair which only allows accessors which return a value of the correct type.</p>
<h1 id="encoding-our-typed-church-pair-in-haskell">Encoding our typed Church Pair in Haskell</h1>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE MultiParamTypeClasses #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE Rank2Types #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE FlexibleInstances #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE IncoherentInstances #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE UnicodeSyntax #-}</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">module</span> <span class="dt">ChurchPair</span> <span class="kw">where</span>
<span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Prelude</span> <span class="kw">hiding</span> (<span class="fu">fst</span>, <span class="fu">snd</span>)</code></pre>
<p>The first order of business will be to implement the disjunction constraint (<span class="math">Λ <em>α</em><em>β</em>. <em>α</em> ∨ <em>β</em></span>) in Haskell. To do this, we can use a type class:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">class</span> <span class="dt">TypeOr</span> α β γ</code></pre>
<p>and inhabit it with the proper combinations:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">TypeOr</span> α β α
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">TypeOr</span> α β β</code></pre>
<p>Now, we can create a type synonym (for the sake of convenience) that encapsulates the structure of pairs:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> <span class="dt">Pair</span> α β <span class="fu">=</span> <span class="ot">∀</span> γ. <span class="dt">TypeOr</span> α β γ <span class="ot">⇒</span> (α <span class="ot">→</span> β <span class="ot">→</span> γ) <span class="ot">→</span> γ</code></pre>
<p>A <span class="math"><strong>Pair</strong></span> over <span class="math">(<em>α</em>, <em>β</em>)</span> is function that takes a function that returns one of its elements. Note that we cannot specify within this non-dependent type system that the result of this accessor actually be one of the elements, but the <code>(TypeOr α β γ)</code> constraint allows us to at least ensure that the result is of the type of either element in the pair.</p>
<p>And now, given two values, we can construct a <span class="math"><strong>Pair</strong></span>:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> pair ::</span> α <span class="ot">→</span> β <span class="ot">→</span> <span class="dt">Pair</span> α β
<span class="fu">&gt;</span> pair x y f <span class="fu">=</span> f x y</code></pre>
<p>The accessors are easily written, and their type annotations make clear their function:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> fst ::</span> <span class="dt">Pair</span> α β <span class="ot">→</span> α
<span class="fu">&gt;</span> <span class="fu">fst</span> p <span class="fu">=</span> p <span class="fu">$</span> \x y <span class="ot">→</span> x</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> snd ::</span> <span class="dt">Pair</span> α β <span class="ot">→</span> β
<span class="fu">&gt;</span> <span class="fu">snd</span> p <span class="fu">=</span> p <span class="fu">$</span> \x y <span class="ot">→</span> y</code></pre>
<p>Incidentally, <code>fst</code> and <code>snd</code> can also be defined in terms of library functions:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> fst&#39; p <span class="fu">=</span> p <span class="fu">const</span>
<span class="fu">&gt;</span> snd&#39; p <span class="fu">=</span> p <span class="fu">$</span> <span class="fu">flip</span> <span class="fu">const</span></code></pre>
<p>To demonstrate the benefit our typing constraints, try the following:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">badAccessor ::</span> <span class="dt">Pair</span> α β <span class="ot">→</span> <span class="dt">String</span>
badAccessor p <span class="fu">=</span> p <span class="fu">$</span> \x y <span class="ot">→</span> <span class="st">&quot;Hello&quot;</span> <span class="co">-- type error</span></code></pre>
<p>It is impossible to create an accessor of the wrong type (unless the accessor itself is the <em>bottom</em>, in which case you will have a runtime error).</p>]]></description>
    <pubDate>Wed, 28 Dec 2011 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2011-12-28-expressing-church-pairs-with-types.html</guid>
</item>
<item>
    <title>Unifying Monoids and Monads with Polymorphic Kinds</title>
    <link>http://www.jonmsterling.com/posts/2012-01-12-unifying-monoids-and-monads-with-polymorphic-kinds.html</link>
    <description><![CDATA[<blockquote>
A monad is just a monoid in the category of endofunctors, what’s the problem? — <a href="http://james-iry.blogspot.com/2009/05/brief-incomplete-and-mostly-wrong.html">James Iry</a>.
</blockquote>

<p>Building on the work of sigfpe’s <a href="http://blog.sigfpe.com/2008/11/from-monoids-to-monads.html">From Monoids to Monads</a> and monoidal’s <a href="http://monoidal.blogspot.com/2010/07/kind-polymorphism-in-action.html">Kind polymorphism in action</a> (which demonstrates kind polymorphism in the <a href="http://www.cs.uu.nl/wiki/UHC">Ultrecht Haskell Compiler</a>), we can unify Monoid and Monad under one type class in GHC 7.4.</p>
<!--MORE-->
<p>So, the quote at the beginning is true, but with a few qualifications. As most beginning functional programmers know it, the monoid is a structure that has an identity element <span class="math"><em>i</em><em>d</em></span> and a binary operator <span class="math"> ⊗ </span>:</p>
<p><span class="math">$\begin{aligned} \text{class} &amp;\textbf{Monoid}\ (m : \star) \text{ where}\\ &amp; id: m\\ &amp; \otimes: m \to m \to m \end{aligned}$</span></p>
<p>For the monoid <span class="math"><em>m</em></span> to be valid, the <span class="math"><em>i</em><em>d</em></span> must be the identity with respect to the operator <span class="math"> ⊗ </span>, like <span class="math">0</span> is to <span class="math"> + </span> on natural numbers, or <span class="math">1</span> to <span class="math"> × </span>, etc; the binary operator must also be associative:</p>
<p><span class="math">$\begin{aligned} \forall x &amp;: m.\ &amp;x\otimes id &amp;\equiv id\otimes x \equiv x\\ \forall a,b,c &amp;: m.\ &amp;(a\otimes b)\otimes c &amp;\equiv a\otimes (b\otimes c) \end{aligned}$</span></p>
<p>This kind of monoid does not bear the sort of abstraction required to unify it with Monad, which is rather different:</p>
<p><span class="math">$\begin{aligned} \text{class} &amp;\textbf{Functor}\ m \Rightarrow \textbf{Monad}\ (m : \star\to\star) \text{ where}\\ &amp; \eta: \forall\alpha:\star. (\textbf{Id}\ \alpha \to m\,\alpha) \\ &amp; \mu: \forall\alpha:\star. (m\, (m\,\alpha) \to m\,\alpha) \end{aligned}$</span></p>
<p>In fact, <span class="math"><em>η</em></span> is a natural transformation<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> from the Identity functor to another functor <span class="math"><em>m</em></span>; <span class="math"><em>μ</em></span> is a natural transformation from <span class="math"><em>m</em><sup>2</sup></span> to <span class="math"><em>m</em></span> (that is, from <span class="math"><em>m</em></span> applied twice to <span class="math"><em>m</em></span> applied once).</p>
<h3 id="a-difference-of-kinds">A Difference of Kinds</h3>
<p>You’ll note that our <span class="math"><strong>Monad</strong></span> and <span class="math"><strong>Monoid</strong></span> operate in totally different worlds: a difference of kinds. That is, an instance of the former is a type of values (<span class="math"><em>m</em>:  ⋆ </span>), whereas an instance of the latter is an arrow from one type to another (a type constructor, <span class="math"><em>m</em>:  ⋆  →  ⋆ </span>). By analogy, then, the former’s functions should be natural transformations in the latter.</p>
<p>This makes fine sense, but the question of what to do with <span class="math"><em>i</em><em>d</em></span> remains: why does it have an input in <span class="math"><strong>Monad</strong></span>, but not in <span class="math"><strong>Monoid</strong></span>? If we are going to understand these functions as arrows between objects in a category, then <span class="math"><em>i</em><em>d</em></span> must have an input. As a natural transformation in <span class="math"><strong>Monad</strong></span>, its input is the identity functor; as a simple function in <span class="math"><strong>Monoid</strong></span>, its input should be <span class="math">$\varnothing$</span>, nothing.</p>
<p>If we uncurry <span class="math"> ⊗ </span>, then its type becomes (<span class="math"><em>m</em> × <em>m</em> → <em>m</em></span>); this adjustment brings its type in line with that of <span class="math"><em>μ</em></span>. So, we can build the following (incomplete and flawed) generalization over an identity element <span class="math"><em>i</em><em>d</em></span> and a type-operator <span class="math"> × </span>:</p>
<p><span class="math">$\begin{align} \text{class} &amp;\textbf{Monoid}\ (id: k)\ (\times : k\to k\to \star)\ (m : k)\ \text{ where}\\ &amp; id: id \to m\\ &amp; \otimes: m\times m \to m \end{align}$</span></p>
<p><span class="math">$\begin{align} \text{instance} &amp;\textbf{Num}\ \alpha \Rightarrow \textbf{Monoid}\ \varnothing\ (\Lambda x\,y. (x,y))\ \alpha\ \text{ where}\\ &amp; id = const\ 0\\ &amp; \otimes = uncurry\ (+) \end{align}$</span></p>
<p><span class="math">$\begin{align} \text{instance} &amp;\textbf{Monoid}\ \textbf{Id}\ (\Lambda f\,g\,\alpha. f\ (g\,\alpha))\ [\,]\ \text{ where}\\ &amp; id\ (\textbf{Id}\ x) = [x]\\ &amp; \otimes [xs] = xs \end{align}$</span></p>
<p>But this doesn’t work, since the type of <span class="math"><em>i</em><em>d</em></span> for our second (monadic) instance reduces to <span class="math"><em>I</em><em>d</em> → []</span>, which doesn’t type-check: that is, the kind of <span class="math">( → )</span> is <span class="math"> ⋆  →  ⋆  →  ⋆ </span>, but the kind of each of its operands in <span class="math"><em>i</em><em>d</em></span> is already (<span class="math"> ⋆  →  ⋆ </span>). What this means is that for monadic instances of <span class="math"><strong>Monoid</strong></span>, we need an arrow type constructor of kind <span class="math">( ⋆  →  ⋆ ) → ( ⋆  →  ⋆ ) →  ⋆ </span>. So we need to abstract over kind of arrow constructor:</p>
<p><span class="math">$\begin{align} \text{class} &amp;\textbf{Monoid}\ (\leadsto\;: k\to k\to\star)\ (id: k)\ (\times : k\to k\to \star)\ (m : k)\ \text{ where}\\ &amp; id: id \leadsto m\\ &amp; \otimes: m\times m \leadsto m \end{align}$</span></p>
<p>A normal monoid deals with function arrows and pairs:</p>
<p><span class="math">$\begin{align} \text{instance} &amp;\textbf{Num}\ \alpha \Rightarrow \textbf{Monoid}\ (\to)\ \varnothing\ (\Lambda x\,y. (x,y))\ \alpha\ \text{ where}\\ &amp; id = const\ 0\\ &amp; \otimes = uncurry\ (+) \end{align}$</span></p>
<p>A monadic monoid deals with natural transformations and composed functors:</p>
<p><span class="math">$\begin{align} \text{instance} &amp;\textbf{Monoid}\ (\Lambda f\,g\,\alpha. f\,\alpha\to g\,\alpha)\ \textbf{Id}\ (\Lambda f\,g\,\alpha. f\ (g\,\alpha))\ [\,]\ \text{ where}\\ &amp; id\ (\textbf{Id}\ x) = [x]\\ &amp; \otimes [xs] = xs \end{align}$</span></p>
<h3 id="the-haskell-version">The Haskell Version</h3>
<p>We’ll need to turn on a bunch of GHC extensions.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE PolyKinds #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE MultiParamTypeClasses #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE UndecidableInstances #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE FunctionalDependencies #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE RankNTypes #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE TypeOperators #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE DeriveFunctor #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE UnicodeSyntax #-}</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">module</span> <span class="dt">GeneralizedMonoid</span> <span class="kw">where</span>
<span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Control.Monad</span> (<span class="kw">Monad</span>(<span class="fu">..</span>))
<span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Data.Monoid</span> (<span class="dt">Monoid</span>(<span class="fu">..</span>))</code></pre>
<p>First we define the type class <code>Monoidy</code>:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">class</span> <span class="dt">Monoidy</span> (<span class="fu">~&gt;</span>) comp <span class="fu">id</span> m <span class="fu">|</span> m (<span class="fu">~&gt;</span>) <span class="ot">→</span> comp <span class="fu">id</span> <span class="kw">where</span>
<span class="fu">&gt;</span><span class="ot">   munit ::</span> <span class="fu">id</span> <span class="fu">~&gt;</span> m
<span class="fu">&gt;</span><span class="ot">   mjoin ::</span> m <span class="ot">`comp`</span> m <span class="fu">~&gt;</span> m</code></pre>
<p>We use functional dependencies to help the typechecker understand that <code>m</code> and <code>~&gt;</code> uniquely determine <code>comp</code> (<span class="math"><em>t</em><em>i</em><em>m</em><em>e</em><em>s</em></span>) and <code>id</code>.</p>
<p>This kind of type class would not have been possible in previous versions of GHC; with the new kind system, however, we can abstract over kinds!<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup> Now, let’s create types for the additive and multiplicative monoids over the natural numbers:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">newtype</span> <span class="dt">Sum</span> a <span class="fu">=</span> <span class="dt">Sum</span> a <span class="kw">deriving</span> <span class="kw">Show</span>
<span class="fu">&gt;</span> <span class="kw">newtype</span> <span class="dt">Product</span> a <span class="fu">=</span> <span class="dt">Product</span> a <span class="kw">deriving</span> <span class="kw">Show</span>
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="kw">Num</span> a <span class="ot">⇒</span> <span class="dt">Monoidy</span> (<span class="ot">→</span>) (,) () (<span class="dt">Sum</span> a) <span class="kw">where</span>
<span class="fu">&gt;</span>   munit _ <span class="fu">=</span> <span class="dt">Sum</span> <span class="dv">0</span>
<span class="fu">&gt;</span>   mjoin (<span class="dt">Sum</span> x, <span class="dt">Sum</span> y) <span class="fu">=</span> <span class="dt">Sum</span> <span class="fu">$</span> x <span class="fu">+</span> y
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="kw">Num</span> a <span class="ot">⇒</span> <span class="dt">Monoidy</span> (<span class="ot">→</span>) (,) () (<span class="dt">Product</span> a) <span class="kw">where</span>
<span class="fu">&gt;</span>   munit _ <span class="fu">=</span> <span class="dt">Product</span> <span class="dv">1</span>
<span class="fu">&gt;</span>   mjoin (<span class="dt">Product</span> x, <span class="dt">Product</span> y) <span class="fu">=</span> <span class="dt">Product</span> <span class="fu">$</span> x <span class="fu">*</span> y</code></pre>
<p>It will be slightly more complicated to make a monadic instance with <code>Monoidy</code>. First, we need to define the identity functor, a type for natural transformations, and a type for functor composition:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">newtype</span> <span class="dt">Id</span> α <span class="fu">=</span> <span class="dt">Id</span> {<span class="ot"> runId ::</span> α } <span class="kw">deriving</span> <span class="kw">Functor</span></code></pre>
<p>A natural transformation (<span class="math">Λ <em>f</em> <em>g</em> <em>α</em>. (<em>f</em> <em>α</em>) → (<em>g</em> <em>α</em>)</span>) may be encoded in Haskell as follows:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">newtype</span> <span class="dt">NT</span> f g <span class="fu">=</span> <span class="dt">NT</span> {<span class="ot"> runNT ::</span> <span class="ot">∀</span> α. f α <span class="ot">→</span> g α }</code></pre>
<p>Functor composition (<span class="math">Λ <em>f</em> <em>g</em> <em>α</em>. <em>f</em> (<em>g</em> <em>α</em>)</span>) is encoded as follows:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">newtype</span> <span class="dt">FC</span> f g α <span class="fu">=</span> <span class="dt">FC</span> {<span class="ot"> runFC ::</span> f (g α) }</code></pre>
<p>Now, let us define some type <code>T</code> which should be a monad:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">newtype</span> <span class="dt">Wrapper</span> a <span class="fu">=</span> <span class="dt">Wrapper</span> {<span class="ot"> runWrapper ::</span> a } <span class="kw">deriving</span> (<span class="kw">Show</span>, <span class="kw">Functor</span>)
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Monoidy</span> <span class="dt">NT</span> <span class="dt">FC</span> <span class="dt">Id</span> <span class="dt">Wrapper</span> <span class="kw">where</span>
<span class="fu">&gt;</span>   munit <span class="fu">=</span> <span class="dt">NT</span> <span class="fu">$</span> <span class="dt">Wrapper</span> <span class="fu">.</span> runId
<span class="fu">&gt;</span>   mjoin <span class="fu">=</span> <span class="dt">NT</span> <span class="fu">$</span> runWrapper <span class="fu">.</span> runFC</code></pre>
<p>With these defined, we can use them as follows:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">ghci<span class="fu">&gt;</span> mjoin (munit (), <span class="dt">Sum</span> <span class="dv">2</span>)
      <span class="dt">Sum</span> <span class="dv">2</span>
ghci<span class="fu">&gt;</span> mjoin (<span class="dt">Product</span> <span class="dv">2</span>, <span class="dt">Product</span> <span class="dv">3</span>)
      <span class="dt">Product</span> <span class="dv">6</span>
ghci<span class="fu">&gt;</span> runNT mjoin <span class="fu">$</span> <span class="dt">FC</span> <span class="fu">$</span> <span class="dt">Wrapper</span> (<span class="dt">Wrapper</span> <span class="st">&quot;hello, world&quot;</span>)
      <span class="dt">Wrapper</span> {runWrapper <span class="fu">=</span> <span class="st">&quot;hello, world&quot;</span> }</code></pre>
<p>We can even provide a special binary operator for the appropriate monoids as follows:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> (&lt;+&gt;) ::</span> <span class="dt">Monoidy</span> (<span class="ot">→</span>) (,) () m <span class="ot">⇒</span> m <span class="ot">→</span> m <span class="ot">→</span> m
<span class="fu">&gt;</span> (<span class="fu">&lt;+&gt;</span>) <span class="fu">=</span> <span class="fu">curry</span> mjoin</code></pre>
<pre class="sourceCode haskell"><code class="sourceCode haskell">ghci<span class="fu">&gt;</span> <span class="dt">Sum</span> <span class="dv">1</span> <span class="fu">&lt;+&gt;</span> <span class="dt">Sum</span> <span class="dv">2</span> <span class="fu">&lt;+&gt;</span> <span class="dt">Sum</span> <span class="dv">4</span>
      <span class="dt">Sum</span> <span class="dv">7</span></code></pre>
<p>Now, all the extra wrapping that Haskell requires for encoding this is rather cumbersome in actual use. So, we can give traditional <code>Monad</code> and <code>Monoid</code> instances for instances of <code>Monoidy</code>:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Monoidy</span> (<span class="ot">→</span>) (,) () m <span class="ot">⇒</span> <span class="dt">Monoid</span> m <span class="kw">where</span>
<span class="fu">&gt;</span>   mempty <span class="fu">=</span> munit ()
<span class="fu">&gt;</span>   mappend <span class="fu">=</span> <span class="fu">curry</span> mjoin</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> (<span class="kw">Functor</span> m, <span class="dt">Monoidy</span> <span class="dt">NT</span> <span class="dt">FC</span> <span class="dt">Id</span> m) <span class="ot">⇒</span> <span class="kw">Monad</span> m <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="fu">return</span> x <span class="fu">=</span> runNT munit <span class="fu">$</span> <span class="dt">Id</span> x
<span class="fu">&gt;</span>   x <span class="fu">&gt;&gt;=</span> f <span class="fu">=</span> runNT mjoin <span class="fu">$</span> <span class="dt">FC</span> (f <span class="ot">`fmap`</span> x)</code></pre>
<p>And so the following works:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">ghci<span class="fu">&gt;</span> mappend mempty (<span class="dt">Sum</span> <span class="dv">2</span>)
      <span class="dt">Sum</span> <span class="dv">2</span>
ghci<span class="fu">&gt;</span> mappend (<span class="dt">Product</span> <span class="dv">2</span>) (<span class="dt">Product</span> <span class="dv">3</span>)
      <span class="dt">Product</span> <span class="dv">6</span>
ghci<span class="fu">&gt;</span> join <span class="fu">$</span> <span class="dt">Wrapper</span> <span class="fu">$</span> <span class="dt">Wrapper</span> <span class="st">&quot;hello&quot;</span>
      <span class="dt">Wrapper</span> {runWrapper <span class="fu">=</span> <span class="st">&quot;hello&quot;</span> }
ghci<span class="fu">&gt;</span> <span class="dt">Wrapper</span> <span class="st">&quot;hello, world&quot;</span> <span class="fu">&gt;&gt;=</span> <span class="fu">return</span>
      <span class="dt">Wrapper</span> {runWrapper <span class="fu">=</span> <span class="st">&quot;hello, world&quot;</span> }</code></pre>
<h3 id="if-you-got-this-far">If you got this far…</h3>
<p>I hope you enjoyed that! I can’t express enough my thanks to the people who came before me and helped me indirectly to refine my ideas and understanding of the relationship between monads and monoids. Additionally, a shout-out to the GHC team for adding kind polymorphism!</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>A <em>natural transformation</em> is an arrow from one functor to another.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p><em>Caveat</em>: you cannot use kind variables in annotations (like <code>m :: k</code>, as you can with type variables). Hopefully this will be fixed soon.<a href="#fnref2">↩</a></p></li>
</ol>
</div>]]></description>
    <pubDate>Thu, 12 Jan 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-01-12-unifying-monoids-and-monads-with-polymorphic-kinds.html</guid>
</item>
<item>
    <title>Typed Collections with Self Types in Objective-C</title>
    <link>http://www.jonmsterling.com/posts/2012-02-05-typed-collections-with-self-types-in-objective-c.html</link>
    <description><![CDATA[<blockquote>
<p>The latest versions of the Clang compiler extend the Objective-C language with related return types, which allow a limited form of covariance to be expressed. Methods with certain names (<code>alloc</code>, <code>init</code>, etc.) are inferred to return an object of the instance type for the receiver; other methods can participate in this covariance by using the <code>instancetype</code> keyword for the return type annotation.</p>
</blockquote>
<p>Typically, this feature is used for convenience constructors which would previously have returned <code>id</code>. However, we can also use it to encode statically-typed collections without full-blown generics.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup></p>
<!--MORE-->

<h2 id="decorating-types-with-protocols">Decorating Types with Protocols</h2>
<p>If Objective-C had parametric polymorphism (that is, the ability to abstract over types), then a simple typesafe collection would be trivial:</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">@protocol</span> OrderedCollection[V]
- (V)at:(NSUInteger)index;
- (<span class="dt">void</span>)put:(V)object;
<span class="kw">@end</span></code></pre></td></tr></table>
<p>With <code>instancetype</code>, we support a subset of parametric polymorphism: that is, we can abstract over one type (the type of an instance of the implementing class), and we are limited to referring to this type in method return types.<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup> So, we can approximate something rather close, but slightly less safe and precise:</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">@protocol</span> OrderedCollection
- (instancetype)at:(NSUInteger)index;
- (<span class="dt">void</span>)put:(id)object;
<span class="kw">@end</span></code></pre></td></tr></table>
<p>Since we are limited to abstracting over the type of <code>self</code>, the static type of any such collection must actually be the type of its elements decorated by the <code>&lt;OrderedCollection&gt;</code> protocol. So, a collection of strings statically be understood to be a single string, decorated with collection methods:</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec">NSString &lt;OrderedCollection&gt; *strings = ...;
[strings put:<span class="st">@&quot;hello,&quot;</span>];
[strings put:<span class="st">@&quot;world!&quot;</span>];</code></pre></td></tr></table>
<h2 id="higher-order-messaging">Higher Order Messaging</h2>
<p>The fact that the static type of such a collection is the product of the type of its elements and a collection trait gives rise serendipitously to the applicability of <em>higher-order-messaging</em>, or HOM. For instance, what does it mean if you send <code>NSString</code>-messages to an object <code>NSString &lt;OrderedCollection&gt;*</code>? It makes sense to treat the collection as a <span class="math"><strong>Functor</strong></span> and map the message over its elements:</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">for</span> (NSString *upperString in [strings.uppercaseString substringFromIndex:<span class="dv">1</span>])
  NSLog(<span class="st">@&quot;%@&quot;</span>, upperString);

<span class="co">// =&gt; ELLO,</span>
<span class="co">// =&gt; ORLD!</span></code></pre></td></tr></table>
<h2 id="an-implementation">An Implementation</h2>
<p>We’ll implement covariant protocols <code>&lt;OrderedCollection, MapCollection&gt;</code>.</p>
<h3 id="the-collection-interfaces">The collection interfaces</h3>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">@protocol</span> OrderedCollection &lt;NSFastEnumeration&gt;
- (instancetype)at:(NSUInteger)index;
- (<span class="dt">void</span>)put:(id)object;
<span class="kw">@end</span>

<span class="kw">@protocol</span> MapCollection &lt;NSFastEnumeration&gt;
- (instancetype)at:(id)key;
- (<span class="dt">void</span>)put:(id)object at:(id)key;
<span class="kw">@end</span></code></pre></td></tr></table>
<h3 id="collection-proxies">Collection Proxies</h3>
<p>We will use proxy objects to implement both the HOM and the checked collection accessors. First, we start with an abstract base <code>CollectionProxy</code> class, in terms of which proxies for both arrays and dictionaries will be expressed:</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">@interface</span> CollectionProxy : NSObject
@property (strong) id target;
@property (assign) class elementClass;

- (id)initWithTarget:(id)target;

+ (Class)collectionClass;

<span class="co">// Subclasses will provide a technique for mapping an element in one</span>
<span class="co">// collection to a new element in another.</span>
- (<span class="dt">void</span>)appendMappedObject:(id)mapped fromObject:(id)original toBuffer:(id)buffer;

<span class="co">// Subclasses may wish to map over an object derivable from object</span>
<span class="co">// given in fast enumeration. For instance, dictionaries map over</span>
<span class="co">// values, rather than keys.</span>
- (id)redirectIteration:(id)object;
<span class="kw">@end</span>

<span class="kw">@implementation</span> CollectionProxy
@synthesize target, elementClass;

- (id)initWithTarget:(id)aTarget {
  <span class="kw">if</span> ((<span class="kw">self</span> = [<span class="kw">super</span> init]))
    target = aTarget;

  <span class="kw">return</span> <span class="kw">self</span>;
}

- (id)init {
  <span class="kw">return</span> [<span class="kw">self</span> initWithTarget:[<span class="kw">self</span>.class.collectionClass new]];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
  <span class="kw">if</span> ([<span class="kw">self</span>.class.collectionClass instancesRespondToSelector:sel])
    <span class="kw">return</span> [<span class="kw">self</span>.class.collectionClass instanceMethodSignatureForSelector:sel];

  <span class="kw">return</span> [<span class="kw">self</span>.elementClass instanceMethodSignatureForSelector:sel];
}

- (BOOL)respondsToSelector:(SEL)aSelector {
  <span class="kw">return</span> [<span class="kw">super</span> respondsToSelector:aSelector]
      || [target respondsToSelector:aSelector]
      || [<span class="kw">self</span>.elementClass instancesRespondToSelector:aSelector];
}

- (<span class="dt">void</span>)forwardInvocation:(NSInvocation *)invocation {
  <span class="co">// If the collection itself responds to this selector (like if</span>
  <span class="co">// someone sent -count), we&#39;ll forward the message to it.</span>
  <span class="kw">if</span> ([target respondsToSelector:invocation.selector])
    <span class="kw">return</span> [invocation invokeWithTarget:target];

  <span class="co">// If the invocation returns void, we still want to invoke it, but</span>
  <span class="co">// we don&#39;t want to try to do anything with its results.</span>
  BOOL returnsValue = strcmp(<span class="st">&quot;v&quot;</span>, invocation.methodSignature.methodReturnType) != <span class="dv">0</span>;
  id buffer = returnsValue ? [<span class="kw">self</span>.class.collectionClass new] : nil;

  <span class="kw">for</span> (id obj in target) {
    [invocation retainArguments];
    [invocation invokeWithTarget:[<span class="kw">self</span> redirectIteration:obj]];

    <span class="dt">void</span> *outPtr = NULL;
    <span class="kw">if</span> (returnsValue) {
      [invocation getReturnValue:&amp;outPtr];

      <span class="co">// We marshall the return value of the invocation back into our space.</span>
      id mapped;
      <span class="kw">if</span> ((mapped = objc_unretainedObject(outPtr)))
        [<span class="kw">self</span> appendMappedObject:mapped fromObject:obj toBuffer:buffer];
    }
  }

  <span class="kw">if</span> (returnsValue &amp;&amp; [buffer count] &gt; <span class="dv">0</span>) {
    <span class="co">// Build up a new proxy of the same kind to return.</span>
    CollectionProxy *proxy = [[<span class="kw">self</span>.class alloc] initWithTarget:buffer];

    <span class="co">// We marshall the proxy out of our space and set it as the return</span>
    <span class="co">// value of our invocation.</span>
    invocation.returnValue = &amp;(<span class="dt">const</span> <span class="dt">void</span> *){
      objc_unretainedPointer(proxy)
    };
  }
}

<span class="co">// Default behavior</span>

+ (Class)collectionClass { <span class="kw">return</span> nil; }
- (<span class="dt">void</span>)appendMappedObject:(id)mapped fromObject:(id)original toBuffer:(id)buffer {}
- (id)redirectIteration:(id)object { <span class="kw">return</span> object; }

<span class="kw">@end</span>

<span class="kw">@interface</span> OrderedCollectionProxy : CollectionProxy
<span class="kw">@end</span>

<span class="kw">@interface</span> MapCollectionProxy : CollectionProxy
<span class="kw">@end</span>


<span class="kw">@implementation</span> OrderedCollectionProxy

- (id)initWithTarget:(id)target {
  <span class="kw">if</span> ((<span class="kw">self</span> = [<span class="kw">super</span> initWithTarget:target]) &amp;&amp; [target count])
    <span class="kw">self</span>.elementClass = [[target lastObject] class];

  <span class="kw">return</span> <span class="kw">self</span>;
}

+ (Class)collectionClass {
  <span class="kw">return</span> [NSMutableArray class];
}

- (<span class="dt">void</span>)appendMappedObject:(id)mapped fromObject:(id)original toBuffer:(id)buffer {
  [buffer addObject:mapped];
}

- (<span class="dt">void</span>)put:(id)object {
  assert([object isKindOfClass:<span class="kw">self</span>.elementClass]);
  [<span class="kw">self</span>.target addObject:object];
}

- (instancetype)at:(NSUInteger)index {
  <span class="kw">return</span> [<span class="kw">self</span>.target objectAtIndex:index];
}

<span class="kw">@end</span>


<span class="kw">@implementation</span> MapCollectionProxy

- (id)initWithTarget:(id)target {
  <span class="kw">if</span> ((<span class="kw">self</span> = [<span class="kw">super</span> initWithTarget:target]) &amp;&amp; [target count])
    <span class="kw">self</span>.elementClass = [[target allValues].lastObject class];

  <span class="kw">return</span> <span class="kw">self</span>;
}


+ (Class)collectionClass {
  <span class="kw">return</span> [NSMutableDictionary class];
}

- (<span class="dt">void</span>)appendMappedObject:(id)mapped fromObject:(id)key toBuffer:(id)buffer {
  [buffer setObject:mapped forKey:key];
}

- (id)redirectIteration:(id)key {
  <span class="kw">return</span> [<span class="kw">self</span>.target objectForKey:key];
}

- (<span class="dt">void</span>)put:(id)object at:(id)key {
  assert([object isKindOfClass:<span class="kw">self</span>.elementClass]);
  [<span class="kw">self</span>.target setObject:object forKey:key];
}

- (instancetype)at:(id)key {
  <span class="kw">return</span> [<span class="kw">self</span>.target objectForKey:key];
}

<span class="kw">@end</span></code></pre></td></tr></table>
<h3 id="collection-constructors">Collection Constructors</h3>
<p>To construct a collection of some class, we send a message to that class with a covariant return type; unfortunately, we cannot decorate <code>instancetype</code> with any further protocols. So, ideally <code>+orderedCollection</code> would return <code>instancetype &lt;OrderedCollection&gt;</code>, but this is currently impossible; thus, you will have to provide the type decoration yourself.<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup></p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">@interface</span> NSObject (Collections)
+ (instancetype)orderedCollection;
+ (instancetype)mapCollection;
<span class="kw">@end</span>

<span class="kw">@implementation</span> NSObject (Collections)

+ (instancetype)orderedCollection {
  CollectionProxy *proxy = [OrderedCollectionProxy new];
  proxy.elementClass = <span class="kw">self</span>;
  <span class="kw">return</span> proxy
}

+ (instancetype)mapCollection {
  CollectionProxy *proxy = [MapCollectionProxy new];
  proxy.elementClass = <span class="kw">self</span>;
  <span class="kw">return</span> proxy;
}

<span class="kw">@end</span></code></pre></td></tr></table>
<h2 id="see-it-in-action">See it in action</h2>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec">NSURL &lt;MapCollection&gt; *sites = (id)[NSURL mapCollection];
[sites put:[NSURL URLWithString:<span class="st">@&quot;http://www.jonmsterling.com/&quot;</span>]
        at:<span class="st">@&quot;jon&quot;</span>];
[sites put:[NSURL URLWithString:<span class="st">@&quot;http://www.reddit.com/&quot;</span>]
        at:<span class="st">@&quot;reddit&quot;</span>];
[sites put:[NSURL URLWithString:<span class="st">@&quot;git://github.com/jonsterling/Foam.git&quot;</span>]
        at:<span class="st">&quot;foam_repo&quot;</span>];

NSURL *jonsSite = [sites at:<span class="st">@&quot;jon&quot;</span>];
<span class="co">// =&gt; http://www.jonmsterling.com/</span>

NSString &lt;MapCollection&gt; *schemes = (id)sites.scheme.uppercaseString;
<span class="co">/* =&gt; { jon: &quot;HTTP://&quot;,</span>
<span class="co">        reddit: &quot;HTTP://&quot;,</span>
<span class="co">        foam_repo: &quot;GIT://&quot; }</span>
<span class="co"> */</span></code></pre></td></tr></table>
<h2 id="further-exercises">Further Exercises</h2>
<p>These HOMs do not correctly handle methods that return non-object types. It is definitely possible to write a more robust version that will box primitives appropriately, but not within the scope of this post. This will require further inspection of the method signature of the forwarded invocation.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>Please duplicate <a href="http://www.openradar.me/radar?id=1517409">rdar://10848469</a> if you want <code>instancetype</code> to be allowed in argument types.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>In the context of protocol, <code>instancetype</code> refers to the conforming class; so, <code>instancetype</code> of <code>NSString &lt;OrderedCollection&gt;*</code> is <code>NSString*</code>.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>Please duplicate <a href="http://www.openradar.me/radar?id=1513402">rdar://10849187</a> if you want to be able to decorate <code>instancetype</code> with a protocol list.<a href="#fnref3">↩</a></p></li>
</ol>
</div>]]></description>
    <pubDate>Sun, 05 Feb 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-02-05-typed-collections-with-self-types-in-objective-c.html</guid>
</item>
<item>
    <title>Refinement Protocols: Another Approach to Typed Collections</title>
    <link>http://www.jonmsterling.com/posts/2012-05-01-refinement-protocols-another-approach-to-typesafe-collections.html</link>
    <description><![CDATA[<blockquote>
<p>In February, I <a href="2012-02-05-typed-collections-with-self-types-in-objective-c.html">wrote</a> about using <code>instancetype</code> to get semi-typesafe collections in Objective-C. After an email conversation with Patrick Beard, I’d like to present another approach.</p>
</blockquote>
<p>One sad consequence of protocols only being commonly used to encode delegation is that beginners frequently conflate protocols with delegation. Hence the proliferation of tutorials on how to “do delegates” in Objective-C; in fact, I had written one such tutorial a long time ago, and it became so popular that I deleted it, for it was feeding directly into this very conflation (which I deem damaging to learners).</p>
<p>In this article, I’ll be showing a more interesting use of protocols: typesafe collections.</p>
<!--MORE-->

<h3 id="narrowing-static-type-with-refinement-protocols">Narrowing Static Type with Refinement Protocols</h3>
<p>In a static-dynamic language like Objective-C, the static type of an object is distinct from its runtime type; in fact, because of mechanisms like forwarding, the runtime type of an object is really quite difficult to pin down (and may change over time)<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup>.</p>
<p>We can take advantage of this disparity by enforcing further restrictions on an object’s interface at compiletime, this eliminating some common sources of programmer error, as well as removing the need for downcasts in many cases.</p>
<h3 id="a-protocol-for-dictionaries-of-numbers">A protocol for dictionaries of numbers</h3>
<p>Take, for instance, the following protocols:</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec"><span class="kw">@protocol</span> NSNumberDictionary &lt;NSObject&gt;
- (NSNumber *)objectForKey:(NSString *)key;
- (NSNumber *)objectForKeyedSubscript:(NSString *)key;
<span class="kw">@end</span>

<span class="kw">@protocol</span> NSNumberMutableDictionary &lt;NSNumberDictionary&gt;
- (<span class="dt">void</span>)setObject:(NSNumber *)number forKey:(NSString *)key;
- (<span class="dt">void</span>)setObject:(NSNumber *)number forKeyedSubscript:(NSString *)key;
<span class="kw">@end</span>

<span class="kw">@interface</span> NSDictionary (NSNumberDictionary) &lt;NSNumberDictionary&gt;
<span class="kw">@end</span>
<span class="kw">@interface</span> NSMutableDictionary (NSNumberMutableDictionary) &lt;NSNumberMutableDictionary&gt;
<span class="kw">@end</span></code></pre>
<p>Now, we can safely interact with a dictionary that is supposed to have only numbers as values:</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec">id &lt;NSNumberMutableDictionary&gt; ages = [NSMutableDictionary new];
ages[<span class="st">@&quot;jon&quot;</span>] = @<span class="dv">19</span>;
ages[<span class="st">@&quot;dan&quot;</span>] = <span class="st">@&quot;53&quot;</span>; <span class="co">// &lt;--- Incompatible pointer types sending &#39;NSString *&#39; to parameter of type &#39;NSNumber *&#39;</span>

<span class="co">// dot notation also works, because our types are fixed statically:</span>
NSUInteger jonAge = ages[<span class="st">@&quot;jon&quot;</span>].unsignedIntegerValue;</code></pre>
<p>Incidentally, due to what would seem to be a bug in Clang, even though our <code>&lt;NSNumberDictionary&gt;</code> protocol does <em>not</em> include a signature for <code>-setObject:forKeyedSubscript:</code>, the following code compiles with no complaint:</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec"><span class="co">// this compiles, but it shouldn&#39;t:</span>
id &lt;NSNumberDictionary&gt; immutableDictionary = [NSDictionary new];
immutableDictionary[<span class="st">@&quot;key&quot;</span>] = @<span class="dv">45</span>;</code></pre>
<p>Until this is fixed, we can work around it by providing an impossible signature in our immutable protocol:</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec"><span class="kw">typedef</span> <span class="kw">struct</span> {} MutationUnavailableForImmutableObject;
<span class="kw">@protocol</span> NSNumberDictionary &lt;NSObject&gt;
- (NSNumber *)objectForKey:(NSString *)key;
- (NSNumber *)objectForKeyedSubscript:(NSString *)key;
- (<span class="dt">void</span>)setObject:(MutationUnavailableForImmutableObject)object forKeyedSubscript:(NSString *)key;
<span class="kw">@end</span></code></pre>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec">id &lt;NSNumberDictionary&gt; immutableDictionary = [NSDictionary new];
immutableDictionary[<span class="st">@&quot;key&quot;</span>] = @<span class="dv">45</span>;
<span class="co">// ^-- Method object parameter type &#39;MutationUnavailableForImmutableObject&#39; is not object type</span></code></pre>
<h1 id="generalizing-our-technique-with-macros">Generalizing our technique with macros</h1>
<p>So far, our approach has involved making new refinement protocols for every possible element type. This is obviously untenable, but we can make things easier by encoding generic protocols as macros:</p>
<p>First, let’s make a macro that handles the creation of any protocol and a dummy adopting category for a class:</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec"><span class="ot">#define GenericProtocol(T,E,Name,...)\</span>
<span class="kw">@protocol</span> E##Name &lt;NSObject&gt;\
__VA_ARGS__\
<span class="kw">@end</span>\
<span class="kw">@interface</span> T (E##Name) &lt;E##Name&gt;\
<span class="kw">@end</span></code></pre>
<p>We’ll also need a macro for a mutable variant that depends on the immutable protocol:</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec"><span class="ot">#define GenericMutableProtocol(T,E,Name,...)\</span>
<span class="kw">@protocol</span> E##Mutable##Name &lt;E##Name&gt;\
__VA_ARGS__\
<span class="kw">@end</span>\
<span class="kw">@interface</span> T (E##Mutable##Name) &lt;E##Mutable##Name&gt;\
<span class="kw">@end</span></code></pre>
<p>Now, if the immutable protocol includes a <code>-mutableCopy</code> method, it will have to return an object of the mutable variant. So, we need to provide forward declarations for the protocols:</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec"><span class="ot">#define ForwardDeclareMutable(E,Name)\</span>
protocol E##Mutable##Name</code></pre>
<p>You probably noticed that we didn’t include the <code>@</code> before <code>protocol</code> in this macro; this is a little trick that will allow us to have our macros begin with the <code>@</code>-sign, just like real Objective-C directives. It’s not necessary, but it’s a nice little sleight of hand. And now, we can provide our generic dictionary macro:</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec"><span class="ot">#define DictProtocol(E) ForwardDeclareMutable(E,Dictionary)\</span>
GenericProtocol(NSDictionary, E, Dictionary,\
  - (id &lt;E##Dictionary&gt;)copy;\
  - (id &lt;E##Mutable##Dictionary&gt;)mutableCopy;\
  - (E *)objectForKey:(NSString *)key;\
  - (E *)objectForKeyedSubscript:(NSString *)key;\
  - (<span class="dt">void</span>)setObject:(MutationUnavailableForImmutableObject)object forKeyedSubscript:(NSString *)key;\
)\
GenericMutableProtocol(NSMutableDictionary, E, Dictionary,\
  - (<span class="dt">void</span>)setObject:(E *)object forKey:(NSString *)key;\
  - (<span class="dt">void</span>)setObject:(E *)object forKeyedSubscript:(NSString *)key;\
  - (<span class="dt">void</span>)addEntriesFromDictionary:(id &lt;E##Dictionary&gt;)otherDictionary;\
  - (<span class="dt">void</span>)setDictionary:(id &lt;E##Dictionary&gt;)otherDictionary;
)</code></pre>
<p>Finally, we can instantiate typed dictionary protocols for various object types:<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup></p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec">@DictProtocol(NSNumber);
@DictProtocol(NSString);
@DictProtocol(NSData);
@DictProtocol(NSArray);</code></pre>
<h2 id="the-downside-to-our-approach">The downside to our approach</h2>
<h3 id="ambiguity-multiple-signatures-for-a-method">Ambiguity: multiple signatures for a method</h3>
<p>The most glaring problem with this approach is that we are injecting multiple signatures for a single method into a single class (via our categories). So, the result is that it becomes impossible to interact with a non-pimped collection; the following code may fail:</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec">NSMutableDictionary *plainDict = [NSMutableDictionary new];
plainDict[<span class="st">@&quot;key&quot;</span>] = <span class="st">@&quot;a string&quot;</span>;
<span class="co">// &lt;-- Compiler was expecting some other random type that we have instantiated,</span>
<span class="co">//     like NSData or something. Oops.</span></code></pre>
<p>So anywhere these refinement protocols and the associated categories are in scope, we are obliged to use them. For many people, that is too great a demand.</p>
<p>We can instead just remove our categories can keep these method signatures scoped in their protocols. But then we have to do an unsafe downcast to <code>id</code> whenever we wish to instantiate a new typed dictionary. That’s rather close to beating the point.</p>
<p>Lastly, literals can never be typesafe, since the signature of <code>+arrayWithObjects:count:</code> and friends is required to take a parameter no more precise than <code>id[]</code> for literal creation (if you don’t believe me, see <code>Sema::BuildObjCArrayLiteral</code> in <a href="http://clang.llvm.org/doxygen/SemaExprObjC_8cpp_source.html"><code>SemaExprObjC.cpp</code></a>). And even more important, the literal expression compiler of course does not abstract over the intended type of its result! So even if it were possible to have one of these methods with a more precise signature, the compiler would still have no way to disambiguate which method signature to follow in any given instance. This may be fixable, but would likely require a not insignificant amount of compiler rejiggering.</p>
<h2 id="concluding-remarks">Concluding Remarks</h2>
<p>It’s a rather nice idea for getting around Objective-C’s lack of type safety, and I thank Patrick for getting me to think about it a little more. It’s not perfect, however, and its necessary deficiencies will likely prevent its use in shipping code for now. If anyone has any ideas on how to improve this and make it work better, I’m all ears!</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>This is a <em>bad thing</em>, but we’re going to roll with it since it’s how the language works. Basically, in an ideal message-passing language, the set of messages an object is guaranteed to respond to (its structural type) should be invariant over time, whereas the way in which the object responds to those methods may change over time. (In this ideal world, we have a structurally typed language rather than a nominally typed one.)</p>
<p>An example of this distinction is Futures: from the moment a future is created, it should be decorated with the protocol of its promised object, and is guaranteed to respond to messages that are meant to the object it encloses. When its promised object has not yet been created, the future will respond to messages by queuing them up for later; after the object has been created, the future should behave transparently as though it were the object itself.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>One limitation is that we can’t provide a contract for elements to be, for instance, of type <code>id &lt;UITextFieldDelegate&gt;</code> or something. We could extend our system to support this, but protocol names would have to be supplied rather than generated.<a href="#fnref2">↩</a></p></li>
</ol>
</div>]]></description>
    <pubDate>Tue, 01 May 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-05-01-refinement-protocols-another-approach-to-typesafe-collections.html</guid>
</item>
<item>
    <title>Partial Functions: more or less than a function?</title>
    <link>http://www.jonmsterling.com/posts/2012-07-15-partial-functions-more-or-less.html</link>
    <description><![CDATA[<blockquote>
<p>Funny how we like to talk about total functions. As if there’s any other kind of function.</p>
</blockquote>
<p>This was my somewhat flippant remark this morning, which incited a conversation about the nature of functions and partial functions, leading me to learn a few things.</p>
<!--MORE-->

<p><strong>But aren’t partial functions another kind of function?</strong> This was a response to my remark, and I think it deserves to be addressed.</p>
<p>The way I see it, a partial function is somewhat <em>less</em> than a function, because it doesn’t fulfill all of the requirements of being a function: namely that it maps every element of its domain <span class="math"><em>X</em></span> to an element of its codomain <span class="math"><em>Y</em></span>:</p>
<p><span class="math">$\begin{align} f&amp;: X \mapsto Y\\ p&amp;: X' \mapsto Y\ \text{where}\ X' \subseteq X \end{align}$</span></p>
<p>But another way to look at it, which I hadn’t thought of previously, was that partial functions are a generalization of functions, and so they are <em>more</em> than a function: they broaden the expectations to include things things that don’t conform to the definition of “function” or “total function”.</p>
<p>Does that mean that a partial function is actually <em>more</em> than a function rather than less? No, I don’t believe that to be the case. For instance, rectangles generalize squares to include right-angled quadrilaterals which are irregular; and so the requirements of <em>rectangle</em> are somewhat less than the requirements of <em>square</em>.</p>
<p>We’re talking about the size of their requirements, not the number of conforming entities. In fact, these two things are basically inverse to each other: as the specificity of requirements increases, the field of conforming entities narrows.</p>
<p>So in terms of requirements, a partial function is indeed less than a function. To avoid confusion, the following terminology might help: <em>partiality</em> is a weaker contract than <em>totality</em>.</p>]]></description>
    <pubDate>Sun, 15 Jul 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-07-15-partial-functions-more-or-less.html</guid>
</item>
<item>
    <title>Flexibly-Phased Constraints in Haskell</title>
    <link>http://www.jonmsterling.com/posts/2012-07-22-flexibly-phased-constraints-in-haskell.html</link>
    <description><![CDATA[<p>Unfortunately, Haskell’s Prelude abounds with partial functions, like <code>head</code>, <code>tail</code>, <code>read</code>, etc. There have been some attempts to resolve this by replacing them with safe variants that return <code>Maybe a</code> rather than <code>a</code>. But what about when we can make static guarantees about data?</p>
<p>Because Haskell doesn’t have real <span class="math">∏ </span>-types, we can’t bring those invariants into our program specifications in the same way a dependently-typed language could. But with GHC 7.4’s new <code>-XDataKinds</code> extension, many data types are automatically promoted into the kind-level; this means that we can maintain a static-dynamic phase distinction at the same time as having data structures mirrored into the kind level. Combined with phantom-types, this is enough to start encoding interesting invariants into the type system. <strong>But, reusing statically verified code for dynamic values can be problematic.</strong></p>
<!--MORE-->
<p>Let’s look back at our length-indexed vectors to see the problem first-hand:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE GADTs #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE DataKinds #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE KindSignatures #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE ExistentialQuantification #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE StandaloneDeriving #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE TypeFamilies #-}</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">module</span> <span class="dt">PhasedConstraints</span> <span class="kw">where</span>
<span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Control.Applicative</span> ((<span class="fu">&lt;$&gt;</span>))</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">Nat</span> <span class="fu">=</span> <span class="dt">Z</span> <span class="fu">|</span> <span class="dt">S</span> <span class="dt">Nat</span>
<span class="fu">&gt;</span> <span class="kw">infixr</span> <span class="fu">:&gt;</span>
<span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">Vect</span><span class="ot"> ::</span> <span class="fu">*</span> <span class="ot">-&gt;</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="fu">*</span> <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">VNil</span><span class="ot"> ::</span> <span class="dt">Vect</span> a <span class="dt">Z</span>
<span class="fu">&gt;</span><span class="ot">   (:&gt;) ::</span> a <span class="ot">-&gt;</span> <span class="dt">Vect</span> a n <span class="ot">-&gt;</span> <span class="dt">Vect</span> a (<span class="dt">S</span> n)
<span class="fu">&gt;</span> <span class="kw">deriving</span> <span class="kw">instance</span> <span class="kw">Show</span> a <span class="ot">=&gt;</span> <span class="kw">Show</span> (<span class="dt">Vect</span> a n)</code></pre>
<p>It’s trivial to write safe <code>head</code> and <code>tail</code> functions now:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">vhead ::</span> <span class="dt">Vect</span> a (<span class="dt">S</span> n) <span class="ot">-&gt;</span> a
vhead (x <span class="fu">:&gt;</span> xs) <span class="fu">=</span> x</code></pre>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">vtail ::</span> <span class="dt">Vect</span> a (<span class="dt">S</span> n) <span class="ot">-&gt;</span> <span class="dt">Vect</span> a n
vtail (x <span class="fu">:&gt;</span> xs) <span class="fu">=</span> xs</code></pre>
<p>But what if we don’t statically know the size of our vector? For instance, if we are converting a plain old list to a vector, or if we are parsing some file. We’d presumably box up the vector and existentially quantify its length:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">EVect</span><span class="ot"> ::</span> <span class="fu">*</span> <span class="ot">-&gt;</span> <span class="fu">*</span> <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">EVect</span><span class="ot"> ::</span> <span class="dt">Vect</span> a n <span class="ot">-&gt;</span> <span class="dt">EVect</span> a
<span class="fu">&gt;</span> <span class="kw">deriving</span> <span class="kw">instance</span> <span class="kw">Show</span> a <span class="ot">=&gt;</span> <span class="kw">Show</span> (<span class="dt">EVect</span> a)</code></pre>
<p>Now we can marshall <span class="math">[<em>α</em>]</span> into <span class="math">∀ (<em>α</em>: <em>S</em><em>e</em><em>t</em>). ∃ (<em>n</em>: N). <em>a</em><sup><em>n</em></sup></span>:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> fromList ::</span> [a] <span class="ot">-&gt;</span> <span class="dt">EVect</span> a
<span class="fu">&gt;</span> fromList [] <span class="fu">=</span> <span class="dt">EVect</span> <span class="dt">VNil</span>
<span class="fu">&gt;</span> fromList (x<span class="fu">:</span>xs) <span class="fu">=</span>
<span class="fu">&gt;</span>   <span class="kw">case</span> fromList xs <span class="kw">of</span>
<span class="fu">&gt;</span>     <span class="dt">EVect</span> v <span class="ot">-&gt;</span> <span class="dt">EVect</span> <span class="fu">$</span> x <span class="fu">:&gt;</span> v</code></pre>
<p>But now, we’re in a bit of a pickle, since we cannot reuse our <code>vhead</code> and <code>vtail</code>. So, we can just write new ones that target <code>Maybe</code>:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">evhead ::</span> <span class="dt">EVect</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a
evhead (<span class="dt">EVect</span> <span class="dt">VNil</span>)     <span class="fu">=</span> <span class="kw">Nothing</span>
evhead (<span class="dt">EVect</span> (a <span class="fu">:&gt;</span> b)) <span class="fu">=</span> <span class="kw">Just</span> a</code></pre>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">evtail ::</span> <span class="dt">EVect</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> (<span class="dt">EVect</span> a)
evtail (<span class="dt">EVect</span> <span class="dt">VNil</span>)     <span class="fu">=</span> <span class="kw">Nothing</span>
evtail (<span class="dt">EVect</span> (a <span class="fu">:&gt;</span> b)) <span class="fu">=</span> <span class="kw">Just</span> (<span class="dt">EVect</span> b)</code></pre>
<p>But this is certainly less-than-desirable. We haven’t reused any of our code. Imagine how unfortunate this would be for a function that is more complicated than <code>head</code> or <code>tail</code>… What we actually need is a way to marshall a function with static guarantees to a function with dynamic guarantees without rewriting everything, and without case analysis.</p>
<h3>
Types as Propositions
</h3>

<p>What if instead of restricting the type of the input of <code>vhead</code>, we just required a proof that it was a nonempty vector? Let’s try that. Under the Curry-Howard correspondance, types are propositions, and values are proofs. So, we can create a type that represents the proposition <em>greater-than-zero</em> for natural numbers:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">NotZero</span><span class="ot"> ::</span> <span class="dt">Nat</span> <span class="ot">-&gt;</span> <span class="fu">*</span> <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">NotZero</span><span class="ot"> ::</span> <span class="dt">NotZero</span> (<span class="dt">S</span> n)
<span class="fu">&gt;</span> <span class="kw">deriving</span> <span class="kw">instance</span> <span class="kw">Show</span> (<span class="dt">NotZero</span> n)</code></pre>
<p>Basically, excluding <em>bottom</em>, <code>NotZero n</code> does not have any inhabitants of type <code>NotZero Z</code>. So, forall natural numbers <code>n</code>, any value <code>NotZero n</code> is a proof that <code>n</code> is not zero. And we can just take this as a parameter in our new version of <code>vhead</code>:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> vhead ::</span> <span class="dt">Vect</span> a n <span class="ot">-&gt;</span> <span class="dt">NotZero</span> n <span class="ot">-&gt;</span> a
<span class="fu">&gt;</span> vhead (x <span class="fu">:&gt;</span> xs) <span class="dt">NotZero</span> <span class="fu">=</span> x</code></pre>
<p>To use <code>vhead</code>, just include the proof in the parameters:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">exampleVector <span class="fu">=</span> <span class="st">&quot;hello&quot;</span> <span class="fu">:&gt;</span> <span class="st">&quot;world&quot;</span> <span class="fu">:&gt;</span> <span class="dt">VNil</span>
hello <span class="fu">=</span> vhead exampleVector <span class="dt">NotZero</span>
<span class="co">-- typeError = vhead VNil NotZero</span></code></pre>
<p>It’s a bit more complicated for <code>vtail</code>, since the length of its input must be universally quantified for it to be able to be applied to a vector with existentially quantified length; that is, behavior must not depend on the value of the index, since the index will just be a skolem type variable in the unpacked existential. So, we need to do subtraction in the right-hand side of the arrow, rather than structural recursion on the left side. To do this, we can use a type family:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> family <span class="dt">Prev</span> (<span class="ot">n ::</span> <span class="dt">Nat</span>)<span class="ot"> ::</span> <span class="dt">Nat</span>
<span class="fu">&gt;</span> <span class="kw">type</span> <span class="kw">instance</span> <span class="dt">Prev</span> (<span class="dt">S</span> n) <span class="fu">=</span> n</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> vtail ::</span> <span class="dt">Vect</span> a n <span class="ot">-&gt;</span> <span class="dt">NotZero</span> n <span class="ot">-&gt;</span> <span class="dt">Vect</span> a (<span class="dt">Prev</span> n)
<span class="fu">&gt;</span> vtail (x <span class="fu">:&gt;</span> xs) <span class="dt">NotZero</span> <span class="fu">=</span> xs</code></pre>
<p>Now, in order to make this work for vectors of unknown length, we need a function that can generate a <code>NotZero</code> proof for all vectors if applicable:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> notEmpty ::</span> <span class="dt">Vect</span> a n <span class="ot">-&gt;</span> <span class="dt">Maybe</span> (<span class="dt">NotZero</span> n)
<span class="fu">&gt;</span> notEmpty <span class="dt">VNil</span> <span class="fu">=</span> <span class="kw">Nothing</span>
<span class="fu">&gt;</span> notEmpty (x <span class="fu">:&gt;</span> xs) <span class="fu">=</span> <span class="kw">Just</span> <span class="dt">NotZero</span></code></pre>
<p>And now, implementing <code>evhead</code> and <code>evtail</code> in terms of the originals is trivial, thanks to currying:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> evhead ::</span> <span class="dt">EVect</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a
<span class="fu">&gt;</span> evhead (<span class="dt">EVect</span> v) <span class="fu">=</span> vhead v <span class="fu">&lt;$&gt;</span> notEmpty v</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> evtail ::</span> <span class="dt">EVect</span> a <span class="ot">-&gt;</span> <span class="dt">Maybe</span> (<span class="dt">EVect</span> a)
<span class="fu">&gt;</span> evtail (<span class="dt">EVect</span> v) <span class="fu">=</span> <span class="dt">EVect</span> <span class="fu">.</span> vtail v <span class="fu">&lt;$&gt;</span> notEmpty v</code></pre>
<p>Gloriously, all the pattern matching and so forth is factored out into the proof generator. This is especially helpful if you have a whole family of functions that you want to be available to both your statically indexed values, and those whose indices are only known dynamically.</p>
<h3>
Taking a breath.
</h3>

<p>The reason we even bothered to do this is that there are more instances of statically verifiable computation in our programs than we like to think. For instance, any time we use a literal form for a data structure, rather than building it up inductively from IO, we are doing something that might benefit from static verification.</p>
<p>But in the popular literature on dependent types (and faking-dependent-types-with-GADTs), there’s quite a bit of focus on building machinery to facilitate this static verification, but not a lot of details on how to make that machinery useful for dynamic data. By factoring constraints into explicit proofs, we can allow our constraints to be checked in different program phases (compilation or execution), according to the requirements of our data (static or dynamic). In a sense, we get to have our cake, and eat it too.</p>]]></description>
    <pubDate>Sun, 22 Jul 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-07-22-flexibly-phased-constraints-in-haskell.html</guid>
</item>
<item>
    <title>Static and Dynamic Proof Inference in Haskell</title>
    <link>http://www.jonmsterling.com/posts/2012-08-05-static-and-dynamic-proof-inference-in-haskell.html</link>
    <description><![CDATA[<p>Previously, I <a href="http://www.jonmsterling.com/posts/2012-07-22-flexibly-phased-constraints-in-haskell.html">discussed</a> using explicit proof parameters in combination with lifted proof generators in order to write code that can distribute its invariants across static and dynamic phases as appropriate. The major disadvantage to that approach is that it can sometimes be difficult and cumbersome to create proofs of certain properties manually. Today, I’ll discuss how to automate that using type classes.</p>
<!--MORE-->
<p>Before we begin, I’d like to further address the question of whether we even need to use explicit proof terms, as it would seem that we could simply use type classes to express our constraints. Let’s try that with a mirroring vector (an collection of an indexed type, where its value is mirrored in both the value and type levels). First, the usual boilerplate:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE GADTs, KindSignatures #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE DataKinds, PolyKinds #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE FlexibleInstances #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE FlexibleContexts #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE TypeOperators #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE TypeFamilies #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE MultiParamTypeClasses #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE OverlappingInstances #-}</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Control.Applicative</span></code></pre>
<p>For some indexed type <code>f i</code>, there is a vector parameterized by a type-level list of <code>i</code>, holding a linked list of values <code>f i</code>.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">infixr</span> <span class="fu">:&lt;</span>
<span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">Vect</span> f is <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">VNil</span><span class="ot"> ::</span> <span class="dt">Vect</span> f <span class="ch">&#39;[]</span>
<span class="fu">&gt;</span><span class="ot">   (:&lt;) ::</span> f i <span class="ot">-&gt;</span> <span class="dt">Vect</span> f is<span class="ot">-&gt;</span> <span class="dt">Vect</span> f (i <span class="ch">&#39;: is)</span></code></pre>
<p>An example indexed type for the vector might be a natural number GADT:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">Nat</span> <span class="fu">=</span> <span class="dt">Z</span> <span class="fu">|</span> <span class="dt">S</span> <span class="dt">Nat</span>
<span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">DNat</span> (<span class="ot">n ::</span> <span class="dt">Nat</span>) <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">DZ</span><span class="ot"> ::</span> <span class="dt">DNat</span> <span class="dt">Z</span>
<span class="fu">&gt;</span>   <span class="dt">DS</span><span class="ot"> ::</span> <span class="dt">DNat</span> n <span class="ot">-&gt;</span> <span class="dt">DNat</span> (<span class="dt">S</span> n)</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> natToNum ::</span> <span class="kw">Num</span> a <span class="ot">=&gt;</span> <span class="dt">DNat</span> n <span class="ot">-&gt;</span> a
<span class="fu">&gt;</span> natToNum <span class="dt">DZ</span> <span class="fu">=</span> <span class="dv">0</span>
<span class="fu">&gt;</span> natToNum (<span class="dt">DS</span> n) <span class="fu">=</span> <span class="dv">1</span> <span class="fu">+</span> natToNum n</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="kw">Show</span> (<span class="dt">DNat</span> n) <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="fu">show</span> <span class="fu">=</span> <span class="fu">show</span> <span class="fu">.</span> natToNum</code></pre>
<p>We wish to have a function to get the index of an item that’s contained in the vector. For that to be safe, we need to be able to prove that the item is even contained in the vector.</p>
<h3>
An attempt without explicit witnesses
</h3>

<p>So, we’ll first try just using a type class. Since the values are guaranteed to be mirrored by the type-list, this is a reasonable way to do it:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">Elem&#39;</span> i is
<span class="kw">instance</span> <span class="dt">Elem&#39;</span> i (i <span class="ch">&#39;: is)</span>
<span class="kw">instance</span> <span class="dt">Elem&#39;</span> i is <span class="ot">=&gt;</span> <span class="dt">Elem&#39;</span> i (j <span class="ch">&#39;: is)</span></code></pre>
<p>But you’ll quickly find that writing a function which uses this constraint is not a simple proposition. In fact, it would appear to be impossible for more than one reason. If we wish to use type classes in this way, we shall actually have to write an <code>IndexOf</code> type class:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">class</span> <span class="dt">IndexOf</span> i is <span class="kw">where</span>
<span class="ot">  indexOf ::</span> <span class="kw">Num</span> a <span class="ot">=&gt;</span> <span class="dt">Vect</span> f is <span class="ot">-&gt;</span> f i <span class="ot">-&gt;</span> a
<span class="kw">instance</span> <span class="dt">IndexOf</span> i (i <span class="ch">&#39;: is) where</span>
  indexOf (i <span class="fu">:&lt;</span> is) i&#39; <span class="fu">=</span> <span class="dv">0</span>
<span class="kw">instance</span> <span class="dt">IndexOf</span> i is <span class="ot">=&gt;</span> <span class="dt">IndexOf</span> i (j <span class="ch">&#39;: is) where</span>
  indexOf (j <span class="fu">:&lt;</span> is) i <span class="fu">=</span> <span class="dv">1</span> <span class="fu">+</span> indexOf is i</code></pre>
<p>And that class will do what we expect, but it <strong>complects constraint with behavior</strong>. This is a “bad” thing, since there may be other functions that require a similar constraint but quite different behavior. That smells of poor factoring. And so we must return to our explicit proof witness strategy.</p>
<h3>
An attempt with explicit witnesses
</h3>

<p>A witness that a value is an item of our mirrored vector is an instance of an inductive family. The base case is that the element lies at the beginning; if we have a proof that it lies somewhere in the vector’s tail, we also have a proof that the it is an element of the vector as a whole:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">Elem</span> a <span class="kw">as</span> <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">Here</span><span class="ot"> ::</span> <span class="dt">Elem</span> x (x <span class="ch">&#39;: xs)</span>
<span class="fu">&gt;</span>   <span class="dt">There</span><span class="ot"> ::</span> <span class="dt">Elem</span> x xs <span class="ot">-&gt;</span> <span class="dt">Elem</span> x (y <span class="ch">&#39;: xs)</span></code></pre>
<p>And so we implement <code>indexOf</code> by recursing through both the values <em>and</em> the layers of proofs!</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> indexOf ::</span> <span class="kw">Num</span> a <span class="ot">=&gt;</span> <span class="dt">Vect</span> f is <span class="ot">-&gt;</span> f i <span class="ot">-&gt;</span> <span class="dt">Elem</span> i is <span class="ot">-&gt;</span> a
<span class="fu">&gt;</span> indexOf (x <span class="fu">:&lt;</span> xs) x&#39; <span class="dt">Here</span> <span class="fu">=</span> <span class="dv">0</span>
<span class="fu">&gt;</span> indexOf (y <span class="fu">:&lt;</span> xs) x (<span class="dt">There</span> p) <span class="fu">=</span> <span class="dv">1</span> <span class="fu">+</span> indexOf xs x p</code></pre>
<p>But, of course, this is absolutely useless at a glance, since in order to even use the function, the programmer has to type a chain of proofs isomorphic to the Peano encoding of the item’s index anyway!</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> testVect ::</span> <span class="dt">Vect</span> <span class="dt">DNat</span> [<span class="dt">Z</span>, <span class="dt">S</span> (<span class="dt">S</span> <span class="dt">Z</span>), <span class="dt">S</span> <span class="dt">Z</span>]
<span class="fu">&gt;</span> testVect <span class="fu">=</span> <span class="dt">DZ</span> <span class="fu">:&lt;</span> (<span class="dt">DS</span> (<span class="dt">DS</span> <span class="dt">DZ</span>)) <span class="fu">:&lt;</span> (<span class="dt">DS</span> <span class="dt">DZ</span>) <span class="fu">:&lt;</span> <span class="dt">VNil</span>
<span class="fu">&gt;</span> noBueno <span class="fu">=</span> indexOf testVect (<span class="dt">DS</span> (<span class="dt">DS</span> <span class="dt">DZ</span>)) (<span class="dt">There</span> <span class="dt">Here</span>) <span class="co">-- 1</span></code></pre>
<p>So, this is a total non-starter unless we can generate the proof term. Since only one term is needed to prove a proposition, we can make a very simple type class for proof inference:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">class</span> <span class="dt">Infer</span> p <span class="kw">where</span>
<span class="fu">&gt;</span><span class="ot">   infer ::</span> p</code></pre>
<p>And we can directly mirror the <code>Elem</code> family (but in the opposite direction):</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Infer</span> (<span class="dt">Elem</span> x (x <span class="ch">&#39;: xs)) where</span>
<span class="fu">&gt;</span>   infer <span class="fu">=</span> <span class="dt">Here</span>
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Infer</span> (<span class="dt">Elem</span> x xs) <span class="ot">=&gt;</span> <span class="dt">Infer</span> (<span class="dt">Elem</span> x (y <span class="ch">&#39;: xs)) where</span>
<span class="fu">&gt;</span>   infer <span class="fu">=</span> <span class="dt">There</span> infer</code></pre>
<p>It’s trivial to write and use a variant of <code>indexOf</code> which uses our new proof inference class:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> indexOf&#39; xs x <span class="fu">=</span> indexOf xs x infer
<span class="fu">&gt;</span> muchoBueno <span class="fu">=</span> testVect <span class="ot">`indexOf&#39;`</span> (<span class="dt">DS</span> (<span class="dt">DS</span> <span class="dt">DZ</span>)) <span class="co">-- 1</span></code></pre>
<h4>
Another example: safe vector access
</h4>

<p>To access a vector at a given index, we need to make sure it’s within bounds. So, we first provide a way to get the length of a type-list:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> family <span class="dt">Length</span><span class="ot"> xs ::</span> <span class="dt">Nat</span>
<span class="fu">&gt;</span> <span class="kw">type</span> <span class="kw">instance</span> <span class="dt">Length</span> <span class="ch">&#39;[] = Z</span>
<span class="fu">&gt;</span> <span class="kw">type</span> <span class="kw">instance</span> <span class="dt">Length</span> (x <span class="ch">&#39;: xs) = S (Length xs)</span></code></pre>
<p>We also need to provide a way to get an element from a type list using an index:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> family <span class="dt">At</span> xs<span class="ot"> n ::</span> <span class="dt">Nat</span>
<span class="fu">&gt;</span> <span class="kw">type</span> <span class="kw">instance</span> <span class="dt">At</span> (x <span class="ch">&#39;: xs) Z = x</span>
<span class="fu">&gt;</span> <span class="kw">type</span> <span class="kw">instance</span> <span class="dt">At</span> (x <span class="ch">&#39;: xs) (S n) = At xs n</span></code></pre>
<p>And now we need a type of less-than proofs:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="kw">LT</span> (<span class="ot">l ::</span> <span class="dt">Nat</span>) (<span class="ot">r ::</span> <span class="dt">Nat</span>) <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">ZLT</span><span class="ot"> ::</span> <span class="kw">LT</span> <span class="dt">Z</span> (<span class="dt">S</span> n)
<span class="fu">&gt;</span>   <span class="dt">SLT</span><span class="ot"> ::</span> <span class="kw">LT</span> n m <span class="ot">-&gt;</span> <span class="kw">LT</span> (<span class="dt">S</span> n) (<span class="dt">S</span> m)</code></pre>
<p>The way we go about <code>at</code> is much the same as in the previous example, just a tiny bit more complicated in the types.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> at ::</span> <span class="dt">Vect</span> f is <span class="ot">-&gt;</span> <span class="dt">DNat</span> n <span class="ot">-&gt;</span> <span class="kw">LT</span> n (<span class="dt">Length</span> is) <span class="ot">-&gt;</span> f (<span class="dt">At</span> is n)
<span class="fu">&gt;</span> at (x <span class="fu">:&lt;</span> xs) <span class="dt">DZ</span> <span class="dt">ZLT</span> <span class="fu">=</span> x
<span class="fu">&gt;</span> at (y <span class="fu">:&lt;</span> xs) (<span class="dt">DS</span> n) (<span class="dt">SLT</span> lt) <span class="fu">=</span> at xs n lt</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Infer</span> (<span class="kw">LT</span> <span class="dt">Z</span> (<span class="dt">S</span> n)) <span class="kw">where</span>
<span class="fu">&gt;</span>   infer <span class="fu">=</span> <span class="dt">ZLT</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Infer</span> (<span class="kw">LT</span> n m) <span class="ot">=&gt;</span> <span class="dt">Infer</span> (<span class="kw">LT</span> (<span class="dt">S</span> n) (<span class="dt">S</span> m)) <span class="kw">where</span>
<span class="fu">&gt;</span>   infer <span class="fu">=</span> <span class="dt">SLT</span> infer</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> v <span class="fu">@.</span> i <span class="fu">=</span> at v i infer</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> hailMary <span class="fu">=</span> testVect <span class="fu">@.</span> (<span class="dt">DS</span> <span class="dt">DZ</span>) <span class="co">-- 2</span></code></pre>
<h3>
Inferring dynamic proofs
</h3>

<p>Dynamic proof inference is the same as static proof inference, except that it may fail:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">class</span> <span class="dt">DynamicInfer</span> p <span class="kw">where</span>
<span class="fu">&gt;</span><span class="ot">   inferDynamic ::</span> <span class="dt">Maybe</span> p</code></pre>
<p>We have to go through this little dance for each proof which we want to make available dynamically. The routine is repetitive enough that one could conceivably use Template Haskell to factor it out, though I’d certainly be pleased to learn if there was a more clean and succinct way of doing it.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">DynamicInfer</span> (<span class="dt">Elem</span> x (x <span class="ch">&#39;: xs)) where</span>
<span class="fu">&gt;</span>   inferDynamic <span class="fu">=</span> <span class="kw">Just</span> infer
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">DynamicInfer</span> (<span class="dt">Elem</span> x xs) <span class="ot">=&gt;</span> <span class="dt">DynamicInfer</span> (<span class="dt">Elem</span> x (y <span class="ch">&#39;: xs)) where</span>
<span class="fu">&gt;</span>   inferDynamic <span class="fu">=</span> <span class="dt">There</span> <span class="fu">&lt;$&gt;</span> inferDynamic
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">DynamicInfer</span> (<span class="dt">Elem</span> x ys) <span class="kw">where</span>
<span class="fu">&gt;</span>   inferDynamic <span class="fu">=</span> <span class="kw">Nothing</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">DynamicInfer</span> (<span class="kw">LT</span> <span class="dt">Z</span> (<span class="dt">S</span> n)) <span class="kw">where</span>
<span class="fu">&gt;</span>   inferDynamic <span class="fu">=</span> <span class="kw">Just</span> infer
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">DynamicInfer</span> (<span class="kw">LT</span> n m) <span class="ot">=&gt;</span> <span class="dt">DynamicInfer</span> (<span class="kw">LT</span> (<span class="dt">S</span> n) (<span class="dt">S</span> m)) <span class="kw">where</span>
<span class="fu">&gt;</span>   inferDynamic <span class="fu">=</span> <span class="dt">SLT</span> <span class="fu">&lt;$&gt;</span> inferDynamic
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">DynamicInfer</span> (<span class="kw">LT</span> n m) <span class="kw">where</span>
<span class="fu">&gt;</span>   inferDynamic <span class="fu">=</span> <span class="kw">Nothing</span></code></pre>
<p>And now it is trivial to make dynamic versions of our functions:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> dynamicIndexOf ::</span> <span class="kw">Num</span> a <span class="ot">=&gt;</span> <span class="dt">Vect</span> f is <span class="ot">-&gt;</span> f i <span class="ot">-&gt;</span> <span class="dt">Maybe</span> a
<span class="fu">&gt;</span> dynamicIndexOf xs x <span class="fu">=</span> indexOf xs x <span class="fu">&lt;$&gt;</span> inferDynamic</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> dynamicAt ::</span> <span class="dt">DynamicInfer</span> (<span class="kw">LT</span> n (<span class="dt">Length</span> is)) <span class="ot">=&gt;</span> <span class="dt">Vect</span> f is <span class="ot">-&gt;</span> <span class="dt">DNat</span> n <span class="ot">-&gt;</span> <span class="dt">Maybe</span> (f (<span class="dt">At</span> is n))
<span class="fu">&gt;</span> dynamicAt xs i <span class="fu">=</span> at xs i <span class="fu">&lt;$&gt;</span> inferDynamic</code></pre>]]></description>
    <pubDate>Sun, 05 Aug 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-08-05-static-and-dynamic-proof-inference-in-haskell.html</guid>
</item>
<item>
    <title>Pi is for Power, Sigma for Product</title>
    <link>http://www.jonmsterling.com/posts/2012-09-07-pi-is-for-power-sigma-for-product.html</link>
    <description><![CDATA[<p><span class="math">∏ </span> and <span class="math">∑ </span> are two fundamental connectives of <a href="http://en.wikipedia.org/wiki/Intuitionistic_type_theory">Intuitionistic Type Theory</a>, corresponding to <span class="math">∀ </span> and <span class="math">∃ </span> in logic respectively. In their non-dependent special cases, they represent cartesian powers and products respectively. Let’s take a look at how this works!</p>
<!--MORE-->

<h2 id="prod-generalizes-arrows-sum-generalizes-products"><span class="math">∏ </span> generalizes arrows, <span class="math">∑ </span> generalizes products</h2>
<p>Anyone who took elementary mathematics is probably aware that <span class="math">∏ </span> is the mathematical symbol for a product of a sequence; you’ve probably seen something like this: <span class="math">$\begin{align} \prod_{i\in\mathbb{N}} f(i) \end{align}$</span>, the product of <span class="math"><em>f</em>(<em>i</em>)</span> over the set of all natural numbers <span class="math">N</span>.</p>
<p>The word “product” gets us mistakenly thinking that a <span class="math">∏ </span>-type should be a pair or something, like <code>(,)</code> in Haskell. Consider the following function type for making a vector of ’!’-characters of a given length in an Agda-like language with dependent types:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="fu">replicate</span> <span class="fu">:</span> (n<span class="fu">:</span>ℕ) <span class="ot">→</span> <span class="dt">Vect</span> n <span class="dt">Char</span> <span class="co">-- syntactic sugar</span>
<span class="fu">replicate</span> <span class="fu">:</span> Π(n<span class="fu">:</span>ℕ)<span class="fu">.</span> <span class="dt">Vect</span> n <span class="dt">Char</span> <span class="co">-- translated into ∏-notation</span>
<span class="fu">replicate</span> <span class="dv">0</span>     <span class="fu">=</span> []
<span class="fu">replicate</span> (n<span class="dv">+1</span>) <span class="fu">=</span> <span class="ch">&#39;!&#39;</span><span class="ot"> ::</span> (<span class="fu">replicate</span> n)</code></pre>
<p>Most dependently-typed languages offer syntactic sugar to allow including terms inside the function-arrow syntax. In fact, we actually can see that for some type <code>P</code> which does not depend on <code>x</code>, <code>Π(x:T).P</code> is exactly equivalent to the plain function type <code>T → P</code>. So how is this really a product?</p>
<blockquote>
<p><strong>Though this be madness, yet there is method in’t!</strong> Let’s see what happens when we restrict our <span class="math">∏ </span>-operator to have the second element not depend on the first.</p>
</blockquote>
<p>Let’s look at a numerical example:</p>
<p><span class="math">$\begin{align} f_x &amp;= C\\ \prod_{i=0}^n f_i &amp;= f_0 \times f_1 \times f_2 \times \cdots \times f_n\\ &amp;= C^n \end{align}$</span></p>
<p>If <code>f</code> is constant over its input, then the multiplication can be collapsed into exponential notation. Now, the above example can be understood with an elementary understanding of grade-school numerical algebra; we can generalize it to hold for type algebra. But remember that an exponential type <span class="math"><em>β</em><sup><em>α</em></sup></span> is just a function type <span class="math"><em>α</em> → <em>β</em></span>! One way to think of it is to say that it maps every <span class="math"><em>α</em></span> into <span class="math"><em>β</em></span>-space.</p>
<p>Another way to think of it is to say that the codomain of a function is modelled by product of all the outputs of that function corresponding to the domain. For instance, consider the set <code>B</code> and some function <code>name</code> that maps bovines to strings:</p>
<p><span class="math">$\begin{align} \textbf{B} &amp;= \{ \text{Bessie}, \text{Brownie}, \text{Macy} \}\\ \textbf{name} &amp;\in \prod_{b\in\textbf{B}}.\ \textbf{String}\\ &amp;\approx \textbf{String}^\textbf{B}\\ &amp;\approx \textbf{B} \to \textbf{String} \end{align}$</span><!--___--></p>
<p>If we’d wanted to specify a function that mapped each bovine to its name paired with <em>that specific</em> bovine, we’d need to use a dependent type.</p>
<p>And so a <span class="math">∏ </span>-type is the (cartesian) product of all elements of its second component corresponding to its first component. In the case that the former is not dependent on the latter, this is a (cartesian) power: this is the space that functions of the second-order lambda calculus inhabit.</p>
<p>It’s much the same with <span class="math">∑ </span>-types. Let’s first take a numerical example:</p>
<p><span class="math">$\begin{align} f_x &amp;= C\\ \sum_{i=0}^n f_i &amp;= f_0 + f_1 + f_2 + \cdots + f_n\\ &amp;= C \times n \end{align}$</span></p>
<p>And so the sum of all the outputs, when the output set doesn’t depend on the input value, is just a product. Let’s look again at our bovine type to see how we can get pairs from this:</p>
<p><span class="math">$\begin{align} \textbf{name} &amp;\in \sum_{b\in\textbf{B}}.\ \textbf{String}\\ &amp;\approx \textbf{String} \times \textbf{B}\\ \end{align}$</span><!--__--></p>
<p>So, in this special non-dependent case, a <span class="math">∑ </span>-type is just a cartesian product (of bovines and strings): it specifies all possible pairs of bovines and string.</p>
<h2 id="realizing-prod-and-sum-in-agda">Realizing <span class="math">∏ </span> and <span class="math">∑ </span> in Agda</h2>
<p>I find that nothing helps me understand a concept better than a concrete example in a language I understand. I’ll be using <a href="http://wiki.portal.chalmers.se/agda/pmwiki.php">Agda</a> today, but the same task could have been done in most other dependent-typed languages, including <a href="http://idris-lang.org">Idris</a>.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">module</span> <span class="dt">SigmaPi</span> <span class="kw">where</span>

<span class="co">-- We use (dependent) records rather than plain-old data declarations</span>
<span class="co">-- because these conveniently provide accessors; an accessor for a</span>
<span class="co">-- Π-type corresponds to function application.</span>
record Π (α <span class="fu">:</span> <span class="dt">Set</span>) (β <span class="fu">:</span> α <span class="ot">→</span> <span class="dt">Set</span>) <span class="fu">:</span> <span class="dt">Set</span> <span class="kw">where</span>
  constructor Λ
  field _<span class="fu">$</span>_ <span class="fu">:</span> ((x <span class="fu">:</span> α) <span class="ot">→</span> β x)

record Σ (α <span class="fu">:</span> <span class="dt">Set</span>) (β <span class="fu">:</span> α <span class="ot">→</span> <span class="dt">Set</span>) <span class="fu">:</span> <span class="dt">Set</span> <span class="kw">where</span>
  constructor _,_
  field
    <span class="fu">fst</span> <span class="fu">:</span> α
    <span class="fu">snd</span> <span class="fu">:</span> β <span class="fu">fst</span>

<span class="co">-- A special case of Π: the function arrow.</span>
_<span class="fu">~&gt;</span>_ <span class="fu">:</span> <span class="dt">Set</span> <span class="ot">→</span> <span class="dt">Set</span> <span class="ot">→</span> <span class="dt">Set</span>
_<span class="fu">~&gt;</span>_ α β <span class="fu">=</span> Π α (λ _ <span class="ot">→</span> β)

<span class="co">-- A special case of Σ: the cartesian product.</span>
_×_ <span class="fu">:</span> <span class="dt">Set</span> <span class="ot">→</span> <span class="dt">Set</span> <span class="ot">→</span> <span class="dt">Set</span>
_×_ α β <span class="fu">=</span> Σ α (λ _ <span class="ot">→</span> β)</code></pre>
<p>Now, we can test them to see how they work:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">module</span> <span class="dt">Tests</span> <span class="kw">where</span>
  open <span class="kw">import</span> <span class="dt">Data.Char</span>
  open <span class="kw">import</span> <span class="dt">Relation.Binary.Core</span>

  open Π
  open Σ

  <span class="kw">data</span> <span class="dt">Bovine</span> <span class="fu">:</span> <span class="dt">Set</span> <span class="kw">where</span>
    <span class="dt">Bessie</span>  <span class="fu">:</span> <span class="dt">Bovine</span>
    <span class="dt">Brownie</span> <span class="fu">:</span> <span class="dt">Bovine</span>
    <span class="dt">Macy</span>    <span class="fu">:</span> <span class="dt">Bovine</span>

  pair <span class="fu">:</span> ℕ × <span class="dt">Bovine</span>
  pair <span class="fu">=</span> <span class="dv">43</span> , <span class="dt">Macy</span>

  suc&#39; <span class="fu">:</span> ℕ <span class="fu">~&gt;</span> ℕ
  suc&#39; <span class="fu">=</span> Λ suc

  <span class="co">-- We can prove trivial equalities to test:</span>
  Σ-<span class="fu">fst-</span>test <span class="fu">:</span> <span class="fu">fst</span> pair ≡ <span class="dv">43</span>
  Σ-<span class="fu">fst-</span>test <span class="fu">=</span> refl

  Σ-<span class="fu">snd-</span>test <span class="fu">:</span> <span class="fu">snd</span> pair ≡ <span class="dt">Macy</span>
  Σ-<span class="fu">snd-</span>test <span class="fu">=</span> refl

  Π-application<span class="fu">-</span>test <span class="fu">:</span> suc&#39; <span class="fu">$</span> <span class="dv">2</span> ≡ <span class="dv">3</span>
  Π-application<span class="fu">-</span>test <span class="fu">=</span> refl</code></pre>
<h2 id="coming-up-next-universe-polymorphism">Coming up next: Universe Polymorphism</h2>
<p>You may be wondering why I haven’t shown how to encode Haskell-style existentials; the problem is that they are actually impossible under the implementation I have given above. In the above implementation, the first part of the <span class="math">∑ </span> is a term of a type, but in order to forget (for instance) the type of a list’s elements, we’d need that first part to be a term of a kind. This calls for <em>universe polymorphism</em>, where the same code can be parameterized over universe levels; this will allow us to easily introduce Haskell-style existential types.</p>]]></description>
    <pubDate>Fri, 07 Sep 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-09-07-pi-is-for-power-sigma-for-product.html</guid>
</item>
<item>
    <title>Pi & Sigma: Adding Universe Polymorphism</title>
    <link>http://www.jonmsterling.com/posts/2012-09-08-adding-universe-polymorphism.html</link>
    <description><![CDATA[<p><a href="http://www.jonmsterling.com/posts/2012-09-07-pi-is-for-power-sigma-for-product.html">Last time</a>, I showed how <span class="math">∏ </span> and <span class="math">∑ </span> types generalize the cartesian power (function arrow) and the cartesian product respectively. Unfortunately, the Agda implementation I provided requires the first element in the <span class="math">∑ </span>-pair to be a term of a type, which precludes the encoding of existentials which could be used to abstract away a type (which is a term of a kind). Today, I’ll show how to fix this using Universe Polymorphism.</p>
<!--MORE-->

<blockquote>
<p><strong>What is universe polymorphism?</strong> In our theory, values inhabit types, types inhabit kinds, and so forth (it’s larger <em>sorts</em> all the way up!) This stratification wraps up the idea that a proposition about a set of terms is their type; and so, if it’s possible to have a proposition about types, then that means they must have kinds; and if we can make propositions about kinds, then they must inhabit terms of some larger space, and so forth. It’s often useful to make a proposition that applies to multiple universes; this is what allows us to, for instance, use the same specification for encoding a list of values and a list of types.</p>
</blockquote>
<h3 id="approaches-to-universe-levels">Approaches to Universe Levels</h3>
<p>The first approach to universe levels is just to ignore them altogether:</p>
<p><span class="math">$\begin{align} \tau \in \textbf{Set} \in \textbf{Set} \in \textbf{Set} \in \textbf{Set}\cdots \tag{Dragons!} \end{align}$</span></p>
<p>This is unfortunate, and will allow us to prove any proposition, even if it is false. Agda provides this feature with its <code>--type-in-type</code> option; even though it would “solve” our problem, it is clearly a nonstarter.</p>
<p>The default approach in Agda is to universe polymorphism, where you parameterize <code>Set</code> with a level index, generating the hierarchy we know and love:</p>
<p><span class="math">$\begin{align} \tau \in \textbf{Set}_0 \in \textbf{Set}_1 \in \textbf{Set}_2\cdots \tag{Stratification} \end{align}$</span>.</p>
<p>The last approach, which is adopted by Idris, is <strong>Cumulativity</strong>.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> Cumulativity adds a typing rule that says that terms in one level are also terms in higher levels:<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup></p>
<p><span class="math">$\begin{align} \frac{\Gamma \vdash \tau \in \text{Set}_\ell} {\Gamma \vdash \tau \in \text{Set}_{\ell+1}} \tag{Cumulativity Rule} \end{align}$</span></p>
<p>Since we’re working in Agda, we will be using the explicit level-parameterization approach.</p>
<h3 id="adding-universe-polymorphism-to-prod-and-sum">Adding Universe Polymorphism to <span class="math">∏ </span> and <span class="math">∑ </span></h3>
<p>Without further delay, let’s rewrite yesterday’s code using universe polymorphism:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">module</span> <span class="dt">SigmaPi</span> <span class="kw">where</span>
  open <span class="kw">import</span> <span class="dt">Level</span> using (_⊔_)

  <span class="co">-- We specify the universe levels as implicit parameters to the type</span>
  <span class="co">-- constructor. Then, we parameterize instances of `Set` with them.</span>

  <span class="co">-- Our parameters may live in different universes, so the resulting</span>
  <span class="co">-- type needs to live in the smallest universe that can hold both.</span>
  <span class="co">-- The _⊔_ operator selects the maximum level of its arguments.</span>
  record Π {l m} (α <span class="fu">:</span> <span class="dt">Set</span> l) (β <span class="fu">:</span> α <span class="ot">→</span> <span class="dt">Set</span> m) <span class="fu">:</span> <span class="dt">Set</span> (l ⊔ m) <span class="kw">where</span>
    constructor Λ
    field _<span class="fu">$</span>_ <span class="fu">:</span> ((x <span class="fu">:</span> α) <span class="ot">→</span> β x)
  open Π public

  record Σ {l m} (α <span class="fu">:</span> <span class="dt">Set</span> l) (β <span class="fu">:</span> α <span class="ot">→</span> <span class="dt">Set</span> m) <span class="fu">:</span> <span class="dt">Set</span> (l ⊔ m) <span class="kw">where</span>
    constructor _,_
    field
      <span class="fu">fst</span> <span class="fu">:</span> α
      <span class="fu">snd</span> <span class="fu">:</span> β <span class="fu">fst</span>
  open Σ public

  <span class="co">-- Not much change is needed to make our special cases work in the</span>
  <span class="co">-- new system.</span>
  _<span class="fu">~&gt;</span>_ <span class="fu">:</span> <span class="ot">∀</span> {ℓ} <span class="ot">→</span> <span class="dt">Set</span> ℓ <span class="ot">→</span> <span class="dt">Set</span> ℓ <span class="ot">→</span> <span class="dt">Set</span> ℓ
  _<span class="fu">~&gt;</span>_ α β <span class="fu">=</span> Π α (λ _ <span class="ot">→</span> β)

  _×_ <span class="fu">:</span> <span class="ot">∀</span> {ℓ} <span class="ot">→</span> <span class="dt">Set</span> ℓ <span class="ot">→</span> <span class="dt">Set</span> ℓ <span class="ot">→</span> <span class="dt">Set</span> ℓ
  _×_ α β <span class="fu">=</span> Σ α (λ _ <span class="ot">→</span> β)</code></pre>
<p>Now, we should be able to existentially abstract out both types <em>and</em> values (previously, we could only abstract out values). Let’s build up some tackle:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">  <span class="co">-- `exists` &quot;forgets&quot; a parameter of its argument; so, `exists P`</span>
  <span class="co">-- would represent translate to `∃ α. P(α)` in logic.</span>
  exists <span class="fu">:</span> <span class="ot">∀</span> {l m} {α <span class="fu">:</span> <span class="dt">Set</span> l} <span class="ot">→</span> (α <span class="ot">→</span> <span class="dt">Set</span> m) <span class="ot">→</span> <span class="dt">Set</span> (l ⊔ m)
  exists <span class="fu">=</span> Σ _

  <span class="co">-- We can define some syntactic sugar to get a cleaner, more familiar</span>
  <span class="co">-- abstraction, which allows us to write `∃ α ⇒ P α ℕ` rather than</span>
  <span class="co">-- the more verbose `exists (λ α → P α ℕ)`.</span>
  syntax exists (λ α <span class="ot">→</span> <span class="dt">P</span>) <span class="fu">=</span> <span class="ot">∃</span> α <span class="ot">⇒</span> <span class="dt">P</span>

  <span class="co">-- Remember, an existential is just a pair containing a value on the</span>
  <span class="co">-- left and a predicate that it satisfies on the right. To simplify</span>
  <span class="co">-- introduction, we can create a little function `∃|` that will infer</span>
  <span class="co">-- the first parameter (such as the length of a vector, or some type</span>
  <span class="co">-- parameter).</span>
  <span class="ot">∃</span>| <span class="fu">:</span> <span class="ot">∀</span> {l m} {α <span class="fu">:</span> <span class="dt">Set</span> l} {β <span class="fu">:</span> α <span class="ot">→</span> <span class="dt">Set</span> m} {x} <span class="ot">→</span> β x <span class="ot">→</span> exists β
  <span class="ot">∃</span>| x <span class="fu">=</span> _ , x</code></pre>
<h3 id="hard-work-pays-off-an-example-use">Hard work pays off: an example use</h3>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">module</span> <span class="dt">Examples</span> <span class="kw">where</span>
  open <span class="kw">import</span> <span class="dt">SigmaPi</span>
  open <span class="kw">import</span> <span class="dt">Data.Nat</span>

  <span class="kw">data</span> <span class="dt">Bovine</span> <span class="fu">:</span> <span class="dt">Set</span> <span class="kw">where</span>
    <span class="dt">Bessie</span>  <span class="fu">:</span> <span class="dt">Bovine</span>
    <span class="dt">Brownie</span> <span class="fu">:</span> <span class="dt">Bovine</span>
    <span class="dt">Macy</span>    <span class="fu">:</span> <span class="dt">Bovine</span>

  <span class="co">-- First, let&#39;s define a dependent vector type, indexed by its length.</span>
  <span class="kw">data</span> <span class="dt">Vector</span> {ℓ} (α <span class="fu">:</span> <span class="dt">Set</span> ℓ) <span class="fu">:</span> ℕ <span class="ot">→</span> <span class="dt">Set</span> ℓ <span class="kw">where</span>
    []  <span class="fu">:</span> <span class="dt">Vector</span> α <span class="dv">0</span>
    _<span class="ot">∷</span>_ <span class="fu">:</span> {n <span class="fu">:</span> ℕ} <span class="ot">→</span> α <span class="ot">→</span> <span class="dt">Vector</span> α n <span class="ot">→</span> <span class="dt">Vector</span> α (n <span class="fu">+</span> <span class="dv">1</span>)
  <span class="kw">infixr</span> <span class="dv">5</span> _<span class="ot">∷</span>_

  <span class="fu">all-</span>bovines <span class="fu">:</span> <span class="dt">Vector</span> <span class="dt">Bovine</span> <span class="dv">3</span>
  <span class="fu">all-</span>bovines <span class="fu">=</span> <span class="dt">Bessie</span> <span class="ot">∷</span> <span class="dt">Brownie</span> <span class="ot">∷</span> <span class="dt">Macy</span> <span class="ot">∷</span> []

  <span class="co">-- We can make a vector&#39;s length abstract (where the length is a value</span>
  <span class="co">-- rather than a type):</span>
  <span class="ot">∃</span>-value<span class="fu">-</span>ex <span class="fu">:</span> <span class="ot">∃</span> n <span class="ot">⇒</span> <span class="dt">Vector</span> <span class="dt">Bovine</span> n
  <span class="ot">∃</span>-value<span class="fu">-</span>ex <span class="fu">=</span> <span class="ot">∃</span>| <span class="fu">all-</span>bovines

  <span class="co">-- We can now also make the type of a vector&#39;s elements abstract:</span>
  <span class="ot">∃</span>-<span class="kw">type</span><span class="fu">-</span>ex <span class="fu">:</span> <span class="ot">∃</span> α <span class="ot">⇒</span> <span class="dt">Vector</span> α <span class="dv">3</span>
  <span class="ot">∃</span>-<span class="kw">type</span><span class="fu">-</span>ex <span class="fu">=</span> <span class="ot">∃</span>| <span class="fu">all-</span>bovines</code></pre>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p><a href="http://idris-lang.org"><code class="url">http://idris-lang.org</code></a><a href="#fnref1">↩</a></p></li>
<li id="fn2"><p><a href="http://www.e-pig.org/epilogue/?p=857"><code class="url">http://www.e-pig.org/epilogue/?p=857</code></a><a href="#fnref2">↩</a></p></li>
</ol>
</div>]]></description>
    <pubDate>Sat, 08 Sep 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-09-08-adding-universe-polymorphism.html</guid>
</item>
<item>
    <title>Natural Language Semantics: Montague → Martin-Löf</title>
    <link>http://www.jonmsterling.com/posts/2012-09-14-natural-language-semantics-I.html</link>
    <description><![CDATA[<p>My great joy at finally taking logical semantics for natural language at Berkeley was a bit dampened by the realization that everyone is still doing semantics in a type theory from the 1940s. Rather than wallowing in dismay, I have been inspired to think about manifesting semantics in a modern Constructive theory within the Martin-Löf tradition;<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> this is the first in a series of posts in that vein.</p>
<!--MORE-->

<h2 id="basics-the-sadly-typed-lambda-calculus">Basics: The Sadly Typed Lambda Calculus</h2>
<p>NL-semantics in the Montague tradition is typically done within a simply-typed lambda calculus, combined with some fast-and-loose subset-predicate stuff. I’ll try to avoid the nasty bits and just show you the context you need in order to understand what we’re doing. Let’s draw out the grammar and typing rules:</p>
<p><span class="math">$\begin{align} \text{types} &amp;::= e,\ t,\ \langle \text{type}, \text{type} \rangle \tag{Grammar}\\ \text{connectives} &amp;::= \forall,\ \exists,\ \land,\ \lor,\ \lnot\\ \text{operators} &amp;::= \lambda,\ \iota \end{align}$</span></p>
<blockquote>
<p><span class="math"><em>e</em></span> is the type of entities, and <span class="math"><em>t</em></span> is the type of propositions; <span class="math">⟨<em>e</em>, <em>t</em>⟩</span> is a function from entities to propositions. Function types are written thus in angle-brackets as comma-separated lists of types, with the comma associating to the right. <span class="math"><em>λ</em></span> is the primative abstraction operator, and <span class="math"><em>ι</em></span> is the primitive singleton-inference operator.</p>
</blockquote>
<p>In extensional semantics, <span class="math"><em>t</em></span> is just a truth value; in an intensional theory (which would seem to be necessary for reasons including the existence of hypotheticals and mood in language), <span class="math"><em>t</em></span> can be thought of as the set of all worlds in which some proposition holds true.</p>
<p>Typing rules are pretty straight-forward, given a context of type-assumptions <span class="math">Γ </span> (basically a list of values and their types).</p>
<p><span class="math">$\begin{align} \frac{\Gamma, x:\sigma \vdash M:\tau} {\Gamma \vdash \lambda x.M : \langle\sigma,\tau\rangle} \tag{T-abstraction} \end{align}$</span></p>
<blockquote>
<p>For some <span class="math"><em>x</em>: <em>σ</em></span> and <span class="math"><em>M</em>: <em>τ</em></span> (where the body of <span class="math"><em>M</em></span> may contain <span class="math"><em>x</em></span>), the lambda abstraction <span class="math"><em>λ</em><em>x</em>. <em>M</em></span> is a function of type <span class="math">⟨<em>σ</em>, <em>τ</em>⟩</span>.</p>
</blockquote>
<p><span class="math">$\begin{align} \frac{\Gamma, f : \langle\sigma,\tau\rangle \vdash x : \sigma} {\Gamma \vdash f(x) : \tau} \tag{T-application} \end{align}$</span></p>
<blockquote>
<p>The application of a function <span class="math"><em>f</em>: ⟨<em>σ</em>, <em>τ</em>⟩</span> on a value <span class="math"><em>x</em>: <em>σ</em></span> is <span class="math"><em>f</em>(<em>x</em>): <em>τ</em></span>.</p>
</blockquote>
<p><span class="math">$\begin{align} \frac{\Gamma, x:e \vdash P : \langle e,t\rangle} {\Gamma\vdash \iota x.P(x) : e} \tag{T-inference} \end{align}$</span></p>
<blockquote>
<p>For a predicate <span class="math"><em>P</em>: ⟨<em>e</em>, <em>t</em>⟩</span> which is satisfied by only one entity, the inference <span class="math"><em>ι</em><em>x</em>. <em>P</em>(<em>x</em>)</span> is that entity.</p>
</blockquote>
<p>So under this framework, common nouns, adjectives and intransitive verbs are of type <span class="math">⟨<em>e</em>, <em>t</em>⟩</span>, whereas individuals (like “Tucker” and 42) are of type <span class="math"><em>e</em></span>. The <span class="math"><em>ι</em></span>-operator is used to map these <span class="math">⟨<em>e</em>, <em>t</em>⟩</span> predicates to the contextually relevant value; if there are multiple (or zero) values in context that satisfy <span class="math"><em>P</em></span>, the derivation of <span class="math"><em>ι</em><em>x</em>. <em>P</em>(<em>x</em>)</span> will crash. So, the following are logical representations of words and phrases in this framework:</p>
<p><span class="math">$\begin{align} ⟦\text{dog}⟧ &amp;= \lambda x.\ \text{‘}x \text{ is a dog’} &amp;&amp;: \langle e,t\rangle\\ ⟦\text{the}⟧ &amp;= \lambda P. \iota x. P(x) &amp;&amp;: \langle\langle e,t\rangle,e\rangle\\ ⟦\text{the}⟧(⟦\text{dog}⟧) &amp;= \iota x.\ ⟦\text{dog}⟧(x)&amp;&amp;: e\\ ⟦\text{love}⟧ &amp;= \lambda x. \lambda y.\ \text{‘}y \text{ loves } x\text{’} &amp;&amp;: \langle e,e,t\rangle \end{align}$</span></p>
<p>And so forth. In this representation, note that we define primitive predicates using an existing token in the metalanguage (in this case, English); it could have Greek or Latin.</p>
<h2 id="semantics-in-a-modern-tt-shifted-up-a-level">Semantics in a Modern TT: Shifted Up a Level</h2>
<p>In modern type theory, we have to sort of rejigger things a bit. The new world order is that simple nouns (formerly <span class="math">⟨<em>e</em>, <em>t</em>⟩</span>) are actually just types; so, rather than saying <span class="math">⟦dog⟧(<em>x</em>)</span>, we now say <span class="math"><em>x</em>: ⟦dog⟧</span>. We’ve actually hoisted most of our machinery into the type-level; under the Curry-Howard Correspondence, types are propositions, and terms are proofs of those propositions.</p>
<p>In our intensional interpretation of natural language semantics, then, different proofs will exist in different worlds; so, in all worlds, there is a proposition <span class="math"><em>P</em></span>, but it will be provable in only some subset of worlds. So, to interpret the truth-value of a <span class="math"><em>P</em></span> in some world, we are really trying to see if there exists a term of type <span class="math"><em>P</em></span> in that world. In a later post, I’ll talk about ways that we can express the concept of multiple worlds in the new framework.</p>
<p>Actual predicates are types indexed by values (so-called <span class="math">∏ </span>-types); values of a predicate type are proofs that the saturated predicate (proposition) holds. Modification of predicates (as in “heavy book”) is done using <span class="math">∑ </span>-types.<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup></p>
<p>To avoid getting mired in words, we can very simply encode this in <a href="http://wiki.portal.chalmers.se/agda/pmwiki.php">Agda</a>, a dependently-typed programming language with a few features that will prove very useful to us.</p>
<h2 id="agda-lets-formalize-our-semantics">Agda: Let’s Formalize Our Semantics</h2>
<p>Today, we’ll only show how to represent what we have currently demonstrated for the Montague-style theory. For those of you who don’t have much programming experience (let alone experience with Agda), I’ll try to leave helpful comments as we go. Let’s get started!</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell"><span class="kw">module</span> <span class="dt">Semantics</span> <span class="kw">where</span></code></pre>
<p>We have a type for cats; in this context, there is only one cat. We’ll be using <code>⟦double-brackets⟧</code> for values which are referring to a word or phrase.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">  <span class="kw">data</span> ⟦cat⟧ <span class="fu">:</span> <span class="dt">Set</span> <span class="kw">where</span>
    ⟦Emma⟧ <span class="fu">:</span> ⟦cat⟧</code></pre>
<p>Our first order of business is to show how we can derive “the”.</p>
<p>First, we need to define propositional equality. Agda’s standard library actually has this built-in, but we’ll define it for ourselves so that we can see how it works.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">  <span class="kw">data</span> _≡_ {<span class="dt">A</span> <span class="fu">:</span> <span class="dt">Set</span>} <span class="fu">:</span> <span class="dt">A</span> <span class="ot">→</span> <span class="dt">A</span> <span class="ot">→</span> <span class="dt">Set</span> <span class="kw">where</span>
    refl <span class="fu">:</span> {x <span class="fu">:</span> <span class="dt">A</span>} <span class="ot">→</span> x ≡ x</code></pre>
<p>The <span class="math"><em>ι</em></span> operator can be seen as a proposition that for some proposition <span class="math"><em>P</em></span>, there is one-and-only-one proof (or, in other words, only one term inhabits type <span class="math"><em>P</em></span>).</p>
<p>A proof that a set <span class="math"><em>P</em></span> is singleton would consist of the single proof <span class="math"><em>x</em></span>, and a proof that all proofs of <span class="math"><em>P</em></span> are equal to <span class="math"><em>x</em></span>; that’s a pair, in which the second item (a function from a value to a proof that it is unique in some set <span class="math"><em>P</em></span>) is dependent upon the first item, which is the value which we’re trying to prove is the only inhabitant of <span class="math"><em>P</em></span>. This is a perfect use for a <span class="math">∑ </span>-type! Let’s define what that is:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">  record ∑ (<span class="dt">A</span> <span class="fu">:</span> <span class="dt">Set</span>) (<span class="dt">B</span> <span class="fu">:</span> <span class="dt">A</span> <span class="ot">→</span> <span class="dt">Set</span>) <span class="fu">:</span> <span class="dt">Set1</span> <span class="kw">where</span>
    constructor _,_
    field
      <span class="fu">fst</span> <span class="fu">:</span> <span class="dt">A</span>
      <span class="fu">snd</span> <span class="fu">:</span> <span class="dt">B</span> <span class="fu">fst</span></code></pre>
<p>We can define some syntactic sugar to make this a little easier to use:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">  syntax ∑ <span class="dt">A</span> (λ x <span class="ot">→</span> <span class="dt">B</span>) <span class="fu">=</span> ∑[ x ∶ <span class="dt">A</span> ] <span class="dt">B</span></code></pre>
<p>And so, a singleton-proof is just a specific instantiation of <span class="math">∑ </span>:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">  <span class="dt">Singleton</span> <span class="fu">:</span> <span class="dt">Set</span> <span class="ot">→</span> <span class="dt">Set1</span>
  <span class="dt">Singleton</span> <span class="dt">P</span> <span class="fu">=</span>  ∑[ x ∶ <span class="dt">P</span> ] (<span class="ot">∀</span> y <span class="ot">→</span> y ≡ x)</code></pre>
<blockquote>
<p>“For some proof <span class="math"><em>x</em></span> of <span class="math"><em>P</em></span>, every proof <span class="math"><em>y</em></span> of <span class="math"><em>P</em></span> is equal to <span class="math"><em>x</em></span>.” In other words, <span class="math"><em>x</em></span> is the only proof of <span class="math"><em>P</em></span>.</p>
</blockquote>
<p>Using the <code>_,_</code> constructor from <span class="math">∑ </span>, we can make a proof that <code>⟦cat⟧</code> is a singleton set:</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">  cat<span class="fu">-</span>singleton <span class="fu">:</span> <span class="dt">Singleton</span> ⟦cat⟧
  cat<span class="fu">-</span>singleton <span class="fu">=</span> ⟦Emma⟧ , λ { ⟦Emma⟧ <span class="ot">→</span> refl }</code></pre>
<p>We now have enough machinery to define the ι operator. Because we want to <em>infer</em> the proof that <code>P</code> is a singleton, we place that parameter in double-curly-braces; this is called an “instance argument” in Agda. If we did not do this, we would have to provide a proof that <code>P</code> is a singleton with every use of ι.</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">  ι <span class="fu">:</span> (<span class="dt">P</span> <span class="fu">:</span> <span class="dt">Set</span>) <span class="ot">→</span> {{proof <span class="fu">:</span> <span class="dt">Singleton</span> <span class="dt">P</span>}} <span class="ot">→</span> <span class="dt">P</span>
  ι _ {{x , _}} <span class="fu">=</span> x</code></pre>
<!--_-->
<p>It turns out that <code>⟦the⟧</code> is actually the exact same thing as <span class="math"><em>ι</em></span>!</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">  ⟦the⟧ <span class="fu">:</span> (<span class="dt">P</span> <span class="fu">:</span> <span class="dt">Set</span>) <span class="ot">→</span> {{proof <span class="fu">:</span> <span class="dt">Singleton</span> <span class="dt">P</span>}} <span class="ot">→</span> <span class="dt">P</span>
  ⟦the⟧ <span class="fu">=</span> ι</code></pre>
<p>And now, to let all our hard work pay off, we can show that ⟦the⟧ really does work as we had hoped!</p>
<pre class="sourceCode Haskell"><code class="sourceCode haskell">  ⟦the<span class="fu">-</span>cat⟧ <span class="fu">:</span> ⟦cat⟧
  ⟦the<span class="fu">-</span>cat⟧ <span class="fu">=</span> ⟦the⟧ ⟦cat⟧</code></pre>
<p>If <code>⟦cat⟧</code> had been inhabited by more values, the program would have failed to typecheck (since it would have been impossible to construct a proof that <code>⟦cat⟧</code> is a singleton).</p>
<h2 id="next-steps">Next steps</h2>
<p>Some things that still need to be discussed in a future post:</p>
<ol style="list-style-type: decimal">
<li><p>How can we unify our new view of semantics with the possible-worlds interpretation? How can we assert a “world-signature” (that says what kind of types and propositions we have), but allow the specific available theorems to differ from world-to-world?</p></li>
<li><p>How can we coerce a function of a more general type to a more specific type? For instance, “eat” might be represented by a type: <code>⟦animal⟧ → ⟦food⟧ → Set</code>, but it should be possible to treat it as a function <code>⟦cat⟧ → ⟦tuna⟧ → Set</code>. (For more on this, see Luo’s paper in the notes.)</p></li>
</ol>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>After I’d written this, I came across this awesome little paper, <a href="http://www.cs.rhul.ac.uk/~zhaohui/SALT20.pdf">Type-theoretical semantics with coercive subtyping</a> that, in addition to making a pretty convincing case for subtyping in the type theories used to encode formal semantics, also explains quite nicely some of the elementaries which I may gloss over; if you have no background in modern Type Theory, I suggest you read over at least Section 2. Note that my technique differs from that described in the paper, in that I do not have a separate kind <code>Prop</code> from <code>Set</code> (which is the type of small types).<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>I hate to toot on my own horn, but if you need to read up on <span class="math">∏ </span> and <span class="math">∑ </span>-types, I have written a <a href="http://www.jonmsterling.com/posts/2012-09-07-pi-is-for-power-sigma-for-product.html">few</a> <a href="http://www.jonmsterling.com/posts/2012-09-08-adding-universe-polymorphism.html">things</a> about those previously that may be helpful.<a href="#fnref2">↩</a></p></li>
</ol>
</div>]]></description>
    <pubDate>Fri, 14 Sep 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-09-14-natural-language-semantics-I.html</guid>
</item>
<item>
    <title>Dependent Types Today: Faking It With Style</title>
    <link>http://www.jonmsterling.com/posts/2012-11-10-faking-it-with-style.html</link>
    <description><![CDATA[<p>There have been various attempts at faking dependent types in Haskell, most notably Conor McBride’s <a href="https://personal.cis.strath.ac.uk/~conor/pub/she/">Strathclyde Haskell Enhancement</a>. Since its creation, several improvements to GHC have set the stage for some of SHE’s features to be implemented natively.</p>
<p>Let’s see what’s necessary to fake dependent types with singletons in today’s GHC.</p>
<!--MORE-->
<p>First, the usual boilerplate:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE NoMonomorphismRestriction #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE ScopedTypeVariables #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE PolyKinds, DataKinds #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE TypeOperators #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE UndecidableInstances, IncoherentInstances #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE FlexibleContexts, FlexibleInstances #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE ViewPatterns, UnicodeSyntax #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE RankNTypes, GADTs #-}</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">module</span> <span class="dt">FakingIt</span> <span class="kw">where</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Prelude</span> <span class="kw">hiding</span> (<span class="fu">lookup</span>)
<span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">GHC.TypeLits</span></code></pre>
<p>Now, in order to simulate dependent types, we need to allow data to exist in three forms:</p>
<ol style="list-style-type: decimal">
<li><p>Terms under types (we get this for free when we define data types).</p></li>
<li><p>Terms under kinds (we also get this for free when <code>-XDataKinds</code> is turned on).</p></li>
<li><p>Values that introduce indexed types (we must manually create or generate a GADT encoding of singleton sets). This is a sort of glue between the first two encodings.</p></li>
</ol>
<p>Let’s see how this works in practice! We’ll start, as always, with a type of dogs:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">Doggy</span> <span class="fu">=</span> <span class="dt">Tucker</span> <span class="fu">|</span> <span class="dt">Rover</span></code></pre>
<p>We have introduced a type <code>Doggy</code> inhabited by two terms at the value-level; we have also introduced a kind <code>'Doggy</code> inhabited by two terms at the type level. Now, we could create the “glue” GADT as follows:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">SDoggy</span><span class="ot"> ::</span> <span class="dt">Doggy</span> <span class="ot">→</span> <span class="fu">*</span> <span class="kw">where</span>
  <span class="dt">STucker</span><span class="ot"> ::</span> <span class="dt">SDoggy</span> <span class="dt">Tucker</span>
  <span class="dt">SRover</span><span class="ot">  ::</span> <span class="dt">SDoggy</span> <span class="dt">Rover</span></code></pre>
<p>But GHC provides a <code>Sing</code> type family under which we should create our singleton sets; this allows us to use some built-in machinery, like <code>sing</code> which allows one to infer the right singleton value for a known type. So, we’ll do the following:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="kw">instance</span> <span class="dt">Sing</span> (<span class="ot">d ::</span> <span class="dt">Doggy</span>) <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">STucker</span><span class="ot"> ::</span> <span class="dt">Sing</span> <span class="dt">Tucker</span>
<span class="fu">&gt;</span>   <span class="dt">SRover</span><span class="ot">  ::</span> <span class="dt">Sing</span> <span class="dt">Rover</span></code></pre>
<p>We’ll need to help out with the inference instances:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">SingI</span> <span class="dt">Tucker</span> <span class="kw">where</span> sing <span class="fu">=</span> <span class="dt">STucker</span>
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">SingI</span> <span class="dt">Rover</span>  <span class="kw">where</span> sing <span class="fu">=</span> <span class="dt">SRover</span></code></pre>
<p>And finally, we need to provide conversion from the singleton type to the plain-old-value type:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">SingE</span> (<span class="dt">Kind</span><span class="ot"> ::</span> <span class="dt">Doggy</span>) <span class="dt">Doggy</span> <span class="kw">where</span>
<span class="fu">&gt;</span>   fromSing <span class="dt">STucker</span> <span class="fu">=</span> <span class="dt">Tucker</span>
<span class="fu">&gt;</span>   fromSing <span class="dt">SRover</span>  <span class="fu">=</span> <span class="dt">Rover</span></code></pre>
<p>It’s clear what this does, but it might not be immediately obvious what the <code>(Kind :: Doggy)</code> business is. Basically, Haskell does not currently allow one to abstract over kinds in a straight-forward way. Since we’re basically trying to make a map from kinds to types (that is, from the kind which <code>-XDataKinds</code> generated to the type whence it arose), we need to pass the kind in as the annotation to a dummy type; in this case, we use <code>Kind</code>, which is provided by <code>GHC.TypeLits</code>, and has no actual meaning by itself.</p>
<p>As you can see, all this boilerplate could in fact be generated with Template Haskell. In fact, the <a href="http://hackage.haskell.org/package/singletons">Singletons</a> package already does so, but it does not use GHC’s built-in kit, so there’s a bit of unhappiness there.</p>

<blockquote>
<strong>Update</strong>: The Singletons package has been updated, and is now compatible with TypeLits.
</blockquote>


<h2 id="singletons-for-higher-order-types">Singletons for Higher Order Types</h2>
<p>Before we get started, now would be a good time to introduce some naughty little shorthands that will make our code a bit less noisy:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> Π <span class="fu">=</span> <span class="dt">Sing</span>
<span class="fu">&gt;</span> π <span class="fu">=</span> fromSing</code></pre>
<p>The capital <code>Π</code> adds a bit of swagger to our dependent function types. Combined with <code>-XViewPatterns</code>, <code>π</code> lets us pattern match on singleton parameters.</p>
<p>The procedure for higher order types (like lists, pairs, etc.) is basically the same as the above. Just a bit more involved; we’ll start with lists:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="kw">instance</span> <span class="dt">Sing</span> (<span class="ot">xs ::</span> [k]) <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">SNil</span><span class="ot"> ::</span> <span class="dt">Sing</span> <span class="ch">&#39;[]</span>
<span class="fu">&gt;</span>   <span class="dt">SCons</span><span class="ot"> ::</span> Π (<span class="ot">x ::</span> k) <span class="ot">→</span> Π (<span class="ot">xs ::</span> [k]) <span class="ot">→</span> <span class="dt">Sing</span> (s <span class="ch">&#39;: xs)</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">SingI</span> <span class="ch">&#39;[] where sing = SNil</span>
<span class="fu">&gt;</span> <span class="kw">instance</span> (<span class="dt">SingI</span> x, <span class="dt">SingI</span> xs) <span class="ot">⇒</span> <span class="dt">SingI</span> (x <span class="ch">&#39;: xs) where</span>
<span class="fu">&gt;</span>   sing <span class="fu">=</span> <span class="dt">SCons</span> (<span class="ot">sing ::</span> <span class="dt">Sing</span> x) (<span class="ot">sing ::</span> <span class="dt">Sing</span> xs)</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">SingE</span> (<span class="dt">Kind</span><span class="ot"> ::</span> k) r <span class="ot">⇒</span> <span class="dt">SingE</span> (<span class="dt">Kind</span><span class="ot"> ::</span> [k]) [r] <span class="kw">where</span>
<span class="fu">&gt;</span>   fromSing <span class="dt">SNil</span> <span class="fu">=</span> []
<span class="fu">&gt;</span>   fromSing (<span class="dt">SCons</span> x xs) <span class="fu">=</span> fromSing x <span class="fu">:</span> fromSing xs</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="kw">instance</span> <span class="dt">Sing</span> (<span class="ot">p ::</span> (a,b)) <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">SPair</span><span class="ot"> ::</span> <span class="dt">Sing</span> a <span class="ot">→</span> <span class="dt">Sing</span> b <span class="ot">→</span> <span class="dt">Sing</span> <span class="ch">&#39;(a,b)</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> (<span class="dt">SingE</span> (<span class="dt">Kind</span><span class="ot"> ::</span> a) x, <span class="dt">SingE</span> (<span class="dt">Kind</span><span class="ot"> ::</span> b) y) <span class="ot">⇒</span>
<span class="fu">&gt;</span>          <span class="dt">SingE</span> (<span class="dt">Kind</span><span class="ot"> ::</span> (a,b)) (x,y) <span class="kw">where</span>
<span class="fu">&gt;</span>   fromSing (<span class="dt">SPair</span> x y) <span class="fu">=</span> (fromSing x, fromSing y)
<span class="fu">&gt;</span> <span class="kw">instance</span> (<span class="dt">SingI</span> k, <span class="dt">SingI</span> v) <span class="ot">⇒</span> <span class="dt">SingI</span> <span class="ch">&#39;(k,v) where</span>
<span class="fu">&gt;</span>   sing <span class="fu">=</span> <span class="dt">SPair</span> sing sing</code></pre>
<h2 id="sigma-types-yes-we-can-to-a-point">Sigma Types: Yes, We Can (to a point)</h2>
<p>Consider the following definition, adapted from <code>Data.Products</code> in the Agda standard library:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">record Σ {a b} (<span class="dt">A</span> <span class="fu">:</span> <span class="dt">Set</span> a) (<span class="dt">B</span> <span class="fu">:</span> <span class="dt">A</span> <span class="ot">→</span> <span class="dt">Set</span> b) <span class="fu">:</span> <span class="dt">Set</span> (a ⊔ b) <span class="kw">where</span>
  construct _,_
  field
    proj₁ <span class="fu">:</span> <span class="dt">A</span>
    proj₂ <span class="fu">:</span> <span class="dt">B</span> proj₁</code></pre>
<p>This is the classic definition of a <a href="http://www.jonmsterling.com/posts/2012-09-07-pi-is-for-power-sigma-for-product.html">dependent sum</a> in Agda. Basically, the first field is a type of some sort, and the second field is a proof that that type satisfies some predicate. Minus the record accessor sugar, the constructor <code>_,_</code> comes out as the following:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> Σ {a b} (<span class="dt">A</span> <span class="fu">:</span> <span class="dt">Set</span> a) (<span class="dt">B</span> <span class="fu">:</span> <span class="dt">A</span> <span class="ot">→</span> <span class="dt">Set</span> b) <span class="fu">:</span> <span class="dt">Set</span> (a ⊔ b) <span class="kw">where</span>
  _,_ <span class="fu">:</span> (proj₁ <span class="fu">:</span> <span class="dt">A</span>) <span class="ot">→</span> <span class="dt">B</span> proj₁ <span class="ot">→</span> Σ <span class="dt">A</span> <span class="dt">B</span></code></pre>
<p>We would hope to be able to create something analogous in Haskell under the limited encoding of dependent types possible using singletons.</p>
<p>Now, as you can see, the Agda version is very flexible in terms of the sorts of things it can quantify, because of its use of <a href="http://www.jonmsterling.com/posts/2012-09-08-adding-universe-polymorphism.html">universe polymorphism</a>. Now, we can’t hope for anything quite as profound in Haskell; we’ll settle for having the second parameter be a predicate over terms of some kind, which is supplied in the first parameter.</p>
<p>We can now create the following definition:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> Σ (<span class="ot">kind ::</span> k) (<span class="fu">pred</span><span class="ot"> ::</span> k <span class="ot">→</span> <span class="fu">*</span>) <span class="kw">where</span>
<span class="ot">  (:|-) ::</span> Π (<span class="ot">x ::</span> k) <span class="ot">→</span> <span class="fu">pred</span> x <span class="ot">→</span> Σ kind <span class="fu">pred</span></code></pre>
<p>Note that this is equivalent to the following (minus our little <code>Π</code> shorthand which we use in the spirit of dependent types):</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> Σ (<span class="ot">kind ::</span> k) (<span class="fu">pred</span><span class="ot"> ::</span> k <span class="ot">→</span> <span class="fu">*</span>) <span class="kw">where</span>
<span class="ot">  (:|-) ::</span> <span class="dt">Sing</span> x <span class="ot">→</span> <span class="fu">pred</span> x <span class="ot">→</span> Σ kind <span class="fu">pred</span></code></pre>
<p>Last, we put the final touches on by making this into a record:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> Σ (<span class="ot">kind ::</span> k) (<span class="fu">pred</span><span class="ot"> ::</span> k <span class="ot">→</span> <span class="fu">*</span>) <span class="kw">where</span>
<span class="fu">&gt;</span><span class="ot">   (:|-) ::</span> { proj₁ <span class="ot">::</span> Π (<span class="ot">x ::</span> k), proj₂ <span class="ot">::</span> <span class="fu">pred</span> x } <span class="ot">→</span> Σ kind <span class="fu">pred</span></code></pre>
<p>Since in most cases, the kind over which the predicate operates is inferrable from the predicate itself, we provide the following convenience synonym:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> <span class="dt">Exists</span> (<span class="fu">pred</span><span class="ot"> ::</span> k <span class="ot">→</span> <span class="fu">*</span>) <span class="fu">=</span> Σ <span class="dt">Kind</span> <span class="fu">pred</span></code></pre>
<p>So, we could, for instance, make a function that takes a number which is not one:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">NotOne</span><span class="ot"> ::</span> <span class="dt">Nat</span> <span class="ot">→</span> <span class="fu">*</span> <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">NotOneZ</span><span class="ot"> ::</span> <span class="dt">NotOne</span> <span class="dv">0</span>
<span class="fu">&gt;</span>   <span class="dt">NotOneSS</span><span class="ot"> ::</span> <span class="dt">NotOne</span> (n <span class="fu">+</span> <span class="dv">2</span>)</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> cantTakeOne ::</span> <span class="kw">Fractional</span> t <span class="ot">⇒</span> <span class="dt">Exists</span> <span class="dt">NotOne</span> <span class="ot">→</span> t
<span class="fu">&gt;</span> cantTakeOne ((π <span class="ot">→</span> n) <span class="fu">:|-</span> _) <span class="fu">=</span> <span class="fl">10.0</span> <span class="fu">/</span> (<span class="fu">fromInteger</span> n <span class="fu">-</span> <span class="dv">1</span>)</code></pre>
<p>We can also show that our Haskell encoding really is similar to the Agda version by providing our own version of the encoding of cartesian products (remember, a cartesian product arises when the predicate ignores its parameter).</p>
<p>If it were possible to have type-level lambdas in Haskell, then this would be just as simple as in Agda:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">type</span> x <span class="fu">&amp;</span> y <span class="fu">=</span> Σ x (λ _ <span class="ot">→</span> y)</code></pre>
<p>Unfortunately, we must actually provide a little bit of indirection to get around this limitation:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> x <span class="fu">&amp;</span> y <span class="fu">=</span> Σ x (<span class="dt">Const</span> y)
<span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">Const</span><span class="ot"> ::</span> l <span class="ot">→</span> k <span class="ot">→</span> <span class="fu">*</span> <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">Const</span><span class="ot"> ::</span> Π (<span class="ot">x ::</span> l) <span class="ot">→</span> <span class="dt">Const</span> (<span class="dt">Kind</span><span class="ot"> ::</span> l) y</code></pre>
<p>As such, to hide away the <code>Const</code> indirection, we’ll need to provide our own constructors and eliminators for products:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> (&amp;) ::</span> Π (<span class="ot">x ::</span> l) <span class="ot">→</span> Π (<span class="ot">y ::</span> k) <span class="ot">→</span> (<span class="dt">Kind</span><span class="ot"> ::</span> l) <span class="fu">&amp;</span> (<span class="dt">Kind</span><span class="ot"> ::</span> k)
<span class="fu">&gt;</span> x <span class="fu">&amp;</span> y <span class="fu">=</span> x <span class="fu">:|-</span> <span class="dt">Const</span> y</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> prodElim ::</span> <span class="dt">SingI</span> pair <span class="ot">⇒</span> (<span class="dt">Kind</span><span class="ot"> ::</span> l) <span class="fu">&amp;</span> (<span class="dt">Kind</span><span class="ot"> ::</span> k) <span class="ot">→</span> <span class="dt">Sing</span> (<span class="ot">pair ::</span> (l,k))
<span class="fu">&gt;</span> prodElim _ <span class="fu">=</span> sing</code></pre>
<p>Looks like our kit should be sufficient to make a pair of dogs:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> dawgFriends <span class="fu">=</span> <span class="dt">STucker</span> <span class="fu">&amp;</span> <span class="dt">SRover</span></code></pre>
<h3>
A dependent head function over lists
</h3>

<p>There are several common ways to make a safe <code>head</code> function, many of which I have discussed in the past. Some of these involve having the function operate on lists which are non-empty by construction (using a length-indexed vector, or a list type which has no nil). If our list, however, exists at both the value and the type levels, we can just predicate over it without changing the structure of the list itself. Consider the following <code>NonEmpty</code> predicate:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">NonEmpty</span><span class="ot"> ::</span> [k] <span class="ot">→</span> <span class="fu">*</span> <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">NonEmpty</span><span class="ot"> ::</span> <span class="dt">NonEmpty</span> (x <span class="ch">&#39;: xs)</span></code></pre>
<p>We can provide this as the predicate to our dependent sum!</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> safeHead ::</span> <span class="dt">SingE</span> (<span class="dt">Kind</span><span class="ot"> ::</span> k) r <span class="ot">⇒</span> Σ (<span class="dt">Kind</span><span class="ot"> ::</span> [k]) <span class="dt">NonEmpty</span> <span class="ot">→</span> r
<span class="fu">&gt;</span> safeHead ((π <span class="ot">→</span> x <span class="fu">:</span> _) <span class="fu">:|-</span> _) <span class="fu">=</span> x</code></pre>
<p>Note that we used a combination of <code>-XViewPatterns</code> and our little <code>π</code> shorthand to pattern match on the value-level reflection of the list. This definition is equivalent to the following:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">safeHead ((<span class="dt">SCons</span> x xs) <span class="fu">:|-</span> _) <span class="fu">=</span> fromSing x</code></pre>
<h3>
Safe Dictionary Lookup
</h3>

<p>We can do much the same thing with dictionaries:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">HasKey</span><span class="ot"> ::</span> l <span class="ot">→</span> [(l,k)] <span class="ot">→</span> <span class="fu">*</span> <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="dt">KeyHere</span><span class="ot">  ::</span> <span class="dt">HasKey</span> k (<span class="ch">&#39;(k, v) &#39;</span><span class="fu">:</span> dict)
<span class="fu">&gt;</span>   <span class="dt">KeyThere</span><span class="ot"> ::</span> <span class="dt">HasKey</span> k dict <span class="ot">→</span> <span class="dt">HasKey</span> k (pair <span class="ch">&#39;: dict)</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> lookup ::</span> (<span class="dt">SingE</span> (<span class="dt">Kind</span><span class="ot"> ::</span> k) k&#39;, <span class="dt">SingE</span> (<span class="dt">Kind</span><span class="ot"> ::</span> v) v&#39;) <span class="ot">⇒</span>
<span class="fu">&gt;</span>           Π (<span class="ot">key ::</span> k) <span class="ot">→</span>
<span class="fu">&gt;</span>           Σ (<span class="dt">Kind</span><span class="ot"> ::</span> [(k,v)]) (<span class="dt">HasKey</span> key) <span class="ot">→</span> v&#39;
<span class="fu">&gt;</span> <span class="fu">lookup</span> _ ((π <span class="ot">→</span> (_,x) <span class="fu">:</span> _) <span class="fu">:|-</span> <span class="dt">KeyHere</span>)     <span class="fu">=</span> x
<span class="fu">&gt;</span> <span class="fu">lookup</span> k (<span class="dt">SCons</span> _ xs      <span class="fu">:|-</span> <span class="dt">KeyThere</span> hk) <span class="fu">=</span> <span class="fu">lookup</span> k (xs <span class="fu">:|-</span> hk)</code></pre>
<p>Of course, we can use the same trick as we always do by providing implicit proof terms:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">class</span> <span class="dt">Implicit</span> x <span class="kw">where</span>
<span class="fu">&gt;</span><span class="ot">   implicitly ::</span> x
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Implicit</span> (<span class="dt">HasKey</span> k (<span class="ch">&#39;(k,v) &#39;</span><span class="fu">:</span> dict)) <span class="kw">where</span>
<span class="fu">&gt;</span>   implicitly <span class="fu">=</span> <span class="dt">KeyHere</span>
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Implicit</span> (<span class="dt">HasKey</span> k dict) <span class="ot">⇒</span> <span class="dt">Implicit</span> (<span class="dt">HasKey</span> k (pair <span class="ch">&#39;: dict)) where</span>
<span class="fu">&gt;</span>   implicitly <span class="fu">=</span> <span class="dt">KeyThere</span> implicitly</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> lookup&#39; k dict <span class="fu">=</span> <span class="fu">lookup</span> k (dict <span class="fu">:|-</span> implicitly)</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> <span class="dt">DogNamesMap</span> <span class="fu">=</span> [<span class="ch">&#39;(Tucker, &quot;Tucker&quot;), &#39;</span>(<span class="dt">Rover</span>, <span class="st">&quot;Rover&quot;</span>)]
<span class="fu">&gt;</span> sDogNamesMap <span class="fu">=</span><span class="ot"> sing ::</span> <span class="dt">Sing</span> <span class="dt">DogNamesMap</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> tuckersName <span class="fu">=</span> <span class="fu">lookup</span> <span class="dt">STucker</span> (sDogNamesMap <span class="fu">:|-</span> <span class="dt">KeyHere</span>)
<span class="fu">&gt;</span> tuckersName&#39; <span class="fu">=</span> lookup&#39; <span class="dt">STucker</span> sDogNamesMap</code></pre>
<h2 id="caveats">Caveats</h2>
<p>That was fun! But this was mostly a demonstration to show that Σ-types are possible in Haskell, rather than a recommendation to use them. For one, it is a fair bit more complicated under this system to allow such functions to operate on dynamic data (which may or may not satisfy the static predicate), than under the system I proposed in <a href="http://www.jonmsterling.com/posts/2012-08-05-static-and-dynamic-proof-inference-in-haskell.html">my previous post</a>.</p>
<p>Another thing which makes the singleton-encoding of dependent types rather unpleasant to use is the fact that whilst we can pretty easily reflect data up and down the ladder of universes, it’s rather more difficult to do the same with functions in a general way. So (at least today), you would have to write all your functions over such data as type families, and then reflect that down to the value level. This is probably possible, but it is indeed quite a lot to ask.</p>
<p>I’m hoping that the situation will continue to improve, though! GHC 7.6 finally made it possible (though not particularly pleasant) to do non-trivial kind abstraction. It is of great interest to me to see what is improved next.</p>
<p>Thanks for playing along!</p>]]></description>
    <pubDate>Sat, 10 Nov 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-11-10-faking-it-with-style.html</guid>
</item>
<item>
    <title>Extensible Records in C++</title>
    <link>http://www.jonmsterling.com/posts/2012-11-23-extensible-records-in-cpp.html</link>
    <description><![CDATA[<p>In my view, <em>extensible records</em> are a rather good problem for gauging type system expressivity. I recently wrote an extensible records framework for Haskell called <a href="https://github.com/jonsterling/Vinyl">Vinyl</a>; today, I thought I would see what it would take to manifest something similar in C++.</p>
<!--MORE-->

<blockquote>
<p>To get started, <strong>extensible records</strong> just means a compositional approach to data structures, usually involving some kind of row polymorphism. So, given specifications for some record fields, we can get an expressive kind of static duck typing.</p>
</blockquote>
<h3 id="the-design">The Design</h3>
<p>I’d like to make a few specifications about the final product:</p>
<ol style="list-style-type: decimal">
<li><p>It should take no more than one line of code to define each field.</p></li>
<li><p>Types should be locally inferrable.</p></li>
<li><p>The names of fields should be available without API consumers ever dealing with strings.</p></li>
<li><p>It should be possible to access fields with normal dot-syntax.</p></li>
</ol>
<h3 id="the-implementation">The Implementation</h3>
<h4 id="field-representation">Field Representation</h4>
<p>First, we’ll want to have an idea of what a field is. Let’s consider fields to be structures which are composed into larger structures using multiple inheritance. So, given a field like the following:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="kw">struct</span> address { <span class="dt">char</span> <span class="dt">const</span> *address; };</code></pre>
<p><!-- *---> We’ll want to expose some metadata about it.</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="kw">template</span> &lt; <span class="kw">class</span> F         <span class="co">// the field structure (e.g. address)</span>
         , <span class="kw">class</span> T         <span class="co">// the field&#39;s type (e.g. const char*)</span>
         , T F::*ptr       <span class="co">// a path to the member (e.g. &amp;address::address)</span>
         , <span class="dt">char</span> <span class="dt">const</span> *sym <span class="co">// the field&#39;s name (e.g. &quot;address&quot;)</span>
         &gt;
<span class="kw">struct</span> Field {
    <span class="kw">typedef</span> T Type;
    <span class="dt">static</span> T F::*access()       { <span class="kw">return</span> ptr; }
    <span class="dt">static</span> <span class="dt">char</span> <span class="dt">const</span> *symbol() { <span class="kw">return</span> sym; }
};</code></pre>
<p>Making this metadata is quite simple:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="kw">extern</span> <span class="dt">char</span> <span class="dt">const</span> address_sym[] = <span class="st">&quot;address&quot;</span>;
<span class="kw">typedef</span> Field&lt;address, <span class="dt">char</span> <span class="dt">const</span>*, &amp;address::address, address_sym&gt; address_meta;</code></pre>
<!-- _--->

<blockquote>
<p><strong>Note</strong> that we cannot instantiate the string template parameter directly in C++; we must provide it in a symbol with external linkage.</p>
</blockquote>
<p>The problem now is twofold: first, we don’t want the user to have to enter in all this boilerplate, small as it is; secondly, we don’t have any way of deriving the metadata from the <code>address</code> struct itself. So, something a little bit more clever is called for!</p>
<p>Let’s make a static lookup-table:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="kw">template</span> &lt;<span class="kw">class</span> F&gt; <span class="kw">struct</span> FieldTable {};

<span class="kw">template</span> &lt;&gt;
<span class="kw">struct</span> FieldTable&lt;address&gt;
  : Field&lt;address, <span class="dt">const</span> <span class="dt">char</span>*, &amp;address::address, address_sym&gt;
{ };</code></pre>
<p>And so we will now be able to access metadata for some field <code>T</code> using only <code>FieldTable&lt;T&gt;</code>! Now we’re getting somewhere. Let’s automate that:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="ot">#define mk_field(T, sym) \</span>
    <span class="kw">extern</span> <span class="dt">char</span> <span class="dt">const</span> sym##_symbol[] = #sym;\
    <span class="kw">struct</span> sym { T sym; };\
    <span class="kw">template</span> &lt;&gt; <span class="kw">struct</span> FieldTable&lt;sym&gt; : Field&lt;sym, T, &amp;sym::sym, sym##_symbol&gt; {};</code></pre>
<h4 id="record-representation">Record Representation</h4>
<p>A record is a just a variadic class template, defined inductively:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="kw">template</span> &lt;<span class="kw">class</span>... rows&gt; <span class="kw">struct</span> Record;</code></pre>
<p><strong>The Base Case:</strong> The only thing we can do with an empty record is add something to it.</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="kw">template</span> &lt;&gt; <span class="kw">struct</span> Record&lt;&gt; {
    Record() { }

    <span class="kw">template</span> &lt;<span class="kw">class</span> f&gt;
    Record&lt;f&gt; insert(<span class="kw">typename</span> FieldTable&lt;f&gt;::Type val) <span class="dt">const</span> {
        Record&lt;g&gt; embiggened(*<span class="kw">this</span>); <span class="co">// make an enlarged record</span>
        embiggened.*(FieldTable&lt;f&gt;::access()) = val;
        <span class="kw">return</span> embiggened;
    }
}</code></pre>
<p><strong>The Inductive Step:</strong> Herein lies the central conceit. We end up inheriting from every single field in the parameter list; we do this recursively (by inheriting from <code>Record</code> instantiated at the tail of the current parameter list).</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="kw">template</span> &lt;<span class="kw">class</span> f, <span class="kw">class</span>... rows&gt;
<span class="kw">struct</span> Record&lt;f, rows...&gt; : f, Record&lt;rows...&gt;
{</code></pre>
<p>We need to enlarge records when inserting new fields. This is not entirely safe, but the presence of <code>null</code> in C++ means that it doesn’t make much of a difference.</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    Record (<span class="dt">const</span> Record&lt;rows...&gt;&amp; smaller) : Record&lt;rows...&gt;(smaller) { }</code></pre>
<p>Our implementation for <code>insert</code> here is mostly the same as the one for the empty record; the type’s a tad different, though.</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">class</span> g&gt;
    Record&lt;g,f,rows...&gt; insert(<span class="kw">typename</span> FieldTable&lt;g&gt;::Type val) <span class="dt">const</span> {
        Record&lt;g,f,rows...&gt; embiggened(*<span class="kw">this</span>);
        embiggened.*(FieldTable&lt;g&gt;::access()) = val;
        <span class="kw">return</span> embiggened;
    }</code></pre>
<p>We allow the construction of a new record with the value to one field changed.</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">class</span> g&gt;
    Record set(<span class="kw">typename</span> FieldTable&lt;g&gt;::Type val) <span class="dt">const</span> {
        Record copy(*<span class="kw">this</span>);
        copy.*(FieldTable&lt;g&gt;::access()) = val;
        <span class="kw">return</span> copy;
    }</code></pre>
<p>We can also just pass in a function to modify the value:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">class</span> T&gt;
    <span class="kw">using</span> Endomorphism = std::function&lt;T(T)&gt;;

    <span class="kw">template</span> &lt;<span class="kw">class</span> g&gt;
    Record modify(Endomorphism&lt;<span class="kw">typename</span> FieldTable&lt;g&gt;::Type&gt; func) <span class="dt">const</span> {
        <span class="dt">auto</span> value = func(<span class="kw">this</span>-&gt;*(FieldTable&lt;g&gt;::access()));
        <span class="kw">return</span> set&lt;g&gt;(value);
    }
}</code></pre>
<h3 id="pretty-printing">Pretty Printing</h3>
<p>The fact that we provide the field’s name in our static metadata will come in handy now! It is the case that all records can be shot through an <code>std::ostream</code>!</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">std::ostream&amp; <span class="kw">operator</span>&lt;&lt;(std::ostream&amp; stream, <span class="dt">const</span> Record&lt;&gt;&amp; empty) {
    <span class="kw">return</span> stream &lt;&lt; <span class="st">&quot;{}&quot;</span>;
}

<span class="kw">template</span> &lt;<span class="kw">class</span> f, <span class="kw">class</span>... rows&gt;
std::ostream&amp; <span class="kw">operator</span>&lt;&lt;(std::ostream&amp; stream, <span class="dt">const</span> Record&lt;f, rows...&gt;&amp; record) {
    Record&lt;rows...&gt; smaller = record;
    <span class="kw">typedef</span> FieldTable&lt;f&gt; field;
    <span class="kw">return</span> stream &lt;&lt; field::symbol() &lt;&lt; <span class="st">&quot; : &quot;</span> &lt;&lt; record.*(field::access()) &lt;&lt; <span class="st">&quot;, &quot;</span> &lt;&lt; smaller;
}</code></pre>
<h3 id="test-drive">Test Drive</h3>
<p>We can play with the machinery we built now. Let’s first define a few fields:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">mk_field(<span class="dt">char</span> <span class="dt">const</span>*, name);
mk_field(<span class="dt">char</span> <span class="dt">const</span>*, favorite_food);
mk_field(<span class="dt">int</span>, age);</code></pre>
<p>We could even have put these in a namespace for extra safety. We can of course express a generic function which increments the <code>age</code> of any record which has that field:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="kw">template</span> &lt;<span class="kw">class</span> R&gt;
R tick_tock(R <span class="dt">const</span>&amp; rec) {
    <span class="kw">return</span> rec.<span class="kw">template</span> modify&lt;age&gt;([](<span class="dt">int</span> i) { <span class="kw">return</span> i + <span class="dv">1</span>; });
}</code></pre>
<p>Let’s try making up some records now:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="dt">void</span> test_records() {
    <span class="dt">const</span> Record&lt;&gt; empty;
    <span class="dt">const</span> <span class="dt">auto</span> step1 = empty.insert&lt;name&gt;(<span class="st">&quot;jon&quot;</span>);
    <span class="dt">const</span> <span class="dt">auto</span> step2 = step1.insert&lt;age&gt;(<span class="dv">20</span>);
    <span class="dt">const</span> <span class="dt">auto</span> step3 = step2.insert&lt;favorite_food&gt;(<span class="st">&quot;icecream&quot;</span>);
    <span class="dt">const</span> <span class="dt">auto</span> step4 = step3.set&lt;favorite_food&gt;(<span class="st">&quot;calzone&quot;</span>);
    <span class="dt">const</span> <span class="dt">auto</span> step5 = tick_tock(step3);

    std::cout &lt;&lt; step1 &lt;&lt; std::endl;
    <span class="co">// =&gt; name : jon, {}</span>
    std::cout &lt;&lt; step2 &lt;&lt; std::endl;
    <span class="co">// =&gt; age : 20, name : jon, {}</span>
    std::cout &lt;&lt; step3 &lt;&lt; std::endl;
    <span class="co">// =&gt; favorite_food : icecream, age : 20, name : jon, {}</span>
    std::cout &lt;&lt; step4 &lt;&lt; std::endl;
    <span class="co">// =&gt; favorite_food : calzone, age : 20, name : jon, {}</span>
    std::cout &lt;&lt; step5.age &lt;&lt; std::endl;
    <span class="co">// =&gt; 21</span>
}</code></pre>
<h3 id="next-steps">Next Steps</h3>
<p>A few changes would have to be made to our design to allow for <em>removing</em> fields from records nicely: our record representation would have to be recursive rather than flat for the proper return type to be readily computable.</p>
<p>It would also be interesting to see how difficult it would be to derive generic equality for records using <code>operator==</code>.</p>
<p>Finally, the most interesting thing to do would be to have some notion of compositional lenses to allow deep update. For instance, imagine if the following were possible:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="dt">auto</span> changed = man.modify&lt;brother,dog,fur,color&gt;(<span class="st">&quot;orange&quot;</span>);</code></pre>]]></description>
    <pubDate>Fri, 23 Nov 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-11-23-extensible-records-in-cpp.html</guid>
</item>
<item>
    <title>Natural Language Syntax in Coq: Baby Steps</title>
    <link>http://www.jonmsterling.com/posts/2012-11-24-nl-syntax-in-coq-baby-steps.html</link>
    <description><![CDATA[In a slight diversion from my <a
    href="http://www.jonmsterling.com/posts/2012-09-14-natural-language-semantics-I.html">path</a>
toward NL <i>semantics</i> in Martin-Löf Type Theory, I'd like to delve
a bit into formulating NL <i>syntax</i> in <a
    href="http://coq.inria.fr">Coq</a>, a dependently typed theorem
prover based on the <a
    href="http://en.wikipedia.org/wiki/Calculus_of_inductive_constructions">Calculus of Inductive Constructions</a>.

<!--MORE-->

<p>We'll begin with a very simple (and underpowered) theory of syntax
including the following:</p>

<ol>
    <li><strong>Syntactic categories:</strong> things like <i>Noun</i>,
    <i>Verb</i>, and <i>Determiner</i>. These classify items in our
    lexicon.
    </li>

    <li><strong>Merge:</strong> an operation that combines two nodes to
    make a larger node. Phrases are built from the lowest head upwards,
    by merging new nodes onto the head.</li>

    <li><strong>X-Bar Schema:</strong> There are at most two levels of
    projection from a single head; a head <code>X</code> may merge with an <i>internal
        argument</i>, projecting a <code>X'</code> node, which may in
    turn merge with an <i>external argument</i> to project the maximal
    <code>XP</code> node.</li>
</ol>

<p>The internal argument is the sister of <code>X</code>, and is called
its <i>complement</i>; the external argument is the aunt of
<code>X</code> (the sister of <code>X'</code>), and is called the
<i>specifier</i>. Therefore, the two kinds of merges that we have
discussed are referred to as <strong>C-Merge</strong> and
<strong>S-Merge</strong> respectively.</p>

<p>The schema looks something like this:</p>

<pre>
              XP                             X
             / \                            / \
            /   \                          /   \
           /     \                        /     \
          ZP     X'       (or just)      Z      X
                / \                            / \
               /   \                          /   \
              /     \                        /     \
             YP      X                      Y       X
</pre>

<p>The latter representation is the same, except the projection-level is
left to be inferred.</p>

<p>In later posts, I'll revisit our theory with enhancements that will
make it more able to express natural language syntax.</p>


<h2>The Implementation</h2>

<div class="code">
<span class="id" type="keyword">Require</span> <span class="id" type="keyword">Import</span> <span class="id" type="var">String</span> <span class="id" type="var">EquivDec</span> <span class="id" type="var">Bool</span>.<br/>
<span class="id" type="keyword">Set Implicit Arguments</span>.<br/>

<br/>
<span class="id" type="keyword">Section</span> <span class="id" type="var">CoreTheory</span>.<br/>

<br/>
</div>

<div class="doc">
We'll start with a few syntactic categories. This is of course
  not sufficient to do real syntax, but it will do for now.
</div>
<div class="code">
&nbsp;&nbsp;<span class="id" type="keyword">Inductive</span> <span class="id" type="var">category</span> := <span class="id" type="var">D</span> | <span class="id" type="var">N</span> | <span class="id" type="var">V</span>.<br/>

<br/>
</div>

<div class="doc">
Each constituent is marked by a set of features; in our current
  theory, features are just a syntactic category, and specifications
  for internal and external arguments.
</div>
<div class="code">

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Inductive</span> <span class="id" type="var">features</span> : <span class="id" type="keyword">Set</span> :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ <span class="id" type="var">cat</span> : <span class="id" type="var">category</span> ;<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">iArg</span> : <span class="id" type="var">option</span> <span class="id" type="var">features</span> ;<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">eArg</span> : <span class="id" type="var">option</span> <span class="id" type="var">features</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}.<br/>

<br/>
</div>

<div class="doc">
Coq allows us to derive decidable equality for categories. This will prove useful below.
</div>
<div class="code">
&nbsp;&nbsp;<span class="id" type="keyword">Theorem</span> <span class="id" type="var">eq_cat_dec</span> (<span class="id" type="var">a</span> : <span class="id" type="var">category</span>) (<span class="id" type="var">b</span> : <span class="id" type="var">category</span>) : {<span class="id" type="var">a</span> = <span class="id" type="var">b</span>} + {<span class="id" type="var">a</span> &lt;&gt; <span class="id" type="var">b</span>}.<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Proof</span>.<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">decide</span> <span class="id" type="var">equality</span>.<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Defined</span>.<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Program Instance</span> <span class="id" type="var">cat_eq_eqdec</span> : <span class="id" type="var">EqDec</span> <span class="id" type="var">category</span> <span class="id" type="var">eq</span> := <span class="id" type="var">eq_cat_dec</span>.<br/>

<br/>
</div>

<div class="doc">
In our current theory, there are two kinds of arguments:
  internal and external; an internal argument is lower in the tree
  than the head, whereas an external argument is higher. We provide
  selectors for arguments.
</div>
<div class="code">

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Inductive</span> <span class="id" type="var">position</span> := <span class="id" type="var">internal</span> | <span class="id" type="var">external</span>.<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">argument_at</span> (<span class="id" type="var">p</span> : <span class="id" type="var">position</span>) :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">match</span> <span class="id" type="var">p</span> <span class="id" type="keyword">with</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">internal</span> =&gt; <span class="id" type="var">iArg</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">external</span> =&gt; <span class="id" type="var">eArg</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">end</span>.<br/>

<br/>
</div>

<div class="doc">
This is where it starts to get interesting. We need a predicate
  that decides whether or not the features <span class="inlinecode"><span class="id" type="var">hfs</span></span> of the head license
  the features <span class="inlinecode"><span class="id" type="var">fs</span></span> of a constituent which wishes to be merged to it
  at some position <span class="inlinecode"><span class="id" type="var">p</span></span>. The predicate is satisfied if <span class="inlinecode"><span class="id" type="var">fs</span></span> is
  saturated, and there is an argument <span class="inlinecode"><span class="id" type="var">arg</span></span> at <span class="inlinecode"><span class="id" type="var">p</span></span> in <span class="inlinecode"><span class="id" type="var">hfs</span></span> whose
  category is equal to the category of <span class="inlinecode"><span class="id" type="var">fs</span></span>.
<div class="paragraph"> </div>

 We can say that a node is saturated at a position if there is no
  specification for an argument present. This is because these
  specifications are erased after each merge.
</div>
<div class="code">

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">saturated_at</span> (<span class="id" type="var">fs</span> : <span class="id" type="var">features</span>) (<span class="id" type="var">p</span> : <span class="id" type="var">position</span>) :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">match</span> <span class="id" type="var">argument_at</span> <span class="id" type="var">p</span> <span class="id" type="var">fs</span> <span class="id" type="keyword">with</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">Some</span> <span class="id" type="var">_</span> =&gt; <span class="id" type="var">false</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">None</span>   =&gt; <span class="id" type="var">true</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">end</span>.<br/>

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">fully_saturated</span> (<span class="id" type="var">fs</span> : <span class="id" type="var">features</span>) :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;(<span class="id" type="var">saturated_at</span> <span class="id" type="var">fs</span> <span class="id" type="var">internal</span>) &amp;&amp; (<span class="id" type="var">saturated_at</span> <span class="id" type="var">fs</span> <span class="id" type="var">external</span>).<br/>

<br/>
</div>

<div class="doc">
First, we determine if a merge is even plausible: for C-merge,
  the internal argument must not already be saturated; for S-merge,
  the internal argument must be saturated, and the external argument
  must not be.
</div>
<div class="code">

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">can_merge_at</span> (<span class="id" type="var">hfs</span> : <span class="id" type="var">features</span>) (<span class="id" type="var">p</span> : <span class="id" type="var">position</span>) :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">match</span> <span class="id" type="var">p</span> <span class="id" type="keyword">with</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">internal</span> =&gt; <span class="id" type="var">negb</span> (<span class="id" type="var">saturated_at</span> <span class="id" type="var">hfs</span> <span class="id" type="var">internal</span>)<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">external</span> =&gt; (<span class="id" type="var">saturated_at</span> <span class="id" type="var">hfs</span> <span class="id" type="var">internal</span>) &amp;&amp; (<span class="id" type="var">negb</span> (<span class="id" type="var">saturated_at</span> <span class="id" type="var">hfs</span> <span class="id" type="var">external</span>))<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">end</span>.<br/>

<br/>
</div>

<div class="doc">
Now, we can check if the merge will be successful, given the
  syntactic category of each of the participants.
</div>
<div class="code">

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">selects</span> (<span class="id" type="var">p</span> : <span class="id" type="var">position</span>) (<span class="id" type="var">hfs</span> : <span class="id" type="var">features</span>) (<span class="id" type="var">fs</span> : <span class="id" type="var">features</span>) :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">match</span> <span class="id" type="var">argument_at</span> <span class="id" type="var">p</span> <span class="id" type="var">hfs</span> <span class="id" type="keyword">with</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">Some</span> <span class="id" type="var">arg</span> =&gt;<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">match</span> <span class="id" type="var">cat</span> <span class="id" type="var">arg</span> == <span class="id" type="var">cat</span> <span class="id" type="var">fs</span> <span class="id" type="keyword">with</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="tactic">left</span>  <span class="id" type="var">_</span> =&gt; <span class="id" type="var">Is_true</span> ((<span class="id" type="var">fully_saturated</span> <span class="id" type="var">fs</span>) &amp;&amp; (<span class="id" type="var">can_merge_at</span> <span class="id" type="var">hfs</span> <span class="id" type="var">p</span>))<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="tactic">right</span> <span class="id" type="var">_</span> =&gt; <span class="id" type="var">False</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">end</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">None</span> =&gt; <span class="id" type="var">False</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">end</span>.<br/>

<br/>
</div>

<div class="doc">
We now compute the type of a merge at position <span class="inlinecode"><span class="id" type="var">p</span></span>. We require a
  proof that the head selects for the new node. The resulting node
  inherits the category of the head, and has its <span class="inlinecode"><span class="id" type="var">iArg</span></span> saturated; if
  <span class="inlinecode"><span class="id" type="var">p</span></span> is external, that means that the <span class="inlinecode"><span class="id" type="var">eArg</span></span> has also been
  saturated.
</div>
<div class="code">

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">gen_merge</span> (<span class="id" type="var">N</span> : <span class="id" type="var">features</span> -&gt; <span class="id" type="keyword">Set</span>) (<span class="id" type="var">p</span> : <span class="id" type="var">position</span>) :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">forall</span> (<span class="id" type="var">hfs</span> : <span class="id" type="var">_</span>) (<span class="id" type="var">fs</span> : <span class="id" type="var">_</span>)<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(<span class="id" type="var">h</span> : <span class="id" type="var">N</span> <span class="id" type="var">hfs</span>) (<span class="id" type="var">n</span> : <span class="id" type="var">N</span> <span class="id" type="var">fs</span>)<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(<span class="id" type="var">sel</span> : <span class="id" type="var">selects</span> <span class="id" type="var">p</span> <span class="id" type="var">hfs</span> <span class="id" type="var">fs</span>),<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">N</span> {| <span class="id" type="var">cat</span> := <span class="id" type="var">cat</span> <span class="id" type="var">hfs</span> ;<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">iArg</span> := <span class="id" type="var">None</span> ;<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">eArg</span> := <span class="id" type="keyword">match</span> <span class="id" type="var">p</span> <span class="id" type="keyword">with</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">internal</span> =&gt; <span class="id" type="var">eArg</span> <span class="id" type="var">hfs</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">external</span> =&gt; <span class="id" type="var">None</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">end</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|}.<br/>

<br/>
</div>

<div class="doc">
Finally, we are ready to model nodes. A node is indexed by its
  features, and may be either a head (minimal projection), or the
  result of a <span class="inlinecode"><span class="id" type="var">cmerge</span></span> (merging of a complement into internal argument
  position), or the result of an <span class="inlinecode"><span class="id" type="var">smerge</span></span> (merginf of a specifier into
  external argument position). The types of the latter two
  constructors are computed using <span class="inlinecode"><span class="id" type="var">gen_merge</span></span> above.
</div>
<div class="code">

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Inductive</span> <span class="id" type="var">node</span> : <span class="id" type="var">features</span> -&gt; <span class="id" type="keyword">Set</span> :=<br/>
&nbsp;&nbsp;| <span class="id" type="var">head</span> : <span class="id" type="keyword">forall</span> (<span class="id" type="var">s</span> : <span class="id" type="var">string</span>), <span class="id" type="keyword">forall</span> (<span class="id" type="var">fs</span> : <span class="id" type="var">features</span>), <span class="id" type="var">node</span> <span class="id" type="var">fs</span><br/>
&nbsp;&nbsp;| <span class="id" type="var">cmerge</span> : <span class="id" type="var">gen_merge</span> <span class="id" type="var">node</span> <span class="id" type="var">internal</span><br/>
&nbsp;&nbsp;| <span class="id" type="var">smerge</span> : <span class="id" type="var">gen_merge</span> <span class="id" type="var">node</span> <span class="id" type="var">external</span>.<br/>

<br/>
</div>

<div class="doc">
As a bonus, we provide a function to fold a node into a string.
</div>
<div class="code">
&nbsp;&nbsp;<span class="id" type="keyword">Fixpoint</span> <span class="id" type="var">to_string</span> {<span class="id" type="var">fs</span> : <span class="id" type="var">_</span>} (<span class="id" type="var">n</span> : <span class="id" type="var">node</span> <span class="id" type="var">fs</span>) : <span class="id" type="var">string</span> :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">match</span> <span class="id" type="var">n</span> <span class="id" type="keyword">with</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">head</span> <span class="id" type="var">s</span> <span class="id" type="var">_</span> =&gt; <span class="id" type="var">s</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">cmerge</span> <span class="id" type="var">_</span> <span class="id" type="var">_</span> <span class="id" type="var">h</span> <span class="id" type="var">c</span> <span class="id" type="var">_</span> =&gt; <span class="id" type="var">append</span> (<span class="id" type="var">to_string</span> <span class="id" type="var">h</span>) (<span class="id" type="var">append</span> " " (<span class="id" type="var">to_string</span> <span class="id" type="var">c</span>))<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;| <span class="id" type="var">smerge</span> <span class="id" type="var">_</span> <span class="id" type="var">_</span> <span class="id" type="var">h</span> <span class="id" type="var">s</span> <span class="id" type="var">_</span> =&gt; <span class="id" type="var">append</span> (<span class="id" type="var">to_string</span> <span class="id" type="var">s</span>) (<span class="id" type="var">append</span> " " (<span class="id" type="var">to_string</span> <span class="id" type="var">h</span>))<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="keyword">end</span>.<br/>

<br/>
<span class="id" type="keyword">End</span> <span class="id" type="var">CoreTheory</span>.<br/>

<br/>
<span class="id" type="keyword">Section</span> <span class="id" type="var">Examples</span>.<br/>

<br/>
</div>

<div class="doc">
Let's make some convenient notation for merges. Note that <span class="inlinecode"><span class="id" type="var">I</span></span> is
  the single constructor for the type <span class="inlinecode"><span class="id" type="var">True</span></span>, and serves as the
  proof-witness that the head selects the merged node.
</div>
<div class="code">

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Notation</span> " head |- comp " := (<span class="id" type="var">cmerge</span> <span class="id" type="var">head</span> <span class="id" type="var">comp</span> <span class="id" type="var">I</span>)<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(<span class="id" type="tactic">right</span> <span class="id" type="keyword">associativity</span>, <span class="id" type="tactic">at</span> <span class="id" type="keyword">level</span> 100).<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Notation</span> " spec -| head " := (<span class="id" type="var">smerge</span> <span class="id" type="var">head</span> <span class="id" type="var">spec</span> <span class="id" type="var">I</span>)<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(<span class="id" type="tactic">left</span> <span class="id" type="keyword">associativity</span>, <span class="id" type="tactic">at</span> <span class="id" type="keyword">level</span> 101).<br/>

<br/>
</div>

<div class="doc">
Let's build up a lexicon.
</div>
<div class="code">
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">dog</span> :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">head</span> "dog"<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{| <span class="id" type="var">cat</span> := <span class="id" type="var">N</span> ; <span class="id" type="var">iArg</span> := <span class="id" type="var">None</span> ; <span class="id" type="var">eArg</span> := <span class="id" type="var">None</span> |}.<br/>

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">love</span> :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">head</span> "love"<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{| <span class="id" type="var">cat</span>  := <span class="id" type="var">V</span> ;<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">iArg</span> := <span class="id" type="var">Some</span> {| <span class="id" type="var">cat</span> := <span class="id" type="var">D</span> ; <span class="id" type="var">iArg</span> := <span class="id" type="var">None</span> ; <span class="id" type="var">eArg</span> := <span class="id" type="var">None</span> |} ;<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">eArg</span> := <span class="id" type="var">Some</span> {| <span class="id" type="var">cat</span> := <span class="id" type="var">D</span> ; <span class="id" type="var">iArg</span> := <span class="id" type="var">None</span> ; <span class="id" type="var">eArg</span> := <span class="id" type="var">None</span> |}<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|}.<br/>

<br/>

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">the</span> :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">head</span> "the"<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{| <span class="id" type="var">cat</span>  := <span class="id" type="var">D</span> ;<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">iArg</span> := <span class="id" type="var">Some</span> {| <span class="id" type="var">cat</span> := <span class="id" type="var">N</span> ; <span class="id" type="var">iArg</span> := <span class="id" type="var">None</span> ; <span class="id" type="var">eArg</span> := <span class="id" type="var">None</span> |} ;<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">eArg</span> := <span class="id" type="var">None</span><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;|}.<br/>

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">I</span> :=<br/>
&nbsp;&nbsp;&nbsp;&nbsp;<span class="id" type="var">head</span> "I"<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{| <span class="id" type="var">cat</span> := <span class="id" type="var">D</span> ; <span class="id" type="var">iArg</span> := <span class="id" type="var">None</span> ; <span class="id" type="var">eArg</span> := <span class="id" type="var">None</span> |}.<br/>

<br/>
</div>

<div class="doc">
We can now build up some phrases. If they type check, then they
  are grammatical within our theory.
</div>
<div class="code">

<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">the_dog</span> := <span class="id" type="var">the</span> |- <span class="id" type="var">dog</span>.<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">love_the_dog</span> := <span class="id" type="var">love</span> |- <span class="id" type="var">the</span> |- <span class="id" type="var">dog</span>.<br/>
&nbsp;&nbsp;<span class="id" type="keyword">Definition</span> <span class="id" type="var">I_love_the_dog</span> := <span class="id" type="var">I</span> -| <span class="id" type="var">love</span> |- <span class="id" type="var">the</span> |- <span class="id" type="var">dog</span>.<br/>

<br/>
</div>

<div class="doc">
The last phrase that we constructed represents the following tree:

<pre>
           V
          / \
         /   \
        /     \
       I      V
             / \
            /   \
           /     \
         love    D
                / \
               /   \
              /     \
             the    dog
</pre>
<div class="paragraph"> </div>

 Evaluating our phrase as a string yields <span class="inlinecode">"<span class="id" type="var">I</span></span> <span class="inlinecode"><span class="id" type="var">love</span></span> <span class="inlinecode"><span class="id" type="var">the</span></span> <span class="inlinecode"><span class="id" type="var">dog</span>"</span>.
</div>
<div class="code">
&nbsp;&nbsp;<span class="id" type="keyword">Eval</span> <span class="id" type="tactic">simpl</span> <span class="id" type="keyword">in</span> <span class="id" type="var">to_string</span> <span class="id" type="var">I_love_the_dog</span>.<br/>
<span class="id" type="keyword">End</span> <span class="id" type="var">Examples</span>.<br/>
</div>


<h2>Next steps</h2>

<p>Basically, all that this theory provides us is the ability to base
grammaticality-judgements of merges on the syntactic category of
consituents and their arguments. This is obvously not enough! Not only
do we need to make more interesting specifications than syntactic
category, we also need to include the following notions: phrasal
movement, agreement, and head movement, to name a few.
</p>

<p>In addition, it would be prudent to escape the bonds that our current
argument representation has left us in, and move toward a more minimal
approach based on a single merge operation; in addition, a notion of
feature strength (that is, whether a feature must be satisfied locally
or not) would be an enormous improvement.</p>

<p>In the meanwhile, play around with the <a
    href="https://github.com/jonsterling/NL-Coq/blob/rev0/BabySteps.v">sources</a>
to this post and see what you can improve!</p>
]]></description>
    <pubDate>Sat, 24 Nov 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-11-24-nl-syntax-in-coq-baby-steps.html</guid>
</item>
<item>
    <title>Eliminating Stringly-Typed Code in Objective-C</title>
    <link>http://www.jonmsterling.com/posts/2012-12-20-stringly-typed-code.html</link>
    <description><![CDATA[<p>Perhaps the greatest sin in the common body of Cocoa design patterns is the pervasiveness of “stringly-typed” code:<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> it frequently comes up in KVO and bindings, among other things. Various macros have arisen to allow type checking of keypaths, largely thanks to <a href="https://github.com/jspahrsummers/libextobjc/blob/master/extobjc/EXTKeyPathCoding.h">efforts</a> by Justin Spahr-Summers and myself. Today, I’d like to talk a bit about some ideas for enforcing statically trusted boundaries for checked keypaths.</p>
<!--MORE-->






<h3 id="the-problem-sometimes-we-lie">The Problem: Sometimes We Lie</h3>
<p>Let’s go over the state of affairs. APIs accept strings for keypaths; we then conjure up some macro like <code>@keypath</code> to allow compile-time checking of keypaths, gaining in addition the ability for them to participate in refactoring. So, we can be sure that our own code is providing safe keypaths to the APIs it consumes.</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec">[detailView bind: @keypath(detailView.titleLabel.text)
        toObject: dogsController
     withKeyPath: @keypath(dogsController.selectedDog.name)
         options: nil];</code></pre>
<p>But the other half of the problem remains: when our own APIs use keypaths, it would be nice to enforce that these keypaths be checked. If we’re just accepting strings and hoping the client code is clever enough to use our <code>@keypath</code> macro, all is well until we begin to lie. And we all lie.</p>
<h3 id="trusted-boundaries-types-for-certified-keypaths">Trusted Boundaries: Types For Certified Keypaths</h3>
<p>Whilst we really can’t do anything about Cocoa’s APIs, we should like to force keypaths passed into our own APIs to be checked. We can do this with a type, and some clever higgle-piggling about with deprecation annotations:<sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup></p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">@interface</span> CheckedKeyPath : NSObject
@property (strong, readonly) NSString *stringValue;
- (id)initWithUnsafeKeyPath:(NSString *)unsafeKeyPath DEPRECATED_ATTRIBUTE;
<span class="kw">@end</span>

<span class="kw">@interface</span> NSString (CheckedKeyPath)
- (CheckedKeyPath *)unsafeMarshalKeyPath DEPRECATED_ATTRIBUTE;
<span class="kw">@end</span>

<span class="ot">#define keypath(PATH) \</span>
_Pragma(<span class="st">&quot;clang diagnostic push&quot;</span>)\
_Pragma(<span class="st">&quot;clang diagnostic ignored </span><span class="ch">\&quot;</span><span class="st">-Wdeprecated</span><span class="ch">\&quot;</span><span class="st">&quot;</span>)\
    (strchr(# PATH, &#39;.&#39;) + <span class="dv">1</span>).unsafeMarshalKeypath \
_Pragma(<span class="st">&quot;clang diagnostic pop&quot;</span>)</code></pre></td></tr></table>
<p>Now, the real trick is in the <code>@keypath</code> macro definition above; feel free to swap in something more advanced for the meat of the definition. The important part is that the macro includes pragmas<sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup> to suppress warnings about deprecated methods, and then goes ahead and uses <code>-unsafeMarshalKeypath</code> in that scope. In this way, we can be reasonably assured (though not entirely, of course) that the only way anyone will <em>ever</em> create a term of type <code>CheckedKeyPath</code> is by using this macro.</p>
<p>Now, in our APIs, we can expose only safe interfaces for keypaths by accepting <code>CheckedKeyPath</code> rather than <code>NSString</code>; when a keypath needs to be passed to Cocoa, we can then trivially throw away the certification by sending <code>-stringValue</code>.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>You’ll have to trust me on this one, since to enumerate the design-sins of Cocoa and Objective-C would likely take the rest of my life.<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>The implementations of these interfaces are trivial; I will leave them to your imagination.<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>We cannot use <code>#pragma</code> within a macro, but <code>_Pragma</code> works just the same.<a href="#fnref3">↩</a></p></li>
</ol>
</div>]]></description>
    <pubDate>Thu, 20 Dec 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-12-20-stringly-typed-code.html</guid>
</item>
<item>
    <title>A Pattern for Lightweight Immutability in Objective-C</title>
    <link>http://www.jonmsterling.com/posts/2012-12-27-a-pattern-for-immutability.html</link>
    <description><![CDATA[<p>Today, I hope to introduce a more lightweight approach to immutable objects in Objective-C that sidesteps some of the problems with class clusters (such as hostility to subclassing) by making some trade-offs. The class cluster approach provides the following fronts of protection against illegal mutation:</p>
<ol style="list-style-type: decimal">
<li>Mutation methods only occur in the interfaces for the mutable variants. This protects us when types are preserved.</li>
<li>Sending a mutation message to an immutable object results in an exception.</li>
</ol>
<p>I’m going to argue that the first force of protection (that of types) is far more important than the second (that of runtime exceptions), and that if we are willing to give it up, we can have a vastly simpler notion of immutability and mutability. Finally, I’ll discuss ways we can recover runtime exceptions in the case of an unsafe cast, and finally how we can recover the functionality of <code>-mutableCopy</code> in a subclass-friendly fashion.</p>
<!--MORE-->

<h3 id="immutability-axioms-for-a-minimal-implementation">Immutability: Axioms for a Minimal Implementation</h3>
<p>Let us agree on the following axioms (that is to say, the extent to which you find this article valuable will vary with the extent to which you stipulate the following):</p>
<ol style="list-style-type: decimal">
<li><p>Objects should be immutable; no shared object should ever have its state changed underneath from another object. If multiple objects need to share the changing state of another object, it should be represented as a reactive event stream.</p></li>
<li><p>It should be trivial to make an updated <em>copy</em> of an object; it should be trivial to update multiple aspects of an object in whichever order you wish.</p></li>
<li><p>We need not code defensively against unsafe casting. If API consumers perform a downward cast, they objectively deserve every bit of bizarre and confusing behavior they are rewarded with.</p></li>
</ol>
<p>And so from <strong>Axiom 3</strong>, we can dispatch the issue of whether it is necessary to have both static and runtime assurances about immutability. If API consumers agree not to perform any obviously unsafe casts, then we can rely on static immutability alone. Later we’ll discuss what is necessary if we wish to discard this last axiom.</p>
<h3 id="implementation-example-an-ordered-dictionary">Implementation Example: An Ordered Dictionary</h3>
<p>The key conceit of our plan is to provide a mutable and an immutable interface to an object; then, we limit access to the mutable interface to a few safe points in our code. That is, we will allow dictionaries to be built and updated imperativiely, but the mutations will be upon a <em>copy</em>. It should look something like this:</p>
<pre class="sourceCode ObjectiveC"><code class="sourceCode objectivec">JSOrderedDictionary *updated = [oldDict update:^(id&lt;JSMutableOrderedDictionary&gt; dict) {
    dict[<span class="st">@&quot;dogs&quot;</span>] = @[ <span class="st">@&quot;tucker&quot;</span>, <span class="st">@&quot;rover&quot;</span> ];
    dict[<span class="st">@&quot;cats&quot;</span>] = @[ <span class="st">@&quot;emma&quot;</span> ];
    [dict removeObjectForKey:<span class="st">@&quot;hamsters&quot;</span>];
}];</code></pre>
<p>Now, we can get started. First, we will define the immutable and mutable interfaces for an ordered dictionary; we expose the mutable one only in <code>-update:</code>. The mutable interface of course inherits all the immutable kit.</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">@protocol</span> JSMutableOrderedDictionary;
<span class="kw">typedef</span> <span class="dt">void</span> (^JSOrderedDictionaryUpdate)(id&lt;JSMutableOrderedDictionary&gt; dict);

<span class="kw">@protocol</span> JSOrderedDictionary &lt;NSFastEnumeration&gt;
- (id)objectForKey:(id&lt;NSCopying&gt;)key;
- (id)objectForKeyedSubscript:(id&lt;NSCopying&gt;)key;

- (NSArray *)allKeys;
- (NSArray *)allValues;
- (NSUInteger)count;

- (instancetype)update:(JSOrderedDictionaryUpdate)updateBlock;
<span class="kw">@end</span>

<span class="kw">@protocol</span> JSMutableOrderedDictionary &lt;JSOrderedDictionary&gt;
- (<span class="dt">void</span>)setObject:(id)object forKey:(id&lt;NSCopying&gt;)key;
- (<span class="dt">void</span>)setObject:(id)object forKeyedSubscript:(id&lt;NSCopying&gt;)key;
- (<span class="dt">void</span>)removeObjectForKey:(id&lt;NSCopying&gt;)key;
<span class="kw">@end</span>

<span class="kw">@interface</span> JSOrderedDictionary : NSObject &lt;JSOrderedDictionary, NSCopying&gt;
- (id)initWithOrderedDictionary:(id&lt;JSOrderedDictionary&gt;)dictionary;
- (id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys;
<span class="kw">@end</span></code></pre></td></tr></table>
<p>The implementation is quite straightforward:</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">@interface</span> JSOrderedDictionary (JSMutableOrderedDictionary) &lt;JSMutableOrderedDictionary&gt;
<span class="kw">@end</span>

<span class="kw">@implementation</span> JSOrderedDictionary {
    NSMutableArray *_keys;
    NSMutableDictionary *_dictionary;
}

<span class="ot">#pragma mark - Initializers</span>

- (id)init {
    <span class="kw">return</span> [<span class="kw">self</span> initWithObjects:@[ ] forKeys:@[ ]];
}

- (id)initWithOrderedDictionary:(id&lt;JSOrderedDictionary&gt;)dictionary {
    <span class="kw">return</span> [<span class="kw">self</span> initWithObjects:dictionary.allValues forKeys:dictionary.allKeys];
}

- (id)initWithObjects:(NSArray *)objects forKeys:(NSArray *)keys {
    <span class="kw">if</span> (<span class="kw">self</span> = [<span class="kw">super</span> init]) {
        _keys = [keys mutableCopy];
        _dictionary = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
    }

    <span class="kw">return</span> <span class="kw">self</span>;
}

<span class="ot">#pragma mark - NSCopying</span>

- (id)copyWithZone:(NSZone *)zone {
    <span class="kw">return</span> [[[<span class="kw">self</span> class] alloc] initWithOrderedDictionary:<span class="kw">self</span>];
}

<span class="ot">#pragma mark - NSFastEnumeration</span>

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
     objects:(__unsafe_unretained id [])buffer count:(NSUInteger)len {
    <span class="kw">return</span> [_keys countByEnumeratingWithState:countByEnumeratingWithState:state objects:buffer count:len];
}

<span class="ot">#pragma mark - JSOrderedDictionary</span>

- (id)objectForKey:(id&lt;NSCopying&gt;)key {
    <span class="kw">return</span> [_dictionary objectForKey:key];
}

- (id)objectForKeyedSubscript:(id&lt;NSCopying&gt;)key {
    <span class="kw">return</span> [<span class="kw">self</span> objectForKey:key];
}

- (NSArray *)allKeys {
    <span class="kw">return</span> [_keys copy];
}

- (NSArray *)allValues {
    NSMutableArray *values = [NSMutableArray arrayWithCapacity:<span class="kw">self</span>.count];
    <span class="kw">for</span> (id&lt;NSCopying&gt; key in <span class="kw">self</span>) {
        [values addObject:<span class="kw">self</span>[key]];
    }

    <span class="kw">return</span> [values copy];
}

- (NSUInteger)count {
    <span class="kw">return</span> _keys.count;
}

- (instancetype)update:(JSOrderedDictionaryUpdate)updateBlock {
    JSOrderedDictionary *copy = [<span class="kw">self</span> copy];
    updateBlock(copy);
    <span class="kw">return</span> copy;
}

<span class="kw">@end</span>

<span class="kw">@implementation</span> JSOrderedDictionary (JSMutableOrderedDictionary)
<span class="co">// The implementation is trivial.</span>
<span class="kw">@end</span></code></pre></td></tr></table>
<h2 id="fudging-the-axioms-what-can-we-recover">Fudging the Axioms: What can we recover?</h2>
<p>Now that we’ve shown the Taliban approach, we can see what is necessary to recover some of the things we might miss.</p>
<h3 id="recovering-exceptions">Recovering Exceptions</h3>
<p>As explained above, the current model expresses the boundary between mutability and immutability using types. That is, we provide a mutable interface to our dictionary, exposed in such a way as to aggregate imperative updates and perform them safely on a copy. But we do nothing to prevent a user from casting <code>JSOrderedDictionary</code> to <code>id&lt;JSMutableOrderedDictionary&gt;</code>; if a dictionary object is shared, and one partaker unscrupulously (and unsafely) casts the dictionary to <code>id</code> or the mutable interface, this may represent a broken program that would be hard to debug.</p>
<p>We can recover exceptions (which would provide a way to determine when a dictionary is being used unsafely) very simply by adding a private flag to the dictionary:</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">@implementation</span> JSOrderedDictionary {
    BOOL _isMutable;
    <span class="co">// ...</span>
}

- (instancetype)modify:(JSOrderedDictionaryUpdate)block {
    JSOrderedDictionary *copy = [<span class="kw">self</span> copy];
    copy-&gt;_isMutable = YES;
    block(copy);
    copy-&gt;_isMutable = NO;
    <span class="kw">return</span> copy;
}

<span class="co">// ...</span>
<span class="kw">@end</span>

<span class="kw">@implementation</span> JSOrderedDictionary (JSMutableOrderedDictionary)

- (<span class="dt">void</span>)assertMutableForSelector:(SEL)selector {
    <span class="kw">if</span> (_isMutable) <span class="kw">return</span>;

    NSString *reason = [NSString stringWithFormat:
                        <span class="st">@&quot;Attempted to send -%@ to immutable object %@&quot;</span>,
                        NSStringFromSelector(selector), <span class="kw">self</span>];
    @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:reason userInfo:nil];
}

- (<span class="dt">void</span>)setObject:(id)object forKey:(id&lt;NSCopying&gt;)key {
    NSParameterAssert(key != nil);
    [<span class="kw">self</span> assertMutableForSelector:_cmd];

    <span class="kw">if</span> (object == nil) [_keys removeObject:key];
    <span class="kw">else</span> <span class="kw">if</span> (![_keys containsObject:key]) {
        [_keys addObject:key];
    }

    [_dictionary setObject:object forKey:key];
}

<span class="co">// ...</span>

<span class="kw">@end</span></code></pre></td></tr></table>
<h3 id="mutability-unchained-omphales-revenge">Mutability Unchained: Omphale’s Revenge</h3>
<p>We can even recover the last remaining thing that the class cluster approach gives us (to have a real mutable dictionary, at your own peril) by adding a bit more kit. Let’s wipe out what we did in the last section and refine it a bit. First, let’s adopt <code>&lt;NSMutableCopying&gt;</code> to our interface:</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">@interface</span> JSOrderedDictionary : NSObject &lt;JSOrderedDictionary, NSCopying, NSMutableCopying&gt;
<span class="co">// ...</span>
<span class="kw">@end</span></code></pre></td></tr></table>
<p>Now for some new kit:</p>
<table class="sourceCode ObjectiveC numberLines"><tr class="sourceCode"><td class="lineNumbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
</pre></td><td class="sourceCode"><pre><code class="sourceCode objectivec"><span class="kw">typedef</span> <span class="kw">enum</span> {
    JSMutabilityNone,
    JSMutabilityTemporary,
    JSMutabilityPermanent
} JSMutabilityState;

<span class="kw">@implementation</span> JSOrderedDictionary {
    JSMutabilityState _mutabilityState;
    <span class="co">// ...</span>
}

- (<span class="dt">void</span>)performWithTemporaryMutability:(JSOrderedDictionaryUpdate)block {
    BOOL immutableByDefault = _mutabilityState != JSMutabilityPermanent;
    <span class="kw">if</span> (immutableByDefault) _mutabilityState = JSMutabilityTemporary;
    block(<span class="kw">self</span>);
    <span class="kw">if</span> (immutableByDefault) _mutabilityState = JSMutabilityNone;
}

- (instancetype)modify:(JSOrderedDictionaryUpdate)block {
    BOOL immutableByDefault = _mutabilityState != JSMutabilityPermanent;
    JSOrderedDictionary *copy = immutableByDefault ? [<span class="kw">self</span> copy] : [<span class="kw">self</span> mutableCopy];
    [copy performWithTemporaryMutability:^(id&lt;JSMutableOrderedDictionary&gt; dict) {
        block(dict);
    }];
    <span class="kw">return</span> copy;
}

<span class="ot">#pragma mark - NSMutableCopying</span>

- (id)mutableCopyWithZone:(NSZone *)zone {
    JSOrderedDictionary *copy = [<span class="kw">self</span> copyWithZone:zone];
    copy-&gt;_mutabilityState = JSMutabilityPermanent;
    <span class="kw">return</span> copy;
}

<span class="kw">@end</span>

<span class="kw">@implementation</span> JSOrderedDictionary (JSMutableOrderedDictionary)

- (<span class="dt">void</span>)assertMutableForSelector:(SEL)selector {
    <span class="kw">if</span> (_mutabilityState != JSMutabilityNone) <span class="kw">return</span>;
    <span class="co">// ...</span>
}

<span class="kw">@end</span></code></pre></td></tr></table>
<p>The beauty of this approach is that it is now possible to provide full mutability by adding only a tiny bit of code to the immutable implementation, in a way that is very friendly to subclasses.</p>
<p>Whereas with class clusters, for a class cluster <span class="math">{<em>A</em><sub>mutable</sub>, <em>A</em><sub>immutable</sub>}</span>, a subclass <span class="math"><em>B</em></span> which wishes to provide correct behavior must provide <span class="math">{<em>B</em><sub>mutable</sub> &lt; <em>A</em><sub>mutable</sub>, <em>B</em><sub>immutable</sub> &lt; <em>A</em><sub>mutable</sub>}</span>; furthermore, methods having free ocurrences of <span class="math"><em>A</em><sub>mutable</sub></span> must be rewritten in the subclass to use <span class="math"><em>B</em><sub>mutable</sub></span> and so forth.</p>
<p>Our approach sidesteps these problems quite nicely.</p>
<h2 id="parting-notes">Parting Notes</h2>
<p>I’m using this approach for ordered dictionaries in <a href="https://github.com/jonsterling/ReactiveFormlets/blob/master/iOS%20Formlets/RAFOrderedDictionary.h">ReactiveFormlets</a>. It seems sufficient for my purposes; I’m excited to see if it will do for more advanced ones.</p>]]></description>
    <pubDate>Thu, 27 Dec 2012 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2012-12-27-a-pattern-for-immutability.html</guid>
</item>
<item>
    <title>Proving Type Inequality in C++</title>
    <link>http://www.jonmsterling.com/posts/2013-02-10-proving-type-inequality-in-cpp.html</link>
    <description><![CDATA[<p>It is trivial to prove type equality in Haskell (to the extent that anything is every “proved” in Haskell). As for proving type <em>inequality</em>, Conor McBride <a href="http://stackoverflow.com/a/14277376/125361">demonstrates</a> that this is possible to do using type families. Today, I’d like to show some techniques for doing the same in C++ with templates.</p>
<!--MORE-->

<p>First, let’s come up with some notion of equality. We’re going to base our encoding off of the following pseudocode:</p>
<p><span class="math">$\begin{align} \frac{\vdash\sigma : \star \qquad \vdash\tau : \star}{\vdash \sigma \equiv \tau : \star}\tag{≡-type} \end{align}$</span></p>
<p><span class="math">$\begin{align} \frac{\vdash\sigma : \star}{\vdash\ \hbox{refl} : \sigma\equiv\sigma}\tag{≡-intro} \end{align}$</span></p>
<p><span class="math">$\begin{align} \frac{\vdash x : \sigma \qquad \sigma\equiv\tau}{\vdash x : \tau}\tag{≡-conversion} \end{align}$</span></p>
<p><span class="math">$\begin{align} \frac{\vdash \sigma\equiv\tau \qquad \vdash f : \star\to\star}{\vdash f(\sigma)\equiv f(\tau)}\tag{≡-congruence} \end{align}$</span></p>
<p><span class="math">$\begin{align} \frac{\vdash \sigma\equiv\tau \qquad \vdash f : \star\to\star\qquad \vdash x : f(\sigma)}{\vdash x : f(\tau)} \tag{≡-transport} \end{align}$</span></p>
<h3 id="encoding-equality">Encoding Equality</h3>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="ot">#include &lt;functional&gt;</span>
<span class="kw">namespace</span> Equality {</code></pre>
<p>There is no term in <code>∀ A B. Eq&lt;A,B&gt;</code>; constructors are automatically generated by C++, so we must explicitly delete it.</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">class</span> A, <span class="kw">class</span> B&gt;
    <span class="kw">struct</span> Eq { Eq() = <span class="kw">delete</span>; };</code></pre>
<p>According to <span class="math">$\hbox{≡-intro}$</span> rule above, we can construct a term in <code>∀ A. Eq&lt;A,A&gt;</code>:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">class</span> A&gt;
    <span class="kw">struct</span> Eq&lt;A,A&gt; { Eq() {} };</code></pre>
<p>Casting as in <span class="math">$\hbox{≡-conversion}$</span> is morally correct, but not provable in C++, lacking any notion of dependent pattern matching and refinement. Trusting in the soundness of our axioms, we do an unsafe cast under the hood, given an equality proof.</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">class</span> A, <span class="kw">class</span> B&gt;
    B cast(Eq&lt;A,B&gt; refl, A x) {
        <span class="kw">return</span> *(B*)&amp;x;
    }</code></pre>
<p>Likewise, <span class="math">$\hbox{≡-congruence}$</span> is not provable in C++ for the same reasons; we’ll have to fudge the implementation, trusting the axioms.</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">template</span> &lt;<span class="kw">class</span>&gt; <span class="kw">class</span> F, <span class="kw">class</span> A, <span class="kw">class</span> B&gt;
    Eq&lt;F&lt;A&gt;,F&lt;B&gt;&gt; cong(Eq&lt;A,B&gt; refl) {
        <span class="dt">auto</span> fudge = Eq&lt;F&lt;A&gt;,F&lt;A&gt;&gt;();
        <span class="kw">return</span> *(Eq&lt;F&lt;A&gt;,F&lt;B&gt;&gt;*)&amp;fudge;
    }</code></pre>
<p>Finally, <span class="math">$\hbox{≡-transport}$</span> can be defined in terms of what we’ve already done:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">template</span> &lt;<span class="kw">class</span>&gt; <span class="kw">class</span> F, <span class="kw">class</span> A, <span class="kw">class</span> B&gt;
    F&lt;B&gt; transport(Eq&lt;A,B&gt; refl, F&lt;A&gt; x) {
        <span class="kw">return</span> cast(cong&lt;F&gt;(refl), d);
    }
}</code></pre>
<h3 id="encoding-some-logic">Encoding some Logic</h3>
<p>In a quick digression that will prove necessary shortly, let’s define some basic types that will correspond to falsity, truth and negation:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="kw">namespace</span> Logic {</code></pre>
<p>In the BHK interpretation of intuitionistic logic, falsity is simply a proposition that has no proofs. So we can just provide a type without any constructors:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">struct</span> Empty { Empty() = <span class="kw">delete</span>; };</code></pre>
<p>To make a provable proposition, we can provide a type that does have a constructor:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">struct</span> Unit { Unit () {} };</code></pre>
<p>For one proposition <span class="math"><em>P</em></span> to imply another proposition <span class="math"><em>Q</em></span>, we provide a function which converts proofs of <span class="math"><em>P</em></span> to proofs of <span class="math"><em>Q</em></span>:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">class</span> P, <span class="kw">class</span> Q&gt;
    <span class="kw">using</span> Implication = std::function&lt;Q(P)&gt;;</code></pre>
<p>Finally, we use <em>reductio ad absurdum</em> to refute a proposition:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">class</span> P&gt;
    <span class="kw">using</span> Not = Implication&lt;P,Empty&gt;;
}</code></pre>
<h3 id="discrimination-refuting-equalities">Discrimination: Refuting Equalities</h3>
<p>Finally, we are ready to encode the central conceit.</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="kw">namespace</span> Refute {
    <span class="kw">using</span> <span class="kw">namespace</span> Logic;
    <span class="kw">using</span> <span class="kw">namespace</span> Equality;</code></pre>
<p>First, we shall encode some type-level discrimination functions; so that we can branch on types:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">class</span> A, <span class="kw">class</span> B, <span class="kw">class</span> T, <span class="kw">class</span> CaseA, <span class="kw">class</span> CaseB&gt; <span class="kw">struct</span> If;

    <span class="kw">template</span> &lt;<span class="kw">class</span> A, <span class="kw">class</span> B, <span class="kw">class</span> CaseA, <span class="kw">class</span> CaseB&gt;
    <span class="kw">struct</span> If&lt;A,B,A,CaseA,CaseB&gt; {
        <span class="kw">using</span> apply = CaseA;
    };

    <span class="kw">template</span> &lt;<span class="kw">class</span> A, <span class="kw">class</span> B, <span class="kw">class</span> CaseA, <span class="kw">class</span> CaseB&gt;
    <span class="kw">struct</span> If&lt;A,B,B,CaseA,CaseB&gt; {
        <span class="kw">using</span> apply = CaseB;
    };</code></pre>
<p>Because of some quirks in the way that C++ handles partial template application, we must provide a bit of indirection for what comes next:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">class</span> A, <span class="kw">class</span> B&gt;
    <span class="kw">struct</span> Discriminate {
        <span class="kw">template</span> &lt;<span class="kw">class</span> T&gt;
        <span class="kw">using</span> apply = <span class="kw">typename</span> If&lt;A,B,T,Unit,Empty&gt;::apply;
    };</code></pre>
<p>If a path from <code>A</code> to <code>B</code> (in <code>Eq&lt;A,B&gt;</code>) actually exists, then we should be able to transport any <code>F&lt;A&gt;</code> to <code>F&lt;B&gt;</code>; in this way, we can convert a proof of <code>Eq&lt;A,B&gt;</code> to a proof of <code>Empty</code>.</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp">    <span class="kw">template</span> &lt;<span class="kw">class</span> A, <span class="kw">class</span> B&gt;
    <span class="kw">typename</span> Discriminate&lt;A,B&gt;::<span class="kw">template</span> apply&lt;B&gt; refute_equality(Eq&lt;A,B&gt; refl) {
        <span class="kw">return</span> transport&lt;Discriminate&lt;A,B&gt;::<span class="kw">template</span> apply&gt;(refl, Unit());
    }
}</code></pre>
<h3 id="the-payoff">The Payoff</h3>
<p>Now, given some different types, we can prove that they are not equal using the kit that we have come up with so far:</p>
<pre class="sourceCode Cpp"><code class="sourceCode cpp"><span class="dt">void</span> demonstration() {
    <span class="kw">using</span> Equality::Eq;
    <span class="kw">using</span> Logic::Not;
    <span class="kw">using</span> Refute::refute_equality;

    <span class="kw">struct</span> Dog;
    <span class="kw">struct</span> Cat;

    Not&lt;Eq&lt;Cat,Dog&gt;&gt; cat_is_not_dog = refute_equality&lt;Cat,Dog&gt;;
}</code></pre>
<p>The term <code>cat_is_not_dog</code> serves as a witness that <code>Cat</code> and <code>Dog</code> are different types!</p>]]></description>
    <pubDate>Sun, 10 Feb 2013 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2013-02-10-proving-type-inequality-in-cpp.html</guid>
</item>
<item>
    <title>Vinyl: Modern Records for Haskell</title>
    <link>http://www.jonmsterling.com/posts/2013-04-06-vinyl-modern-records-for-haskell.html</link>
    <description><![CDATA[<p><a href="http://github.com/jonsterling/Vinyl/">Vinyl</a> is a general solution to the records problem in Haskell using type level strings and other modern GHC features, featuring static structural typing (with a subtyping relation), and automatic row-polymorphic lenses. All this is possible without Template Haskell.</p>
<!--MORE-->
<p>First, install Vinyl from Hackage:</p>
<pre><code>cabal update
cabal install vinyl</code></pre>
<p>Let’s work through a quick example. We’ll need to enable some language extensions first:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE DataKinds, TypeOperators #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE FlexibleContexts, NoMonomorphismRestriction #-}</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Data.Vinyl</span>
<span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Data.Vinyl.Unicode</span>
<span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Data.Vinyl.Validation</span>
<span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Control.Applicative</span>
<span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Control.Monad.Identity</span>
<span class="fu">&gt;</span> <span class="kw">import</span> <span class="dt">Data.Char</span></code></pre>
<p>Let’s define the fields we want to use:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> name     <span class="fu">=</span> <span class="dt">Field</span><span class="ot"> ::</span> <span class="st">&quot;name&quot;</span>     <span class="ot">::</span><span class="fu">:</span> <span class="dt">String</span>
<span class="fu">&gt;</span> age      <span class="fu">=</span> <span class="dt">Field</span><span class="ot"> ::</span> <span class="st">&quot;age&quot;</span>      <span class="ot">::</span><span class="fu">:</span> <span class="dt">Int</span>
<span class="fu">&gt;</span> sleeping <span class="fu">=</span> <span class="dt">Field</span><span class="ot"> ::</span> <span class="st">&quot;sleeping&quot;</span> <span class="ot">::</span><span class="fu">:</span> <span class="dt">Bool</span></code></pre>
<p>Now, let’s try to make an entity that represents a man:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> jon <span class="fu">=</span> name <span class="fu">=:</span> <span class="st">&quot;jon&quot;</span>
<span class="fu">&gt;</span>    <span class="fu">&lt;+&gt;</span> age <span class="fu">=:</span> <span class="dv">20</span>
<span class="fu">&gt;</span>    <span class="fu">&lt;+&gt;</span> sleeping <span class="fu">=:</span> <span class="kw">False</span></code></pre>
<p>We could make an alias for the sort of entity that <code>jon</code> is:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> <span class="dt">LifeForm</span> <span class="fu">=</span> [<span class="st">&quot;name&quot;</span> <span class="ot">::</span><span class="fu">:</span> <span class="dt">String</span>, <span class="st">&quot;age&quot;</span> <span class="ot">::</span><span class="fu">:</span> <span class="dt">Int</span>, <span class="st">&quot;sleeping&quot;</span> <span class="ot">::</span><span class="fu">:</span> <span class="dt">Bool</span>]
<span class="fu">&gt;</span><span class="ot"> jon ::</span> <span class="dt">PlainRec</span> <span class="dt">LifeForm</span></code></pre>
<p>The types are inferred, though, so this is unnecessary unless you’d like to reuse the type later. Now, make a dog! Dogs are life-forms, but unlike men, they have masters. So, let’s build my dog:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> master <span class="fu">=</span> <span class="dt">Field</span><span class="ot"> ::</span> <span class="st">&quot;master&quot;</span> <span class="ot">::</span><span class="fu">:</span> <span class="dt">PlainRec</span> <span class="dt">LifeForm</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> tucker <span class="fu">=</span> name <span class="fu">=:</span> <span class="st">&quot;tucker&quot;</span>
<span class="fu">&gt;</span>       <span class="fu">&lt;+&gt;</span> age <span class="fu">=:</span> <span class="dv">7</span>
<span class="fu">&gt;</span>       <span class="fu">&lt;+&gt;</span> sleeping <span class="fu">=:</span> <span class="kw">True</span>
<span class="fu">&gt;</span>       <span class="fu">&lt;+&gt;</span> master <span class="fu">=:</span> jon</code></pre>
<h2 id="using-lenses">Using Lenses</h2>
<p>Now, if we want to wake entities up, we don’t want to have to write a separate wake-up function for both dogs and men (even though they are of different type). Luckily, we can use the built-in lenses to focus on a particular field in the record for access and update, without losing additional information:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> wakeUp ::</span> ((<span class="st">&quot;sleeping&quot;</span> <span class="ot">::</span><span class="fu">:</span> <span class="dt">Bool</span>) ∈ fields) <span class="ot">=&gt;</span> <span class="dt">PlainRec</span> fields <span class="ot">-&gt;</span> <span class="dt">PlainRec</span> fields
<span class="fu">&gt;</span> wakeUp <span class="fu">=</span> sleeping <span class="ot">`rPut`</span> <span class="kw">False</span></code></pre>
<p>Now, the type annotation on <code>wakeUp</code> was not necessary; I just wanted to show how intuitive the type is. Basically, it takes as an input any record that has a <code>BOOL</code> field labelled <code>sleeping</code>, and the modifies that specific field in the record accordingly.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> tucker&#39; <span class="fu">=</span> wakeUp tucker
<span class="fu">&gt;</span> jon&#39; <span class="fu">=</span> wakeUp jon</code></pre>
<p>We can also access the entire lens for a field using the <code>rLens</code> function; since lenses are composable, it’s super easy to do deep update on a record:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> masterSleeping ::</span> ((<span class="st">&quot;master&quot;</span> <span class="ot">::</span><span class="fu">:</span> <span class="dt">PlainRec</span> <span class="dt">LifeForm</span>) ∈ fields) <span class="ot">=&gt;</span> <span class="dt">SimpleLens</span> (<span class="dt">PlainRec</span> fields) <span class="dt">Bool</span>
<span class="fu">&gt;</span> masterSleeping <span class="fu">=</span> rLens master <span class="fu">.</span> rLens sleeping</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> tucker&#39;&#39; <span class="fu">=</span> masterSleeping <span class="fu">.~</span> <span class="kw">True</span> <span class="fu">$</span> tucker&#39;</code></pre>
<p>Again, the type annotation is unnecessary. In fact, the seperate definition is also unnecessary, and we could just define:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> tucker&#39;&#39;&#39; <span class="fu">=</span> rLens master <span class="fu">.</span> rLens sleeping <span class="fu">.~</span> <span class="kw">True</span> <span class="fu">$</span> tucker&#39;</code></pre>
<h2 id="subtyping-relation-and-coercion">Subtyping Relation and Coercion</h2>
<p>A record <code>PlainRec xs</code> is a subtype of a record <code>PlainRec ys</code> if <code>ys ⊆ xs</code>; that is to say, if one record can do everything that another record can, the former is a subtype of the latter. As such, we should be able to provide an upcast operator which “forgets” whatever makes one record different from another (whether it be extra data, or different order).</p>
<p>Therefore, the following works:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> upcastedTucker ::</span> <span class="dt">PlainRec</span> <span class="dt">LifeForm</span>
<span class="fu">&gt;</span> upcastedTucker <span class="fu">=</span> cast (fixRecord tucker)</code></pre>
<p>The reason for using <code>fixRecord</code> will become clear a bit later.</p>
<p>The subtyping relationship between record types is expressed with the <code>(&lt;:)</code> constraint; so, <code>cast</code> is of the following type:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">cast ::</span> r1 <span class="fu">&lt;:</span> r2 <span class="ot">=&gt;</span> r1 <span class="ot">-&gt;</span> r2</code></pre>
<p>Also provided is a (≅) constraint which indicates record congruence (that is, two record types differ only in the order of their fields).</p>
<h2 id="records-are-polymorphic-over-functors">Records are polymorphic over functors</h2>
<p>So far, we’ve been working with the <code>PlainRec</code> type; but below that, there is something a bit more advanced called <code>Rec</code>, which looks like this:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">data</span> <span class="dt">Rec</span><span class="ot"> ::</span> [<span class="fu">*</span>] <span class="ot">-&gt;</span> (<span class="fu">*</span> <span class="ot">-&gt;</span> <span class="fu">*</span>) <span class="ot">-&gt;</span> <span class="fu">*</span> <span class="kw">where</span>
  <span class="dt">RNil</span><span class="ot"> ::</span> <span class="dt">Rec</span> <span class="ch">&#39;[] f</span>
<span class="ot">  (:&amp;) ::</span> (r <span class="fu">~</span> (sy <span class="ot">::</span><span class="fu">:</span> t)) <span class="ot">=&gt;</span> f t <span class="ot">-&gt;</span> <span class="dt">Rec</span> rs f <span class="ot">-&gt;</span> <span class="dt">Rec</span> (r <span class="ch">&#39;: rs) f</span></code></pre>
<p>The second parameter is a functor, in which every element of the record will be placed. In <code>PlainRec</code>, the functor is just set to <code>Identity</code>. Let’s try and motivate this stuff with an example.</p>
<p>Let’s imagine that we want to do validation on a record that represents a name and an age:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> <span class="dt">Person</span> <span class="fu">=</span> [<span class="st">&quot;name&quot;</span> <span class="ot">::</span><span class="fu">:</span> <span class="dt">String</span>, <span class="st">&quot;age&quot;</span> <span class="ot">::</span><span class="fu">:</span> <span class="dt">Int</span>]</code></pre>
<p>We’ve decided that names must be alphabetic, and ages must be positive. For validation, we’ll use a type that’s included here called <code>Result e a</code>, which is similar to <code>Either</code>, except that its <code>Applicative</code> instance accumulates monoidal errors on the left.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> goodPerson ::</span> <span class="dt">PlainRec</span> <span class="dt">Person</span>
<span class="fu">&gt;</span> goodPerson <span class="fu">=</span> name <span class="fu">=:</span> <span class="st">&quot;Jon&quot;</span>
<span class="fu">&gt;</span>          <span class="fu">&lt;+&gt;</span> age <span class="fu">=:</span> <span class="dv">20</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> badPerson <span class="fu">=</span> name <span class="fu">=:</span> <span class="st">&quot;J#@#$on&quot;</span>
<span class="fu">&gt;</span>          <span class="fu">&lt;+&gt;</span> age <span class="fu">=:</span> <span class="dv">20</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> validatePerson ::</span> <span class="dt">PlainRec</span> <span class="dt">Person</span> <span class="ot">-&gt;</span> <span class="dt">Result</span> [<span class="dt">String</span>] (<span class="dt">PlainRec</span> <span class="dt">Person</span>)
<span class="fu">&gt;</span> validatePerson p <span class="fu">=</span> (\n a <span class="ot">-&gt;</span> name <span class="fu">=:</span> n <span class="fu">&lt;+&gt;</span> age <span class="fu">=:</span> a) <span class="fu">&lt;$&gt;</span> vName <span class="fu">&lt;*&gt;</span> vAge <span class="kw">where</span>
<span class="fu">&gt;</span>   vName <span class="fu">=</span> validateName (rGet name p)
<span class="fu">&gt;</span>   vAge  <span class="fu">=</span> validateAge  (rGet age p)
<span class="fu">&gt;</span> 
<span class="fu">&gt;</span>   validateName str <span class="fu">|</span> <span class="fu">all</span> <span class="fu">isAlpha</span> str <span class="fu">=</span> <span class="dt">Success</span> str
<span class="fu">&gt;</span>   validateName _ <span class="fu">=</span> <span class="dt">Failure</span> [ <span class="st">&quot;name must be alphabetic&quot;</span> ]
<span class="fu">&gt;</span>   validateAge i <span class="fu">|</span> i <span class="fu">&gt;=</span> <span class="dv">0</span> <span class="fu">=</span> <span class="dt">Success</span> i
<span class="fu">&gt;</span>   validateAge _ <span class="fu">=</span> <span class="dt">Failure</span> [ <span class="st">&quot;age must be positive&quot;</span> ]</code></pre>
<p>The results are as expected (<code>Success</code> for <code>goodPerson</code>, and a <code>Failure</code> with one error for <code>badPerson</code>); but this was not very fun to build.</p>
<p>Further, it would be nice to have some notion of a <strong>partial record</strong>; that is, if part of it can’t be validated, it would still be nice to be able to access the rest. <em>What if we could make a version of this record where the elements themselves were validation functions, and then that record could be applied to a plain one, to get a record of validated fields?</em> That’s what we’re going to do.</p>
<p>Vinyl provides a type of validators, which is basically a natural transformation from the <code>Identity</code> functor to the <code>Result</code> functor, which we just used above.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">type</span> <span class="dt">Validator</span> e <span class="fu">=</span> <span class="dt">Identity</span> <span class="fu">~&gt;</span> <span class="dt">Result</span> e</code></pre>
<p>Let’s parameterize a record by it: when we do, then an element of type <code>a</code> should be a function <code>Identity a -&gt; Result e a</code>:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> vperson ::</span> <span class="dt">Rec</span> <span class="dt">Person</span> (<span class="dt">Validator</span> [<span class="dt">String</span>])
<span class="fu">&gt;</span> vperson <span class="fu">=</span> <span class="dt">NT</span> validateName <span class="fu">:&amp;</span> <span class="dt">NT</span> validateAge <span class="fu">:&amp;</span> <span class="dt">RNil</span> <span class="kw">where</span>
<span class="fu">&gt;</span>    validateName (<span class="dt">Identity</span> str) <span class="fu">|</span> <span class="fu">all</span> <span class="fu">isAlpha</span> str <span class="fu">=</span> <span class="dt">Success</span> str
<span class="fu">&gt;</span>    validateName _ <span class="fu">=</span> <span class="dt">Failure</span> [ <span class="st">&quot;name must be alphabetic&quot;</span> ]
<span class="fu">&gt;</span>    validateAge (<span class="dt">Identity</span> i) <span class="fu">|</span> i <span class="fu">&gt;=</span> <span class="dv">0</span> <span class="fu">=</span> <span class="dt">Success</span> i
<span class="fu">&gt;</span>    validateAge _ <span class="fu">=</span> <span class="dt">Failure</span> [ <span class="st">&quot;age must be positive&quot;</span> ]</code></pre>
<p>And we can use the special application operator <code>&lt;&lt;*&gt;&gt;</code> (which is analogous to <code>&lt;*&gt;</code>, but generalized a bit) to use this to validate a record:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> goodPersonResult <span class="fu">=</span> vperson <span class="fu">&lt;&lt;*&gt;&gt;</span> goodPerson
<span class="fu">&gt;</span> badPersonResult  <span class="fu">=</span> vperson <span class="fu">&lt;&lt;*&gt;&gt;</span> badPerson</code></pre>
<pre class="sourceCode haskell"><code class="sourceCode haskell">goodPersonResult <span class="fu">===</span> name <span class="fu">:=:</span> <span class="dt">Success</span> <span class="st">&quot;Jon&quot;</span>, age <span class="fu">:=:</span> <span class="dt">Success</span> <span class="dv">20</span>, {}
badPersonResult  <span class="fu">===</span> name <span class="fu">:=:</span> <span class="dt">Failure</span> [<span class="st">&quot;name must be alphabetic&quot;</span>], age <span class="fu">:=:</span> <span class="dt">Success</span> <span class="dv">20</span>, {}</code></pre>
<p>So now we have a partial record, and we can still do stuff with its contents. Next, we can even recover the original behavior of the validator (that is, to give us a value of type <code>Result [String] (PlainRec Person)</code> using <code>run</code>:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> runGoodPerson <span class="fu">=</span> run goodPersonResult
<span class="fu">&gt;</span> runBadPerson  <span class="fu">=</span> run badPersonResult</code></pre>
<pre class="sourceCode haskell"><code class="sourceCode haskell">runGoodPerson <span class="fu">===</span> <span class="dt">Success</span> name <span class="fu">:=:</span> <span class="st">&quot;Jon&quot;</span>, age <span class="fu">:=:</span> <span class="dv">20</span>, {}
runBadPerson  <span class="fu">===</span> <span class="dt">Failure</span> [<span class="st">&quot;name must be alphabetic&quot;</span>]</code></pre>
<h2 id="fixing-a-polymorphic-record-into-the-identity-functor">Fixing a polymorphic record into the Identity Functor</h2>
<p>If you produced a record using <code>(=:)</code> and <code>(&lt;+&gt;)</code> without providing a type annotation, then its type is something like this:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">record ::</span> <span class="kw">Applicative</span> f <span class="ot">=&gt;</span> <span class="dt">Record</span> [ <span class="fu">&lt;</span>bunch <span class="kw">of</span> stuff<span class="fu">&gt;</span> ] f</code></pre>
<p>The problem is then we can’t do anything with the record that requires us to know what its functor is. For instance, <code>cast</code> will fail. So, we might try to provide a type annotation, but that can be a bit brittle and frustrating to have to do. To alleviate this problem, <code>fixRecord</code> is provided:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">fixRecord ::</span> (forall f<span class="fu">.</span> <span class="kw">Applicative</span> f <span class="ot">=&gt;</span> <span class="dt">Rec</span> rs f) <span class="ot">-&gt;</span> <span class="dt">PlainRec</span> rs</code></pre>]]></description>
    <pubDate>Sat, 06 Apr 2013 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2013-04-06-vinyl-modern-records-for-haskell.html</guid>
</item>
<item>
    <title>Inferring Typing Derivations for the STLC in Haskell</title>
    <link>http://www.jonmsterling.com/posts/2013-04-13-inferring-evidence-for-the-stlc-in-haskell.html</link>
    <description><![CDATA[<p>We can define the STLC at the type-level in Haskell, and then provide a type of derivations (proofs of well-typedness) which is indexed by terms. Further, we can use Haskell’s type classes to infer typing derivations for well-typed terms in the STLC.</p>
<!--MORE-->
<p>First, let us pry open the pandora’s box; some of these wights are more dangerous than others.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE PolyKinds              #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE DataKinds              #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE FunctionalDependencies #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE GADTs                  #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE FlexibleContexts       #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE FlexibleInstances      #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE KindSignatures         #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE LambdaCase             #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE RankNTypes             #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE TypeOperators          #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE UndecidableInstances   #-}</span>
<span class="fu">&gt;</span> <span class="ot">{-# LANGUAGE UnicodeSyntax          #-}</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">module</span> <span class="dt">STLC</span> <span class="kw">where</span></code></pre>
<h3> 
The Syntax of the STLC
</h3>

<p>First, we will begin with a type-free syntax of terms generating a universe with a predicative hierarchy of sets:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">Term</span>
<span class="fu">&gt;</span>   <span class="fu">=</span> <span class="dt">Set</span> <span class="dt">Term</span>       <span class="co">-- ^ predicative sets</span>
<span class="fu">&gt;</span>   <span class="fu">|</span> (<span class="fu">~&gt;</span>) <span class="dt">Term</span> <span class="dt">Term</span> <span class="co">-- ^ the function arrow</span>
<span class="fu">&gt;</span>   <span class="fu">|</span> ℕ              <span class="co">-- ^ natural numbers</span>
<span class="fu">&gt;</span>   <span class="fu">|</span> <span class="dt">Z</span>              <span class="co">-- ^ zero</span>
<span class="fu">&gt;</span>   <span class="fu">|</span> <span class="dt">S</span> <span class="dt">Term</span>         <span class="co">-- ^ successor</span>
<span class="fu">&gt;</span>   <span class="fu">|</span> Λ <span class="dt">Term</span>         <span class="co">-- ^ abstraction</span>
<span class="fu">&gt;</span>   <span class="fu">|</span> (<span class="fu">#</span>) <span class="dt">Term</span> <span class="dt">Term</span>  <span class="co">-- ^ application</span>
<span class="fu">&gt;</span>   <span class="fu">|</span> <span class="dt">V</span> <span class="dt">Term</span>         <span class="co">-- ^ variables</span></code></pre>
<p>It may seem odd that, for instance, we parameterize <code>Set</code> and <code>V</code> by <code>Term</code>, since it’s clear that we should want natural numbers there. But this will get nailed down when we make our family of typing rules.</p>
<p>Contexts are either empty or are extended by a type:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> <span class="dt">Cx</span>
<span class="fu">&gt;</span>   <span class="fu">=</span> <span class="dt">E</span>
<span class="fu">&gt;</span>   <span class="fu">|</span> (<span class="fu">:&gt;</span>) <span class="dt">Term</span> <span class="dt">Cx</span></code></pre>
<h3> 
Typing Rules for the STLC
</h3>

<p>With the addition of a dirty little bit of syntactic sugar, we can now present the typing rules of our system.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> x ⊢ f <span class="fu">=</span> f x
<span class="fu">&gt;</span> <span class="kw">infixr</span> <span class="dv">5</span> ⊢</code></pre>
<p>I’ve decided to arrange these rules in a natural-deduction style presentation. A term of type <code>γ ⊢ x ∈ τ</code> says that “the context <code>γ</code> proves that <code>x</code> is of type <code>τ</code>”; this is called a typing derivation.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">data</span> (∈)<span class="ot"> ::</span> <span class="dt">Term</span> <span class="ot">→</span> <span class="dt">Term</span> <span class="ot">→</span> <span class="dt">Cx</span> <span class="ot">→</span> ★ <span class="kw">where</span></code></pre>
<p>There is an infinite hierarchy of sets, where each is the type of the previous, down to the base case, which is the type of small types.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span>   <span class="dt">TSet</span><span class="ot">  ::</span>           <span class="dt">E</span> ⊢ n ∈ ℕ
<span class="fu">&gt;</span>           <span class="fu">--------------------------------</span>
<span class="fu">&gt;</span>          <span class="ot">→</span>      γ ⊢ <span class="dt">Set</span> n ∈ <span class="dt">Set</span> (<span class="dt">S</span> n)</code></pre>
<p><code>ℕ</code> is a small type.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span>   <span class="dt">TNat</span><span class="ot">  ::</span> <span class="fu">-------------------------------</span>
<span class="fu">&gt;</span>                    γ ⊢ ℕ ∈ <span class="dt">Set</span> <span class="dt">Z</span></code></pre>
<p><code>Z</code> is a natural number.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span>   <span class="dt">TZ</span><span class="ot">    ::</span> <span class="fu">-------------------------------</span>
<span class="fu">&gt;</span>                       γ ⊢ <span class="dt">Z</span> ∈ ℕ</code></pre>
<p>Given a natural number <code>n</code>, <code>S n</code> is also a natural number.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span>   <span class="dt">TS</span><span class="ot">    ::</span>            γ ⊢ n ∈ ℕ
<span class="fu">&gt;</span>           <span class="fu">--------------------------------</span>
<span class="fu">&gt;</span>          <span class="ot">→</span>           γ ⊢ <span class="dt">S</span> n ∈ ℕ</code></pre>
<p>Given a term <code>l</code> of type <code>τ</code> a context extended by <code>σ</code>, <code>Λ l</code> is of type <code>σ ~&gt; τ</code>.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span>   <span class="dt">TLam</span><span class="ot">  ::</span>        σ <span class="fu">:&gt;</span> γ ⊢ l ∈ τ
<span class="fu">&gt;</span>           <span class="fu">--------------------------------</span>
<span class="fu">&gt;</span>          <span class="ot">→</span>       γ ⊢ Λ l ∈ (σ <span class="fu">~&gt;</span> τ)</code></pre>
<p>Given a term <code>f</code> in <code>σ ~&gt; τ</code> and a term <code>x</code> in <code>σ</code>, <code>f # x</code> is in <code>τ</code>.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span>   <span class="dt">TApp</span><span class="ot">  ::</span>  γ ⊢ f ∈ (σ <span class="fu">~&gt;</span> τ) <span class="ot">→</span> γ ⊢ x ∈ σ
<span class="fu">&gt;</span>           <span class="fu">--------------------------------</span>
<span class="fu">&gt;</span>          <span class="ot">→</span>         γ ⊢ f <span class="fu">#</span> x ∈ τ</code></pre>
<p>Now we provide evidence that a variable of a given type is within a context.</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span>   <span class="dt">TVTop</span><span class="ot"> ::</span> <span class="fu">-------------------------------</span>
<span class="fu">&gt;</span>                  τ <span class="fu">:&gt;</span> γ ⊢ <span class="dt">V</span> <span class="dt">Z</span> ∈ τ
<span class="fu">&gt;</span>   <span class="dt">TVPop</span><span class="ot"> ::</span>   <span class="dt">E</span> ⊢ i ∈ ℕ   <span class="ot">→</span>   γ ⊢ <span class="dt">V</span> i ∈ σ
<span class="fu">&gt;</span>           <span class="fu">--------------------------------</span>
<span class="fu">&gt;</span>          <span class="ot">→</span>     τ <span class="fu">:&gt;</span> γ ⊢ <span class="dt">V</span> (<span class="dt">S</span> i) ∈ σ</code></pre>
<h3> 
Computing Typing Derivations for Terms
</h3>

Using <code>-XDataKinds</code> we can construct terms of our lambda calculus using Haskell’s type system as a metalanguage. For instance, <span class="math"><em>λ</em><em>x</em>.  <strong>suc</strong> <em>x</em></span> is encoded as follows:
</h3>

<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="kw">type</span> <span class="dt">PlusOne</span> <span class="fu">=</span> Λ (<span class="dt">S</span> (<span class="dt">V</span> <span class="dt">Z</span>))
<span class="ot">plusOne ::</span> <span class="dt">E</span> ⊢ <span class="dt">PlusOne</span> ∈ (ℕ <span class="fu">~&gt;</span> ℕ)
plusOne <span class="fu">=</span> <span class="dt">TLam</span> (<span class="dt">TS</span> <span class="dt">TVTop</span>)</code></pre>
<p>We of course can also just have our expressions in-line:</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">plusOne&#39; ::</span> <span class="dt">E</span> ⊢ (Λ <span class="dt">S</span> (<span class="dt">V</span> <span class="dt">Z</span>)) ∈ (ℕ <span class="fu">~&gt;</span> ℕ)
plusOne&#39; <span class="fu">=</span> <span class="dt">TLam</span> (<span class="dt">TS</span> <span class="dt">TVTop</span>)</code></pre>
<p>It would be nice if we could get the process of generating typing derivations automated for us! Since it’s the case that the typing derivation for well-typed expressions usually resembles the structure of the term very nicely anyway, this should be possible. We can start with this type class:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">class</span> <span class="dt">Infer</span> (<span class="ot">x ::</span> <span class="dt">Term</span>) (τ <span class="ot">::</span> <span class="dt">Term</span>) (γ <span class="ot">::</span> <span class="dt">Cx</span>) <span class="fu">|</span> x γ <span class="ot">→</span> τ <span class="kw">where</span>
<span class="fu">&gt;</span><span class="ot">   infer ::</span> γ ⊢ x ∈ τ</code></pre>
<p>It turns out that we’ll basically just be recapitulating the typing rules wholesale, in such a way as to get Haskell’s constraint solver to infer them for us:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Infer</span> ℓ ℕ <span class="dt">E</span> <span class="ot">⇒</span> <span class="dt">Infer</span> (<span class="dt">Set</span> ℓ) (<span class="dt">Set</span> (<span class="dt">S</span> ℓ)) γ <span class="kw">where</span>
<span class="fu">&gt;</span>   infer <span class="fu">=</span> <span class="dt">TSet</span> infer
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Infer</span> <span class="dt">Z</span> ℕ γ <span class="kw">where</span>
<span class="fu">&gt;</span>   infer <span class="fu">=</span> <span class="dt">TZ</span>
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Infer</span> n ℕ γ <span class="ot">⇒</span> <span class="dt">Infer</span> (<span class="dt">S</span> n) ℕ γ <span class="kw">where</span>
<span class="fu">&gt;</span>   infer <span class="fu">=</span> <span class="dt">TS</span> infer</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Infer</span> l τ (σ <span class="fu">:&gt;</span> γ) <span class="ot">⇒</span> <span class="dt">Infer</span> (Λ l) (σ <span class="fu">~&gt;</span> τ) γ <span class="kw">where</span>
<span class="fu">&gt;</span>   infer <span class="fu">=</span> <span class="dt">TLam</span> infer
<span class="fu">&gt;</span> <span class="kw">instance</span> (<span class="dt">Infer</span> f (σ <span class="fu">~&gt;</span> τ) γ, <span class="dt">Infer</span> x σ γ) <span class="ot">⇒</span> <span class="dt">Infer</span> (f <span class="fu">#</span> x) τ γ <span class="kw">where</span>
<span class="fu">&gt;</span>   infer <span class="fu">=</span> <span class="dt">TApp</span> infer infer</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="dt">Infer</span> (<span class="dt">V</span> <span class="dt">Z</span>) τ (τ <span class="fu">:&gt;</span> γ) <span class="kw">where</span>
<span class="fu">&gt;</span>   infer <span class="fu">=</span> <span class="dt">TVTop</span>
<span class="fu">&gt;</span> <span class="kw">instance</span> (<span class="dt">Infer</span> i ℕ <span class="dt">E</span>, <span class="dt">Infer</span> (<span class="dt">V</span> i) σ γ) <span class="ot">⇒</span> <span class="dt">Infer</span> (<span class="dt">V</span> (<span class="dt">S</span> i)) σ (τ <span class="fu">:&gt;</span> γ) <span class="kw">where</span>
<span class="fu">&gt;</span>   infer <span class="fu">=</span> <span class="dt">TVPop</span> infer infer</code></pre>
<p>Then, we can make a type for closed expressions that have an inferrable type:</p>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">type</span> <span class="dt">Closed</span> e <span class="fu">=</span> <span class="dt">Infer</span> e τ <span class="dt">E</span> <span class="ot">⇒</span> <span class="dt">E</span> ⊢ e ∈ τ</code></pre>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="fu">fst</span><span class="ot"> ::</span> <span class="dt">Closed</span> (Λ (Λ (<span class="dt">V</span> (<span class="dt">S</span> <span class="dt">Z</span>))))
<span class="fu">fst</span> <span class="fu">=</span> infer</code></pre>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="fu">snd</span><span class="ot"> ::</span> <span class="dt">Closed</span> (Λ (Λ (<span class="dt">V</span> <span class="dt">Z</span>)))
<span class="fu">snd</span> <span class="fu">=</span> infer</code></pre>
<h3>
Appendix: Pretty Pretting
</h3>

<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">instance</span> <span class="kw">Show</span> (γ ⊢ x ∈ t) <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="fu">show</span> (<span class="dt">TSet</span> ℓ) <span class="fu">=</span> <span class="st">&quot;Set&quot;</span> <span class="fu">++</span> (<span class="fu">show</span> <span class="fu">.</span> <span class="dt">Sub</span> <span class="fu">.</span> natToInt <span class="fu">$</span> ℓ)
<span class="fu">&gt;</span>   <span class="fu">show</span> <span class="dt">TNat</span> <span class="fu">=</span> <span class="st">&quot;ℕ&quot;</span>
<span class="fu">&gt;</span>   <span class="fu">show</span> <span class="dt">TZ</span> <span class="fu">=</span> <span class="st">&quot;Z&quot;</span>
<span class="fu">&gt;</span>   <span class="fu">show</span> (<span class="dt">TS</span> n) <span class="fu">=</span> <span class="st">&quot;S (&quot;</span> <span class="fu">++</span> <span class="fu">show</span> n <span class="fu">++</span> <span class="st">&quot;)&quot;</span>
<span class="fu">&gt;</span>   <span class="fu">show</span> (<span class="dt">TLam</span> l) <span class="fu">=</span> <span class="st">&quot;λ. &quot;</span> <span class="fu">++</span> <span class="fu">show</span> l
<span class="fu">&gt;</span>   <span class="fu">show</span> (<span class="dt">TApp</span> f x) <span class="fu">=</span> <span class="st">&quot;(&quot;</span> <span class="fu">++</span> <span class="fu">show</span> f <span class="fu">++</span> <span class="st">&quot;)&quot;</span> <span class="fu">++</span> <span class="st">&quot; &quot;</span> <span class="fu">++</span> <span class="st">&quot;(&quot;</span> <span class="fu">++</span> <span class="fu">show</span> x <span class="fu">++</span> <span class="st">&quot;)&quot;</span>
<span class="fu">&gt;</span>   <span class="fu">show</span> <span class="dt">TVTop</span> <span class="fu">=</span> <span class="st">&quot;v&quot;</span> <span class="fu">++</span> <span class="fu">show</span> (varToInt <span class="dt">TVTop</span>)
<span class="fu">&gt;</span>   <span class="fu">show</span> (<span class="dt">TVPop</span> _ i) <span class="fu">=</span> <span class="st">&quot;v&quot;</span> <span class="fu">++</span> (<span class="fu">show</span> <span class="fu">.</span> <span class="dt">Sub</span> <span class="fu">.</span> varToInt <span class="fu">$</span> i)</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> varToInt ::</span> γ ⊢ <span class="dt">V</span> i ∈ σ <span class="ot">→</span> <span class="dt">Int</span>
<span class="fu">&gt;</span> varToInt <span class="dt">TVTop</span> <span class="fu">=</span> <span class="dv">0</span>
<span class="fu">&gt;</span> varToInt (<span class="dt">TVPop</span> _ i) <span class="fu">=</span> <span class="dv">1</span> <span class="fu">+</span> varToInt i</code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span><span class="ot"> natToInt ::</span> γ ⊢ n ∈ ℕ <span class="ot">→</span> <span class="dt">Int</span>
<span class="fu">&gt;</span> natToInt <span class="dt">TZ</span> <span class="fu">=</span> <span class="dv">0</span>
<span class="fu">&gt;</span> natToInt (<span class="dt">TS</span> i) <span class="fu">=</span> <span class="dv">1</span> <span class="fu">+</span> natToInt i
<span class="fu">&gt;</span> natToInt _ <span class="fu">=</span> <span class="fu">error</span> <span class="st">&quot;non-canonical natural number&quot;</span></code></pre>
<pre class="sourceCode literate haskell"><code class="sourceCode haskell"><span class="fu">&gt;</span> <span class="kw">newtype</span> <span class="dt">Subscript</span> <span class="fu">=</span> <span class="dt">Sub</span> <span class="dt">Int</span>
<span class="fu">&gt;</span> <span class="kw">instance</span> <span class="kw">Show</span> <span class="dt">Subscript</span> <span class="kw">where</span>
<span class="fu">&gt;</span>   <span class="fu">show</span> (<span class="dt">Sub</span> n) <span class="fu">=</span> <span class="fu">fmap</span> trans (<span class="fu">show</span> n) <span class="kw">where</span>
<span class="fu">&gt;</span>     trans <span class="fu">=</span>
<span class="fu">&gt;</span>       \<span class="kw">case</span>
<span class="fu">&gt;</span>         <span class="ch">&#39;0&#39;</span> <span class="ot">→</span> <span class="ch">&#39;₀&#39;</span>
<span class="fu">&gt;</span>         <span class="ch">&#39;1&#39;</span> <span class="ot">→</span> <span class="ch">&#39;₁&#39;</span>
<span class="fu">&gt;</span>         <span class="ch">&#39;2&#39;</span> <span class="ot">→</span> <span class="ch">&#39;₂&#39;</span>
<span class="fu">&gt;</span>         <span class="ch">&#39;3&#39;</span> <span class="ot">→</span> <span class="ch">&#39;₃&#39;</span>
<span class="fu">&gt;</span>         <span class="ch">&#39;4&#39;</span> <span class="ot">→</span> <span class="ch">&#39;₄&#39;</span>
<span class="fu">&gt;</span>         <span class="ch">&#39;5&#39;</span> <span class="ot">→</span> <span class="ch">&#39;₅&#39;</span>
<span class="fu">&gt;</span>         <span class="ch">&#39;6&#39;</span> <span class="ot">→</span> <span class="ch">&#39;₆&#39;</span>
<span class="fu">&gt;</span>         <span class="ch">&#39;7&#39;</span> <span class="ot">→</span> <span class="ch">&#39;₇&#39;</span>
<span class="fu">&gt;</span>         <span class="ch">&#39;8&#39;</span> <span class="ot">→</span> <span class="ch">&#39;₈&#39;</span>
<span class="fu">&gt;</span>         <span class="ch">&#39;9&#39;</span> <span class="ot">→</span> <span class="ch">&#39;₉&#39;</span>
<span class="fu">&gt;</span>         d   <span class="ot">→</span> d</code></pre>]]></description>
    <pubDate>Sat, 13 Apr 2013 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2013-04-13-inferring-evidence-for-the-stlc-in-haskell.html</guid>
</item>
<item>
    <title>A Survey of Phrase Projectivity in the <em>Antigone</em></title>
    <link>http://www.jonmsterling.com/posts/2013-04-28-phrase-projectivity-in-antigone.html</link>
    <description><![CDATA[<p>In this <a href="/pdfs/Antigone-Projectivity.pdf">paper</a>, I demonstrate how, and to what degree, phrase projectivity corresponds with register and meter in Sophocles’s <em>Antigone</em>, by developing a quantitative metric <span class="math">℘</span> for projectivity and comparing it across lyrics, trimeters and anapaests using the data provided by the <a href="http://nlp.perseus.tufts.edu/syntax/treebank/greek.html">Perseus Ancient Greek Dependency Treebank</a>. In the appendices, the formal algorithm for the computations done herein is developed in Haskell.</p>
<!--MORE-->

<p>Read the paper here: <a href="/pdfs/Antigone-Projectivity.pdf">Antigone-Projectivity.pdf</a></p>]]></description>
    <pubDate>Sun, 28 Apr 2013 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2013-04-28-phrase-projectivity-in-antigone.html</guid>
</item>
<item>
    <title>Derivative and Novel Speeches in Plato&#8217;s <em>Symposium</em></title>
    <link>http://www.jonmsterling.com/posts/2013-05-19-derivative-and-novel-speeches-in-platos-symposium.html</link>
    <description><![CDATA[<p>The six speeches of the <em>Symposium</em> may be divided into two sets: on the one hand, there is Phaedrus’s speech and those which are derivative of his, and on the other hand, there are the novel speeches; and these are the ones which reject the previous approaches and propose unique theories of Eros.</p>
<!--MORE-->

<h2 id="phaedrus-and-his-derivatives">Phaedrus and his derivatives</h2>
<p>Phaedrus’s speech may be understood as the basis for a theory of Eros which is developed and augmented all the way through the speeches of Pausanias and Eryximachus. If we put aside Phaedrus’s initial mythological appeals, the main focus of Phaedrus’s speech, then, would seem to be the power of Eros to engender in humans a kind of virtue or fury which they might not have had without the god’s inspiration.</p>
<p>When Pausanias begins, he criticizes Phaedrus for failing to include in his account the fact that Eros is double in nature:</p>
<blockquote>
<p><span lang="gk">εἰπεῖν δ’ αὐτὸν ὅτι Οὐ καλῶς μοι δοκεῖ, ὦ Φαῖδρε, προβεβλῆσθαι ἡμῖν ὁ λόγος, τὸ ἁπλῶς οὕτως παρηγγέλθαι ἐγκωμιάζειν Ἔρωτα. εἰ μὲν γὰρ εἷς ἦν ὁ Ἔρως, καλῶς ἂν εἶχε, νῦν δὲ οὐ γάρ ἐστιν εἷς· μὴ ὄντος δὲ ἑνός ὀρθότερόν ἐστι πρότερον προρηθῆναι ὁποῖον δεῖ ἐπαινεῖν.</span><sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> (180c3–180d1)</p>
</blockquote>
<p>But Pausanias’s analysis is necessarily a refinement of Phaedrus’s, and not a refutation. In fact, Pausanias only adds and does not subtract from Phaedrus’s point; for he simply specifies further both the nature and the origin of the inspiration that Phaedrus discussed, integrating it into his dual understanding of Eros. In Pausanias’s framework, this inspiration is nothing other than the engenderment of concern for virtue in the hearts of lovers and their beloveds; and this is, to be sure, the inspiration which is derived from the Heavenly Eros, as opposed to the other:</p>
<blockquote>
<p><span lang="gk">οὗτός ἐστιν ὁ τῆς οὐρανίας θεοῦ ἔρως καὶ οὐράνιος καὶ πολλοῦ ἄξιος καὶ πόλει καὶ ἰδιώταις, πολλὴν ἐπιμέλειαν ἀναγκάζων ποιεῖσθαι πρὸς ἀρετὴν τόν τε ἐρῶντα αὐτὸν αὑτοῦ καὶ τὸν ἐρώμενον· οἱ δ’ ἕτεροι πάντες τῆς ἑτέρας, τῆς πανδήμου.</span><sup><a href="#fn2" class="footnoteRef" id="fnref2">2</a></sup> (185b5–185c2)</p>
</blockquote>
<p>In this way, Pausanias is one of the refiners of previous ideas. Likewise, Eryximachus fails to present an entirely new approach, but rather starts where he considers Pausanias to have left off on the way to the correct theory:</p>
<blockquote>
<p><span lang="gk">Εἰπεῖν δὴ τὸν Ἐρυξίμαχον, Δοκεῖ τοίνυν μοι ἀναγκαῖον εἶναι, ἐπειδὴ Παυσανίας ὁρμήσας ἐπὶ τὸν λόγον καλῶς οὐχ ἱκανῶς ἀπετέλεσε, δεῖν ἐμὲ πειρᾶσθαι τέλος ἐπιθεῖναι τῷ λόγῳ.</span><sup><a href="#fn3" class="footnoteRef" id="fnref3">3</a></sup> (185e6–196a2)</p>
</blockquote>
<p>In the course of his analysis, Eryximachus proceeds to generalize the existing discourse to encompass wide enough a breadth so as to admit a discussion of Medicine, Music, Athletics, Agriculture, and, in fact, every other affair.</p>
<p>To Eryximachus, then, the two kinds of love that humans may experience in their relationships are only special cases of something much more abstract; that is, Eros is simply the thing which drives opposites to combine. And so when things at variance combine by means of the Heavenly Eros (whether they be extremes of humor, flavor, pitch or temperature, or some other continuum), the result is harmonious and orderly; whereas, when the differing things combine by means of the Common Eros, the result is of disorderliness, harm, and pestilence.</p>
<p>By this means, Eryximachus continues with Pausanias’s program of analyzing which kinds of inspiration are engendered by which kind of Eros, generalizing them to the point where we must understand the Inspiration introduced by Phaedrus as a special case itself of what results from, more abstractly, the joining of things together—in this case, namely, the joining of humans together.</p>
<h2 id="the-novel-speeches">The Novel Speeches</h2>
<p>Aristophanes begins by noting how he intends to pursue a different tack than that those who preceded him:</p>
<blockquote>
<p><span lang="gk">Καὶ μήν, ὦ Ἐρυξίμαχε, εἰπεῖν τὸν Ἀριστοφάνη, ἄλλῃ γέ πῃ ἐν νῷ ἔχω λέγειν ἢ ᾗ σύ τε καὶ Παυσανίας εἰπέτην.</span><sup><a href="#fn4" class="footnoteRef" id="fnref4">4</a></sup> (189c2–189c3)</p>
</blockquote>
<p>The approach of Aristophanes is to develop his theory by providing a mythological backdrop, and then using it to explain the attractions which occur between humans. At the surface, his argument would almost appear in the class of explanations which say that different kinds of love yield different kinds of inspiration, as Pausanias argued. And yet, I think it can be shown to be not so much that, but rather something a bit different.</p>
<p>In enumerating the different kinds of love-pursuit that may occur (that is, men pursuing women, women pursuing men, women pursuing women, and men pursuing men), Aristophanes distinguishes between different kinds of love: when men and women pursue each other, this is the spirit of adultery; when women pursue women, this is the spirit of lesbianism; but when men pursue men, this is manliness:</p>
<blockquote>
<p><span lang="gk">ὅσοι δὲ ἄρρενος τμῆμά εἰσι, τὰ ἄρρενα διώκουσι, καὶ τέως μὲν ἂν παῖδες ὦσιν, ἅτε τεμάχια ὄντα τοῦ ἄρρενος, φιλοῦσι τοὺς ἄνδρας καὶ χαίρουσι συγκατακείμενοι καὶ συμπεπλεγμένοι τοῖς ἀνδράσι, καί εἰσιν οὗτοι βέλτιστοι τῶν παίδων καὶ μειρακίων, ἅτε ἀνδρειότατοι ὄντες φύσει.</span><sup><a href="#fn5" class="footnoteRef" id="fnref5">5</a></sup> (191e1–192a2)</p>
</blockquote>
<p>And so, if we wished to characterize Aristophanes’s analysis within the framework of the dual Eros, it would be the male homosexual relationships which are derived from the Heavenly Eros, and all the others from the Common one. And yet, such a characterization proves quite difficult to argue, if we consider the lines of causality between nature, love and inspiration.</p>
<p>Whereas we right well imagine that Pausanias would consent to the idea it is a person’s nature which determines which kind of Eros will join him to his beloved (or vice versa), and that it is this in turn which determines whether or not his inspiration is virtuous, we cannot say the same of Aristophanes.</p>
<p>For to Aristophanes, the nature of a human (which is to say, whether he or she derived from a man-man, a woman-woman, or a man-woman) determines which Love they will experience; this much provokes no disagreement with the previous discourse, and merely augments it with a comical just-so story. But it is not <em>which</em> Love they experience that inspires them with civic and virtuous concerns, but rather their nature itself:</p>
<blockquote>
<p><span lang="gk">καὶ γὰρ τελεωθέντες μόνοι ἀποβαίνουσιν εἰς τὰ πολιτικὰ ἄνδρες οἱ τοιοῦτοι. ἐπειδὰν δὲ ἀνδρωθῶσι, παιδεραστοῦσι καὶ πρὸς γάμους καὶ παιδοποιίας οὐ προσέχουσι τὸν νοῦν φύσει, ἀλλ’ ὑπὸ τοῦ νόμου ἀναγκάζονται· ἀλλ’ ἐξαρκεῖ αὐτοῖς μετ’ ἀλλήλων καταζῆν ἀγάμοις.</span><sup><a href="#fn6" class="footnoteRef" id="fnref6">6</a></sup> (192a6–192b3)</p>
</blockquote>
<p>It is on account of being derived from a man-man that one is daring and virile, and it is on account of being that way both that one is inclined toward homosexual love, and that one is inspired to participate in the matters of the city. So, the inspiration in Aristophanes’s framework does not derive from the Love, but rather issues directly from the primitive nature of the man himself, by which the kind of Love to be experienced is also determined.</p>
<p>Now then, Agathon begins by dismissing all the previous attempts at explaining Eros as missing the point, by failing to praise the god himself, but rather only congratulating the humans who are affected by him:</p>
<blockquote>
<p><span lang="gk">δοκοῦσι γάρ μοι πάντες οἱ πρόσθεν εἰρηκότες οὐ τὸν θεὸν ἐγκωμιάζειν ἀλλὰ τοὺς ἀνθρώπους εὐδαιμονίζειν τῶν ἀγαθῶν ὧν ὁ θεὸς αὐτοῖς αἴτιος· ὁποῖος δέ τις αὐτὸς ὢν ταῦτα ἐδωρήσατο, οὐδεὶς εἴρηκεν.</span><sup><a href="#fn7" class="footnoteRef" id="fnref7">7</a></sup> (194e4–195a1)</p>
</blockquote>
<p>The analysis provided by Agathon is, to put it briefly, that Eros alights upon those who are soft and beautiful, and that he is young and soft himself. He omits the notion of the dual Eros, and conceives that he looks for the beautiful and the good, and engenders it in everyone he touches.</p>
<p>Not to be outdone by Agathon, Socrates starts off by feining to have misunderstood what an encomium was, having expected to be able to simply say the most beautiful truths that could be said about the subject so well as he could, but being instead put to attribute all the greatest and most beautiful things to the subject, whether or not they are the truth.</p>
<blockquote>
<p><span lang="gk">ἐγὼ μὲν γὰρ ὑπ’ ἀβελτερίας ᾤμην δεῖν τἀληθῆ λέγειν περὶ ἑκάστου τοῦ ἐγκωμιαζομένου, καὶ τοῦτο μὲν ὑπάρχειν, ἐξ αὐτῶν δὲ τούτων τὰ κάλλιστα ἐκλεγομένους ὡς εὐπρεπέστατα τιθέναι· καὶ πάνυ δὴ μέγα ἐφρόνουν ὡς εὖ ἐρῶν, ὡς εἰδὼς τὴν ἀλήθειαν τοῦ ἐπαινεῖν ὁτιοῦν. τὸ δὲ ἄρα, ὡς ἔοικεν, οὐ τοῦτο ἦν τὸ καλῶς ἐπαινεῖν ὁτιοῦν, ἀλλὰ τὸ ὡς μέγιστα ἀνατιθέναι τῷ πράγματι καὶ ὡς κάλλιστα, ἐὰν τε ᾖ οὕτως ἔχοντα ἐάν τε μή· εἰ δὲ ψευδῆ, οὐδὲν ἄρ’ ἦν πρᾶγμα.</span><sup><a href="#fn8" class="footnoteRef" id="fnref8">8</a></sup> (198d3–198e2)</p>
</blockquote>
<p>After some coaxing, Socrates agrees to deliver a praise speech in the way that he sees fit, distinct from the rest. In this way, Socrates wipes clean the slate and establishes his framework as one of the novel ones. Indeed, the theory which he claims to have gotten from Diotima is more divergent from all the previous speeches than any of them differed amongst themselves.</p>
<h2 id="conclusion">Conclusion</h2>
<p>As I have shown, the last three speeches were novel, in that none of them could be combined with the ones that preceded to form a non-contradictory theory of Eros. Whilst nobody should be surprised that Socrates failed to agree with anyone on something, I suggest that in addition to him, it may be no coincidence at all that it was the poets of the company, Agathon and Aristophanes, who came up with original and non-derivative speeches.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>And he said, “It doesn’t seem right to me, O Phaedrus, for the speech to be proposed, that is, for it to be exhorted to just simply praise Eros. For if Eros were indeed singular, then it would be fine; but in fact, he is not singular; and since he is not singular, then it would more correct to say beforehand in what fashion one ought to praise him.”<a href="#fnref1">↩</a></p></li>
<li id="fn2"><p>This is the love from the heavenly goddess, and it’s heavenly itself, and worthy of much both in the city and in private, forcing both the lover and the beloved to have much care for himself in relation to excellence; and the all the others are of the other (love), the one one of common (Aphrodite).<a href="#fnref2">↩</a></p></li>
<li id="fn3"><p>So Eryximuachus said, “It seems to me to be necessarily the case, since Pausanias started into the speech well but failed to finish it satisfactorily, that I must try and add an end to the speech.”<a href="#fnref3">↩</a></p></li>
<li id="fn4"><p>“And yet, O Eryximachus,” said Aristophanes, “I have it in mind to speak in a different way, at least, from how you and Pausanias have spoken.”<a href="#fnref4">↩</a></p></li>
<li id="fn5"><p>And all those which are cuttings from the male pursue men, and so long as they are children, inasmuch as they are slices of a man, love men and delight in lying with them and embracing them, and these are the best of children and youths, inasmuch as they are the most manly by nature.<a href="#fnref5">↩</a></p></li>
<li id="fn6"><p>For indeed, when the grow up, only such men turn out to be politically inclined. And whenever they become men, they desire boys and do not incline themselves toward marriage and the making of children by nature, but rather are compelled by custom; rather, it suffices for them to live out their lives unmarried in each other’s company.<a href="#fnref6">↩</a></p></li>
<li id="fn7"><p>For it seems to me that the ones who have spoken so far were not praising the god, but rather congratulating the men for the goods of which the god is responsible for them; but being what kind of god he himself gave these gifts, nobody has said.<a href="#fnref7">↩</a></p></li>
<li id="fn8"><p>For I in my silliness thought that one ought to say the truth about each god who is being praised, and to begin this thing, and to pick out the most beautiful out of these same things and put them as nicely as possible; and forsooth, I thought very much indeed that I would speak well, on the grounds that I knew the truth about praising something. But, as it would turn out, this is not what is meant by praising something finely, but rather it is to attribute the greatest things to the subject, and the most beautiful, whether it be the case or not; and if they are false, it turns out to be of no account.<a href="#fnref8">↩</a></p></li>
</ol>
</div>]]></description>
    <pubDate>Sun, 19 May 2013 00:00:00 UT</pubDate>
    <guid>http://www.jonmsterling.com/posts/2013-05-19-derivative-and-novel-speeches-in-platos-symposium.html</guid>
</item>

    </channel> 
</rss>
