<?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://jonmsterling.com/</link>
        <description><![CDATA[]]></description>
        <atom:link href="http://jonmsterling.com//rss.xml" rel="self"
                   type="application/rss+xml" />
        <lastBuildDate>Fri, 28 Aug 2009 00:00:00 UT</lastBuildDate>
        <item>
    <title>Implementing Object-Oriented Programming in Pure C</title>
    <link>http://jonmsterling.com//posts/2009-08-28-implementing-object-oriented-programming-in-pure-c.html</link>
    <description><![CDATA[<p>An interesting experiment is to try to implement a system for object-oriented programming in pure C.</p>
<p>My method was to use C structures for classes, where methods are function pointers as members of the structure; instance variables are to be encapsulated (that is, only touched through accessors and mutators). For every class it is necessary to have a constructor and a destructor. Finally, instances of these classes should be referred to by pointers, like in Objective-C.</p>
<p>I decided to implement a rudimentary string class called <code>PString</code>:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode c"><span class="kw">typedef</span> <span class="kw">struct</span> pstring_t {<br />  <span class="co">/*</span><br /><span class="co">   instance variables</span><br /><span class="co">   */</span><br />  <span class="dt">char</span> * chars;<br /><br />  <span class="co">/*</span><br /><span class="co">   instance methods</span><br /><span class="co">   */</span><br />  <span class="dt">int</span> (* length)(<span class="kw">struct</span> pstring_t *);<br />  <span class="dt">char</span> (* characterAtIndex)(<span class="kw">struct</span> pstring_t *, <span class="dt">int</span>);<br />  <span class="dt">char</span> * (* value)(<span class="kw">struct</span> pstring_t *);<br />  <span class="dt">void</span> (* setValue)(<span class="kw">struct</span> pstring_t *, <span class="dt">char</span> *);<br />  <span class="dt">void</span> (* destroy)(<span class="kw">struct</span> pstring_t *);<br />} PString;</code></pre></td></tr></table>
<p>The class <code>PString</code> has one instance variable, a <code>char</code> array called <code>chars</code>. It has five methods: <code>length</code>, <code>characterAtIndex</code>, <code>value</code>, <code>setValue</code>, and <code>destroy</code>. Next, the functions that implement these methods, as well as a constructor, must be declared:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode c">PString * initializePString();<br /><span class="dt">int</span> length(PString * self);<br /><span class="dt">char</span> characterAtIndex(PString * self, <span class="dt">int</span> i);<br /><span class="dt">char</span> * value (PString * self);<br /><span class="dt">void</span> setValue(PString * self, <span class="dt">char</span> * chars);<br /><span class="dt">void</span> destroy(PString * self);</code></pre></td></tr></table>
<p>The first function returns a pointer to an initialized <code>PString</code>. <code>initializePString()</code> allocates memory for the <code>PString</code> and its instance variables, and sets the function pointer members of its structure to the functions declared above:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode c">PString * initializePString() {<br />  PString *str=(PString*)malloc(<span class="kw">sizeof</span>(PString));<br />  str-&gt;chars = (<span class="dt">char</span> *)malloc(<span class="kw">sizeof</span>(<span class="dt">char</span>) * <span class="dv">1</span>);<br />  str-&gt;chars[<span class="dv">0</span>] = '';<br />  str-&gt;length = &amp;length;<br />  str-&gt;characterAtIndex = &amp;characterAtIndex;<br />  str-&gt;value = &amp;value;<br />  str-&gt;setValue = &amp;setValue;<br />  str-&gt;destroy = &amp;destroy;<br />  <span class="kw">return</span> str;<br />}</code></pre></td></tr></table>
<p>Finally, the methods of <code>PString</code> are implemented in the following functions:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode c"><span class="dt">int</span> length(PString * self) {<br />  <span class="kw">return</span> strlen(self-&gt;chars);<br />}<br /><br /><span class="dt">char</span> characterAtIndex(PString * self, <span class="dt">int</span> i) {<br />  <span class="kw">return</span> self-&gt;chars[i];<br />}<br /><br /><span class="dt">char</span> * value(PString * self) {<br />  <span class="kw">return</span> self-&gt;chars;<br />}<br /><br /><span class="dt">void</span> setValue(PString * self, <span class="dt">char</span> * chars) {<br />  free(self-&gt;chars);<br />  self-&gt;chars = (<span class="dt">char</span> *)malloc(<span class="kw">sizeof</span>(<span class="dt">char</span>) * (strlen(chars) + <span class="dv">1</span>));<br />  strcpy(self-&gt;chars, chars);<br />}<br /><br /><span class="dt">void</span> destroy(PString * self) {<br />  free(self-&gt;chars);<br />  free(self);<br />}</code></pre></td></tr></table>
<p>Each method takes a pointer to a <code>PString</code> called <code>self</code>. In object-oriented languages built on top of C, methods take a hidden parameter that references their owner. Right now, using these methods is no better than having normal functions, because you have to enter the self parameter:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode c">PString * str = initializePString();<br />str.setValue(str, <span class="st">&quot;a value&quot;</span>);<br />printf(<span class="st">&quot;string: %s&quot;</span>, str.value(str));<br />str.destroy(str);</code></pre></td></tr></table>
<p>In order to work around this, I created two <code>#define</code> macros: one for methods that take no parameters other than <code>self</code>, and another for those that take one or more:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode c"><span class="ot">#define $(obj,method) obj-&gt;method(obj)</span><br /><span class="ot">#define $(obj,method,args) obj-&gt;method(obj,args)</span></code></pre></td></tr></table>
<p>Now, the code above can be rewritten as:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode c">PString *str = initializePString();<br />$(str, setValue, <span class="st">&quot;a value&quot;</span>);<br />printf(<span class="st">&quot;string: %s&quot;</span>, $(str, value));<br />$(str, destroy);</code></pre></td></tr></table>
<p>It isn’t the prettiest syntax in the world, but it works. You can clone this entire project from <a href="http://github.com/jonsterling/Pragmatic-C/tree/master">Github</a>.</p>]]></description>
    <pubDate>Fri, 28 Aug 2009 00:00:00 UT</pubDate>
    <guid>http://jonmsterling.com//posts/2009-08-28-implementing-object-oriented-programming-in-pure-c.html</guid>
</item>
<item>
    <title>Object-Oriented Programming in C, Mark II</title>
    <link>http://jonmsterling.com//posts/2009-09-07-object-oriented-programming-in-c-mark-two.html</link>
    <description><![CDATA[<p>A few weeks ago, I <a href="http://www.jonmsterling.com/blog/2009/08/28/implementing-object-oriented-programming-in-pure-c.html">showed</a> you how to implement a rudimentary system for object-oriented programming in C using structures and function pointers. That, however, is more of a hacky forcing of C++/Objective-C ideas onto C, and does not represent how C is normally written. Today, we are going to look at how an object model would normally be implemented in C.</p>
<p>This time, instead of implementing a <code>String</code> class, we are going to build a relatively useless Person structure, which can be manipulated using normal C functions. First, we will declare the structure and function prototypes in our header file:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode c"><span class="kw">typedef</span> <span class="kw">struct</span> person_t {<br />  <span class="dt">char</span> * firstName;<br />  <span class="dt">char</span> * lastName;<br />  <span class="dt">int</span> age;<br />} Person;<br /><br /><span class="dt">char</span> * person_getFullName(<span class="dt">char</span> ** dest, Person p);<br />Person * person_addToAge(Person * p, <span class="dt">int</span> years);<br />Person * person_revertToInfancy(Person * p);<br /><span class="dt">void</span> person_sayHello(Person p);</code></pre></td></tr></table>
<p>Now, the helper functions can be implemented:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode c"><span class="dt">char</span> * person_getFullName(<span class="dt">char</span> ** dest, Person p) {<br />  *dest = (<span class="dt">char</span> *)malloc((strlen(p.firstName) + strlen(p.lastName) + <span class="dv">1</span>) * <span class="kw">sizeof</span>(<span class="dt">char</span>));<br /><br />  strcpy(*dest, p.firstName);<br />  strcat(*dest, <span class="st">&quot; &quot;</span>);<br />  strcat(*dest, p.lastName);<br /><br />  <span class="kw">return</span> *dest;<br />}<br /><br />Person * person_addToAge(Person * p, <span class="dt">int</span> years) {<br />  p-&gt;age += years;<br />  <span class="kw">return</span> p;<br />}<br /><br />Person * person_revertToInfancy(Person *p) {<br />  p-&gt;age = <span class="dv">0</span>;<br />  <span class="kw">return</span> p;<br />}<br /><br /><span class="dt">void</span> person_sayHello(Person p) {<br />  <span class="dt">char</span> * fullName;<br />  printf(<span class="st">&quot;Hi! I'm %s! Hello World!</span><span class="ch">\n</span><span class="st">&quot;</span>, person_getFullName(&amp;fullName, p));<br />  free(fullName);<br />}</code></pre></td></tr></table>
<p>Notice that functions that manipulate a <code>Person</code> structure take a pointer to that structure as an argument (this is sort of like <code>self</code> or <code>this</code> in object-oriented programming). Functions that merely use data from a <code>Person</code> structure don’t use a pointer for an argument, because it is unnecessary; it would work if they did (of course, <code>p.member</code> would have to change to <code>p-&gt;member</code>), but it doesn’t make a lot of sense to do it that way.</p>
<p>Now, these functions can be tested as follows:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode c">Person jon;<br />jon.firstName = <span class="st">&quot;Jonathan&quot;</span>;<br />jon.lastName = <span class="st">&quot;Sterling&quot;</span>;<br />jon.age = <span class="dv">17</span>;<br /><br /><span class="dt">char</span> * fullName;<br />person_getFullName(&amp;fullName, jon);<br /><br />printf(<span class="st">&quot;Jon&#8217;s full name: %s</span><span class="ch">\n</span><span class="st">&quot;</span>, fullName);<br />free(fullName);<br /><br />printf(<span class="st">&quot;Jon&#8217;s original age: %i</span><span class="ch">\n</span><span class="st">&quot;</span>, jon.age);<br />printf(<span class="st">&quot;adding 30 years&#8230;</span><span class="ch">\n</span><span class="st">&quot;</span>);<br />person_addToAge(&amp;jon, <span class="dv">30</span>);<br />printf(<span class="st">&quot;Jon&#8217;s new age: %i</span><span class="ch">\n</span><span class="st">&quot;</span>, jon.age);<br /><br />printf(<span class="st">&quot;reverting to infancy&#8230;</span><span class="ch">\n</span><span class="st">&quot;</span>);<br />person_revertToInfancy(&amp;jon);<br />printf(<span class="st">&quot;Jon&#8217;s new age: %i</span><span class="ch">\n</span><span class="st">&quot;</span>, jon.age);<br /><br />person_sayHello(jon);</code></pre></td></tr></table>
<p>The output of that is as follows:</p>
<pre class="numberLines"><code>Jon’s full name: Jonathan Sterling
Jon’s original age: 17
adding 30 years…
Jon’s new age: 47
reverting to infancy…
Jon’s new age: 0
Hi! I’m Jonathan Sterling! Hello World!
</code></pre>
<p>I hope that this tutorial has been educational. As always, you can grab the source to this project on <a href="http://github.com/jonsterling/Structure-Example/tree/master">Github</a>.</p>]]></description>
    <pubDate>Mon, 07 Sep 2009 00:00:00 UT</pubDate>
    <guid>http://jonmsterling.com//posts/2009-09-07-object-oriented-programming-in-c-mark-two.html</guid>
</item>
<item>
    <title>Writing Mac OS X applications in Smalltalk</title>
    <link>http://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>
<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://jonmsterling.com//posts/2009-09-20-writing-mac-os-x-applications-in-smalltalk.html</guid>
</item>
<item>
    <title>On Life and 'Good Enough'</title>
    <link>http://jonmsterling.com//posts/2010-07-10-on-life-and-good-enough.html</link>
    <description><![CDATA[<p>The phrase “good enough” is thrown around in the design community quite a lot these days, usually to disparage the act of <strong>settling</strong> for something that is not perfect, but <strong>good enough</strong>. This is a direct insult to our expectations as consumers for quality.</p>
<p>Indeed, if something that is terrible is <strong>good enough</strong> for me, there follow two consequential facts: that I have bad taste, and that I have shirked the duty of shaping the marketplace through my decisions as a consumer. The thing about <strong>Capitalism</strong> is that it only works when people care enough about the shit they are buying to demand perfection: if perfection is something that is displaced by raw practicality, we have damaged the marketplace and our chances of having <strong>good things</strong>.</p>
<p><strong>Good enough</strong> to a paying customer should always mean that the product is functional, and beautiful (not only with respect to visual design, but also data abstraction), and crafted with love. On the contrary, the word you are looking for when you try to justify the purchase of a substandard product is “best” or “better”: no stipulations are made as to the upper limits of its actual quality. Hence, when someone boasts that his product is the <strong>best of its kind</strong>, a little red flag needs to go up: unless you are an early-adopter (we’ll leave that for another essay), <strong>run away fast</strong>. Because the product certainly isn’t yet <strong>good enough</strong>, or a comparison to similar products would have been unnecessary.</p>
<p>Don’t let poor design make you its bitch, just because it is hard to find an alternative. If there were no systems like Mac OS and iOS, I would be composing this essay on a typewriter: <strong>life is too short for you to be given the run-around by other people’s bad ideas.</strong> And typewriters still work just fine.</p>]]></description>
    <pubDate>Sat, 10 Jul 2010 00:00:00 UT</pubDate>
    <guid>http://jonmsterling.com//posts/2010-07-10-on-life-and-good-enough.html</guid>
</item>
<item>
    <title>A Creative Essay</title>
    <link>http://jonmsterling.com//posts/2010-08-17-a-creative-essay.html</link>
    <description><![CDATA[<blockquote>
<p>You are a factory owner, and as before you own a set of processing machines. Processing machines are just a metaphor for functions; they accept some input and produce some output. Your goal is to combine these processing machines so that they can perform richer, and more complicated tasks. Monads allow you to combine these machines in a pipeline. Arrows allow you to combine them in more interesting ways. The result of this is that you can perform certain tasks in a less complicated and more efficient manner. — “Haskell: Understanding Arrows”</p>
</blockquote>
<p>I started to black out, watching my notepad fall from my fingers as I lost consciousness. I was standing in a pitch-dark holodeck, counting the yellow stripes on the floors and walls. He could not see me, but I spied a man in a white lab-coat wearing a pince-nez, sporting a smart mustache; a few feet away lay a fat man in sweats on a red couch. I laughed out loud (audibly only to myself), for each time the latter man moved his hand, one of his other limbs would involuntarily twitch, shiver or kick.</p>
<p>“Your problem, Herr C.,” I heard the first gentleman say as he paced back and forth, “is that you have no control over the side-effects of your movements.” The fat man whimpered. “Likewise, your motor control is problematic: for instance, when tossing a ball between both hands, you often try to catch before you have finished throwing.”</p>
<p>The fat man shook his head. “But,” he started with a shaky voice, “I’m more flexible than you are. I can do lots of things.”</p>
<p>The gentleman wagged his finger at his patient: “Tut tut, your flexibility is a function of your impurity and inability to think properly; indeed, you would ingest a rock if someone told you it were an apple wrapped in gray cloth. No, I see no hope for you.” He paused.</p>
<p>“In fact, let us try an experiment. You are to make a list of the first one hundred odd numbers, and then recite them; I will do likewise. Perhaps after you see my method, you will realize how hopeless you really are.”</p>
<p>I walked toward Herr C. and watched over his shoulder; he noticed neither my presence nor his own putrid stench. This is what he wrote:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode C"><span class="ot">#include </span><span class="ot">&lt;stdio.h&gt;</span><br /><br /><span class="dt">int</span> main () {<br />  size_t n = <span class="dv">100</span>;<br />  <span class="dt">int</span> odds[n];<br /><br />  size_t i;<br />  <span class="kw">for</span>(i = <span class="dv">0</span>; i &lt; n; ++i) {<br />    odds[i] = <span class="dv">2</span> * i + <span class="dv">1</span>;<br />  }<br /><br />  size_t j;<br />  <span class="kw">for</span>(j = <span class="dv">0</span>; j &lt; n; ++j) {<br />    printf(<span class="st">&quot;%s%i%s&quot;</span>, (j != <span class="dv">0</span> ? <span class="st">&quot;,&quot;</span> : <span class="st">&quot;[&quot;</span>), odds[j], (j == (n<span class="dv">-1</span>) ? <span class="st">&quot;]&quot;</span> : <span class="st">&quot;&quot;</span>));<br />  }<br /><br />  <span class="kw">return</span> <span class="dv">0</span>;<br />}</code></pre></td></tr></table>
<p>The moment he had finished writing, he shouted the following triumphantly:</p>
<pre><code>[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,
 57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,
 107,109,111,113,115,117,119,121,123,125,127,129,131,133,135,137,139,141,143,
 145,147,149,151,153,155,157,159,161,163,165,167,169,171,173,175,177,179,181,
 183,185,187,189,191,193,195,197,199].
</code></pre>
<p><em>“See? I got it right!”</em></p>
<p>“Well done, Herr C.,” replied the man in the pince-nez. “But perhaps you will want to see my solution.” He handed the fat man his notepad.</p>
<pre class="sourceCode"><code class="sourceCode haskell">main <span class="fu">=</span> <span class="fu">print</span> [<span class="dv">2</span><span class="fu">*</span>i <span class="fu">+</span> <span class="dv">1</span> <span class="fu">|</span> i <span class="ot">&lt;-</span> [<span class="dv">0</span><span class="fu">..</span><span class="dv">99</span>]]</code></pre>
<p>Herr C. began to cry; as I watched him, I pitied him. Indeed, I hoped that when I reached his age, my life would not be as disappointing. Despite the emotional state of his patient, the Psychologist was relentless: “That was diverting, was it not? Now we shall each modify our solutions to additionally return the sum of the first one hundred odd numbers. Proceed.”</p>
<p>The fat man rubbed his paper with his sleeve, only smearing his writing with tears. He began:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode c"><span class="ot">#include </span><span class="ot">&lt;stdio.h&gt;</span><br /><br /><span class="dt">int</span> main () {<br />  size_t n = <span class="dv">100</span>;<br />  <span class="dt">int</span> odds[n];<br /><br />  size_t i;<br />  <span class="kw">for</span>(i = <span class="dv">0</span>; i &lt; n; ++i) {<br />    odds[i] = <span class="dv">2</span> * i + <span class="dv">1</span>;<br />  }<br /><br />  size_t j;<br />  <span class="dt">int</span> s = <span class="dv">0</span>;<br />  <span class="kw">for</span>(j = <span class="dv">0</span>; j &lt; n; ++j) {<br />    s = s + odds[j];<br />    printf(<span class="st">&quot;%s%i%s&quot;</span>, (j != <span class="dv">0</span> ? <span class="st">&quot;,&quot;</span> : <span class="st">&quot;[&quot;</span>), odds[j], (j == (n<span class="dv">-1</span>) ? <span class="st">&quot;]&quot;</span> : <span class="st">&quot;&quot;</span>));<br />  }<br /><br />  printf(<span class="st">&quot;</span><span class="ch">\n</span><span class="st">sum: %i&quot;</span>, s);<br /><br />  <span class="kw">return</span> <span class="dv">0</span>;<br />}</code></pre></td></tr></table>
<p>But his efforts were in vain, for though he came up with the right answer, the Psychologist’s solution was far more elegant:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode haskell">main <span class="fu">=</span> <span class="fu">print</span> odds <span class="fu">&gt;&gt;</span> <span class="fu">print</span> (<span class="st">&quot;sum: &quot;</span> <span class="fu">++</span> (<span class="fu">show</span> <span class="fu">.</span> <span class="fu">sum</span>) odds)<br />          <span class="kw">where</span> odds <span class="fu">=</span> [<span class="dv">2</span><span class="fu">*</span>i <span class="fu">+</span> <span class="dv">1</span> <span class="fu">|</span> i <span class="ot">&lt;-</span> [<span class="dv">0</span><span class="fu">..</span><span class="dv">99</span>]]</code></pre></td></tr></table>
<p>With that, the fat man evaporated. As I gasped, the man in the white lab-coat turned toward me: “You probably imagined that I could not see you; the fact that I did not evaluate you until now is unrelated to the time at which I noticed you. You have much to learn, young man.”</p>]]></description>
    <pubDate>Tue, 17 Aug 2010 00:00:00 UT</pubDate>
    <guid>http://jonmsterling.com//posts/2010-08-17-a-creative-essay.html</guid>
</item>
<item>
    <title>Diamonds Wait For No Man</title>
    <link>http://jonmsterling.com//posts/2010-08-17-diamonds-wait-for-no-man.html</link>
    <description><![CDATA[<blockquote>
<p>Here’s to the <strong>crazy ones</strong>. The <strong>misfits</strong>. The <strong>rebels</strong>. The <strong>troublemakers</strong>. The round pegs in the square hole. The ones who see things <strong>differently</strong>. They’re not fond of rules. And they have no respect for the status quo. You can quote them, disagree with them, glorify or vilify them. About the only thing you can’t do is ignore them. Because they <strong>change</strong> things. They push the human race forward. And while some may see them as the <strong>crazy ones</strong>, we see genius. Because the people who are crazy enough to think they can <strong>change the world</strong>, are the ones who do. — Apple Inc.</p>
</blockquote>
<blockquote>
<p>By the way, what have you <strong>done</strong> that’s so great? Do you <strong>create</strong> anything, or just criticize others’ <strong>work</strong> and belittle their motivations? — Steve Jobs</p>
</blockquote>
<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>
<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://jonmsterling.com//posts/2010-08-17-diamonds-wait-for-no-man.html</guid>
</item>
<item>
    <title>FunctionKit: a brave new world</title>
    <link>http://jonmsterling.com//posts/2010-09-17-functionkit-a-brave-new-world.html</link>
    <description><![CDATA[<p>In the past, I have been rather fond of writing about FunctionalKit (library for bringing functional programming constructs to Objective-C). In the past, I have done a lot of work on my own fork of the project, but I have brought that to a close, because I have something that interests me much more: <strong>FunctionKit</strong>, my simpler successor to <strong>FunctionalKit</strong>.</p>
<p><em>Short-attention-span-mercy: If you want to see what I have done, just check out my <a href="http://github.com/jonsterling/FunctionKit">Github repository</a>. But be sure to scroll down to the end of the article to see my neat-o expressive array and dictionary syntax.</em></p>
<p>FunctionKit is still in the early stages, and may change a lot in the future (so what you see in this post may not stay relevant). But I’d like to show you some of the cool things that are possible with it. First of all, FunctionKit depends upon Objective-C++ because it uses templates as well as operator overloading. Instead of giving a boring narrative of the hows and whys, I’m just going to show a few examples.</p>
<h2 id="functions">Functions</h2>
<p>For reasons that will become clear in the Functor section of this article, functions are implemented as blocks wrapped in C++ structs that overload the <code>operator()</code>. The following returns a function: <code>fk::f(^(id val) { return @&quot;hello!&quot;; })</code>. Note that all functions are of one argument only; I find that single-arity functions are easier to work with, and lend themselves better to functional programming. I do realize, however, that without proper function currying, this is a weakness.</p>
<p>Because we are using a C++ struct, functions can also be composed using the <code>*</code> operator, much like the <code>(.)</code> operator of Haskell. <code>fk::f</code> also provides more interesting operators such as <code>&gt;&gt;=</code> and <code>&lt;&lt;=</code> for monadic combinations.</p>
<h3 id="effects">Effects</h3>
<p>Effects are functions that take one argument, and return <code>void</code>. They are included, because sometimes we want to produce side effects, but not get a result. <code>fk::e</code> is similar to <code>fk::f</code>, but should be used sparingly.</p>
<h3 id="predicates">Predicates</h3>
<p>Predicates are functions that take one argument, and return <code>BOOL</code>. <code>fk::p</code> included mainly for filtering functors.</p>
<h2 id="functors">Functors</h2>
<p>The <a href="http://lmgtfy.com/?q=what+is+a+functor">Functor</a> is a really useful way to reason about operations on containers like arrays or option-types; like in FunctionalKit, <code>&lt;Functor&gt;</code> is just a protocol that can be implemented by any class. But its requirements are completely different. Where the <code>&lt;FKFunctor&gt;</code> of FunctionalKit was based on a <code>-map:</code> method which took a block argument, <code>&lt;Functor&gt;</code> in FunctionKit requires only that the implementer expose its contents as an array (which can be mapped over using <a href="http://lmgtfy.com/?q=nsfastenumeration">fast enumeration</a>). Then, FunctionKit defines a function which can lift any function into a functor, defined in terms of a for-loop on top of the exposed container contents.</p>
<p>You will recall that the type signature of a function <span class="math"><em>m</em><em>a</em><em>p</em></span> that lifts another function into a functor is <span class="math"><em>m</em><em>a</em><em>p</em>: : <em>F</em><em>u</em><em>n</em><em>c</em><em>t</em><em>o</em><em>r</em> <em>f</em> ⇒ (<em>a</em> → <em>b</em>) → (<em>f</em> <em>a</em> → <em>f</em> <em>b</em>). </span> Translated into Objective-C parlance, we are looking at a function that takes a closure of type <code>id (^)(id)</code> and returns a new closure of type <code>id &lt;Functor&gt; (^)(id &lt;Functor&gt;)</code>.</p>
<p>That means that any function <code>f</code> can be turned into a new function <code>F</code> that will operate on any collection that implements <code>&lt;Functor&gt;</code>. The utility that does this is called the <code>map</code> function, which will give us a new function to be used on a collection; alternatively, I have allowed for functions to be lifted into a functor implicitly on application by the use of the <code>[]</code> operator instead of <code>()</code> for calling. An example:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode objectivecpp">fk::f f = fk::f(^(NSString *s) {<br />  <span class="kw">return</span> [s stringByAppendingString:<span class="st">@&quot;!&quot;</span>];<br />});<br /><br />fk::f F = map(f);<br /><br />NSArray *arr = [NSArray arrayWithObjects:<span class="st">@&quot;dog&quot;</span>,<span class="st">@&quot;cat&quot;</span>,nil];<br /><br />f(<span class="st">@&quot;dog&quot;</span>);   <span class="co">// =&gt; @&quot;dog!&quot;</span><br />F(arr);      <span class="co">// =&gt; {@&quot;dog!&quot;,@&quot;cat!&quot;}</span><br />map(f)(arr); <span class="co">// =&gt; {@&quot;dog!&quot;,@&quot;cat!&quot;}</span><br />f[arr];      <span class="co">// =&gt; {@&quot;dog!&quot;,@&quot;cat!&quot;}</span></code></pre></td></tr></table>
<h2 id="monads">Monads</h2>
<p>The <a href="http://lmgtfy.com/?q=what+is+a+monad">Monad</a> is another way to map over the contents of a collection, and is a superset of Functor. The <code>&lt;Monad&gt;</code> protocol requires only a <code>-flatten</code> method. Then, functions can be composed monadically using the <code>&gt;&gt;=</code> operator, whose type signature is <span class="math">( ≫  = ): : <em>M</em><em>o</em><em>n</em><em>a</em><em>d</em> <em>m</em> ⇒ (<em>a</em> → <em>m</em> <em>b</em>) → (<em>m</em> <em>a</em> → <em>m</em> <em>b</em>). </span> That is, we take a closure of type <code>id &lt;Monad&gt; (^)(id)</code> and return a new closure of type <code>id &lt;Monad&gt; (^)(id &lt;Monad&gt;)</code>. I’m not going to go into detail on the monadic capabilities of FunctionKit, simply because I don’t encourage the overuse of monads, and not a whole lot of value is added by Monad over Functor. Suffice it to say that just as there is provided a utility to lift pure functions into Functors, Monad provides a utility to lift functions returning collections (constituting monadic combinations) into Functors.</p>
<h2 id="monoids">Monoids</h2>
<p><a href="http://lmgtfy.com/?q=what+is+a+monoid">Monoid</a> is actually one of the most exciting parts of FunctionKit for me. A 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} id &amp;:: Monoid\ m \Rightarrow m\\ \otimes &amp;:: Monoid\ m \Rightarrow m \to m \to m \end{aligned}$</span></p>
<p>For the monoid <span class="math"><em>M</em></span> to be valid, the identity element must be isomorphic to <span class="math">0</span> on the addition of natural numbers, or <span class="math">1</span> on the multiplication of the natural numbers, etc; the binary operator must also be associative:</p>
<p><span class="math">$\begin{aligned} \forall x &amp;\in M.\ &amp;x\otimes id &amp;\equiv id\otimes x \equiv x\\ \forall a,b,c &amp;\in M.\ &amp;(a\otimes b)\otimes c &amp;\equiv a\otimes (b\otimes c) \end{aligned}$</span></p>
<p>The <code>&lt;Monoid&gt;</code> protocol demands that a class expose a <code>zero</code>-value (<span class="math"><em>i</em><em>d</em></span>, <code>+zero</code>), as well as a binary operation that will “append” values to it (<span class="math"> ⊗ </span>, <code>-append:</code>). FunctionKit provides a function for folding any collection (implementing <code>&lt;Functor&gt;</code>): <code>id fold(id &lt;Functor&gt; cont, id acc, id (^f)(id memo, id val))</code>. In essence, whenever we use this function, we are creating an ad-hoc Monoid.</p>
<p>It follows that we could abstract out a lot of repeated logic for the case when we are folding a collection of Monoids by declaring a function <code>id fold_monoid(id &lt;Functor&gt; cont, id &lt;Monoid&gt; (^f)(id &lt;Monoid&gt; memo, id val))</code> that would grab the default <code>zero</code>-value of the monoid for us, but let us provide the logic for the folding itself.</p>
<p>Finally, we can declare an even simpler function that will use the default <code>+zero</code> object and <code>-append:</code> method of the Monoid and just fold our collection like a deck of cards: <code>id fold_monoid_append(id &lt;Functor&gt; cont)</code>. For instance, I was able to implement <code>+[NSDictionary(Functor) functorWithObjects:]</code> (mapping from the underlying <code>NSArray</code> to the Functor) in terms of the <code>fold_monoid_append</code> and <code>NSDictionary(Monoid)</code>:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode objectivecpp">+ (id &lt;Functor&gt;)functorWithObjects:(NSArray *)anArray {<br />  <span class="kw">return</span> fold_monoid_append(anArray);<br />}</code></pre></td></tr></table>
<p>We simple took all of the items in the array (in this case, each item was an <code>NSDictionary</code> with a single key-value pair) and appended them to each other using <code>NSDictionary</code>’s implementation of <code>&lt;Monoid&gt;</code>.</p>
<h2 id="type-fu-boxing-and-unboxing-non-objects">Type-Fu: boxing and unboxing non-objects</h2>
<p>A really important part of FunctionKit is its easy mechanism for boxing and unboxing non-objects using the functions <code>id box&lt;T&gt;(T v)</code> and <code>T unbox&lt;T&gt;(id v)</code>. So, we can use <code>box&lt;CGPoint&gt;(CGPointMake(0.3,1.0))</code>, which will use <code>+[NSValue valueWithCGPoint:]</code> to give us an object, automatically. Supported types are <code>int</code>, <code>float</code>, <code>double</code>, <code>BOOL</code>, <code>const char *</code>, <code>SEL</code>, <code>Class</code>, <code>CGPoint</code>, <code>CGRect</code>, <code>CGSize</code>, <code>NSRange</code>, <code>void*</code>, and <code>id</code> (which gives back the same object either way).</p>
<p><strong>But we can do better…</strong> Of course, with a little luck, the limited type inference capabilities of C++ will allow us instead of typing <code>box&lt;BOOL&gt;(YES)</code> to get <code>[NSNumber numberWithBOOL:YES]</code>, to write <code>box(YES)</code>.</p>
<p><strong>And we can have better array syntax…</strong> I often see really nasty code the moment people start trying to use arrays, especially with non-object types. FunctionKit provides a better way:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode objectivecpp"><span class="kw">template</span> &lt;<span class="kw">typename</span> T&gt; NSArray *fk::arr (T obj1, ...) NS_REQUIRES_NIL_TERMINATION;<br /><span class="kw">template</span> &lt;<span class="kw">typename</span> T&gt; NSArray *fk::lift_arr (T obj);<br /><br /><span class="co">// we started with the following, which would be better represented as a C-array of ints:</span><br />[NSArray arrayWithObjects:<br /> [NSNumber numberWithInt:<span class="dv">2</span>],<br /> [NSNumber numberWithInt:<span class="dv">5</span>],<br /> [NSNumber numberWithInt:<span class="dv">1</span>],<br /> [NSNumber numberWithInt:<span class="dv">45</span>],<br /> nil];<br /><br /><span class="co">// but it could be better, if we are intent on using an NSArray:</span><br />[NSArray arrayWithObjects:box&lt;<span class="dt">int</span>&gt;(<span class="dv">2</span>),box&lt;<span class="dt">int</span>&gt;(<span class="dv">5</span>),box&lt;<span class="dt">int</span>&gt;(<span class="dv">1</span>),box&lt;<span class="dt">int</span>&gt;(<span class="dv">45</span>),nil];<br /><br /><span class="co">// still better:</span><br />[NSArray arrayWithObjects:box(<span class="dv">2</span>),box(<span class="dv">5</span>),box(<span class="dv">1</span>),box(<span class="dv">45</span>),nil];<br /><br /><span class="co">// but check this out:</span><br />fk::arr&lt;<span class="dt">int</span>&gt;(<span class="dv">2</span>,<span class="dv">5</span>,<span class="dv">1</span>,<span class="dv">45</span>,nil);<br /><br /><span class="co">// using C++'s type inference, we can make this even simpler!:</span><br />fk::arr(<span class="dv">2</span>,<span class="dv">5</span>,<span class="dv">1</span>,<span class="dv">45</span>,nil);<br /><br /><span class="co">// FunctionKit also provides a way to lift a single value into an array without having to terminate with nil:</span><br />fk::lift_arr&lt;<span class="dt">int</span>&gt;(<span class="dv">3</span>); <span class="co">// =&gt; [NSArray arrayWithObject:[NSNumber numberWithInt:3]];</span><br /><br /><span class="co">// of course, this is even better:</span><br />fk::lift_arr(<span class="dv">3</span>);</code></pre></td></tr></table>
<p>The problem of arrays is common also in dictionaries. FunctionKit changes all that:</p>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode objectivecpp"><span class="kw">template</span> &lt;<span class="kw">typename</span> K,<span class="kw">typename</span> V&gt; NSDictionary *fk::dict (K k1,...) NS_REQUIRES_NIL_TERMINATION;<br /><span class="kw">template</span> &lt;<span class="kw">typename</span> K,<span class="kw">typename</span> V&gt; NSDictionary *fk::pair (K key, V value);<br /><br /><span class="co">// let's start with a simple key-value pair, where the value is a boolean, and the key is a string:</span><br />[NSDictionary dictionaryWithObject:[NSNumber numberWithBOOL:YES] forKey:<span class="st">@&quot;foo&quot;</span>];<br />[NSDictionary dictionaryWithObject:box&lt;BOOL&gt;(YES) forKey:<span class="st">@&quot;foo&quot;</span>];<br />[NSDictionary dictionaryWithObject:$(YES) forKey:<span class="st">@&quot;foo&quot;</span>];<br />fk::pair&lt;BOOL,NSString *&gt;(YES,<span class="st">@&quot;foo&quot;</span>);<br /><br /><span class="co">// The same concept goes for dictionaries with many pairs</span><br />[NSDictionary dictionaryWithObjectsAndKeys:<br /> [NSNumber numberWithBOOL:YES],<span class="st">@&quot;foo&quot;</span>,<br /> [NSNumber numberWithBOOL:NO],<span class="st">@&quot;bar&quot;</span>,<br /> nil];<br /><br />[NSDictionary dictionaryWithObjectsAndKeys:<br /> box&lt;BOOL&gt;(YES),<span class="st">@&quot;foo&quot;</span>,<br /> box&lt;BOOL&gt;(NO),<span class="st">@&quot;bar&quot;</span>,<br /> nil];<br /><br />fk::dict&lt;BOOL,NSString *&gt;(YES,<span class="st">@&quot;foo&quot;</span>,NO,<span class="st">@&quot;bar&quot;</span>,nil);</code></pre></td></tr></table>
<p>Thanks for reading! The implementation details of parts of this are a bit gnarly, which is why I didn’t go into more detail. If you’re curious, feel free to check out the code on <a
href="http://github.com/jonsterling/FunctionKit">Github</a>!</p>]]></description>
    <pubDate>Fri, 17 Sep 2010 00:00:00 UT</pubDate>
    <guid>http://jonmsterling.com//posts/2010-09-17-functionkit-a-brave-new-world.html</guid>
</item>
<item>
    <title>Thoughts on the future of Cocoa</title>
    <link>http://jonmsterling.com//posts/2010-11-04-thoughts-on-the-future-of-cocoa.html</link>
    <description><![CDATA[<p>So, our tools are pretty great; Objective-C’s dynamicism is glorious, and Cocoa is the most intuitive set of frameworks ever, and Xcode is like a luxury car. Or something.</p>
<p>But everything I’ve just said is false, or at least highly suspect. This is my attempt at proposing steps toward making our tools something really worth boasting of.</p>
<h2 id="the-case-against-cocoa">The Case Against Cocoa</h2>
<p>There are several points I wish to go over.</p>
<h3 id="configuration-over-convention">configuration over convention</h3>
<p>Cocoa is a massive, incredibly powerful conglomerate of frameworks that provides object-interfaces for a great many things. Cocoa is so all-encompassing that it is conceivable to write almost any type of application and link only against the Cocoa frameworks.</p>
<p>Keeping in step with its apparent attempt to be everything to everyone, Cocoa appears to be uncomfortable with the concept of declaring any one <em>configuration</em> as the default. A perfect example of this mentality is how when we are setting up an <code>NSWindow</code>, or loading from <code>NSData</code>, we are compelled to pass in all manner of bitmask combinations in order to specify the behavior of the returned object.</p>
<p>Now, this sort of model would make sense if the majority of time, the configuration we needed was variant; the problem is, however, that most of the time, we are passing in the exact same bitmasks, nearly every time we use these APIs. It is the exception, not the rule, that we should want to configure something outside of convention. (If you want an example of ludicrous configuration potential, check out the block-based enumeration method and block signatures for <code>NSArray</code>: the amount of configuration they throw at you at the start is both astounding and laughable.)</p>
<h3 id="unpredictability">unpredictability</h3>
<p>One of the first things I did when I started to learn my way around Cocoa was to puzzle over the Class Cluster pattern: it took me a while before I could quite wrap my head around how the Cocoa collections API worked. In short, mutable and immutable interfaces are exposed, but objects created are actually instances of internal subclasses whose implementations are opaque. In theory, this is a neat idea, in that it allows the library to make decisions on efficiency that the consumer of the API shouldn’t have to worry about.</p>
<p>In practice, however, this is a nightmare. I, for instance, do not appreciate when <code>[someArray class]</code> returns <code>__NSArray_M</code> or something ridiculous like that. Likewise, I have encountered bugs that are caused by silly things, like the ability to interchange mutable and immutable objects without warnings.</p>
<p>Another instance of unpredictability is how objects are faulted in Core Data. Objective-C’s fast-and-loose polymorphism is a powerful and a dangerous tool: sometimes the fact that we can does not mean that we should. Often, sending a message to a managed object, whence you should expect to be returned an object of some expected type, you really receive some sort of mocked object that is not what you wanted. This is especially inherent when debugging (though the problem can be avoided by using <code>-[NSObject valueForKeyPath:]</code>).</p>
<h3 id="archaic-design">archaic design</h3>
<p>Any feature that adds compile-time checks and contracts to Objective-C is a welcome one, which is why I love protocols so much. Protocols enable something like a less powerful, inverted generic type system, and are indispensable when trying to abstract implementation from interface.</p>
<p>The problem is that because earlier versions of Objective-C did not support protocols, most of our APIs handle this sort of polymorphic behavior by adding categories to the root class.</p>
<p>This is problematic for a few reasons: mainly, though, it makes it much more difficult to enforce constraints, because most objects can be treated as instances of <code>NSObject</code>; all we can do is check whether the object has implemented the required methods at runtime.</p>
<p>Because of this, it is up to us as developers to remember to use objects which implement the right methods with the APIs, for the compiler cannot help us.</p>
<p>The problem is alleviated somewhat with the addition of the formal protocol; we need not check for compliance at runtime, since the compiler will warn us when we pass an incorrect object as an argument whose type specifies some protocol. Yet, I constantly see my colleagues marking their protocol methods as <code>@optional</code>, and checking for implementation on every call. This removes any advantage that the formal protocol gave us in the first place, and is truly counterproductive.</p>
<h4 id="predicate-metalanguages">predicate metalanguages</h4>
<p><code>NSPredicate</code> and Key-Value Coding are really cool features of Cocoa, and can be incredibly useful. And the various collection operators (<code>@avg</code>, <code>@count</code>, etc.) that are parsed in key path predicates are pretty cool. <em>For a language that doesn’t have blocks, that is.</em></p>
<p>This interpreted metalanguage ought to be replaced by a combination of enumeration methods for mapping, reducing, filtering, etc.</p>
<h3 id="mutability-centered-design">mutability-centered design</h3>
<p>In the brand of object-oriented programming that Cocoa subscribes to, we spend a lot of time constructing and configuring objects that will then perform tasks for us. A way to think about it is taking a function of several variables (the fields of our class), and currying it in order to allow less verbose partial application (by setting some of the fields in an instance of our class).</p>
<p>There really isn’t anything wrong with this model inherently, except that the way Cocoa implements it is to emphasize the configuration of objects by mutation instead of planned construction. In many cases, the reason we use the mutable object is that it is the only one we can easily configure.</p>
<p>Immutable objects are difficult to configure, because they require us to think of everything at once, and then pass it in some gigantic method, complete with scary dictionaries and bitmasks. Because it is so much more difficult (and expensive) to configure safer, immutable objects than it is to configure unsafe, mutable objects, the entire API favors unnecessary mutability.</p>
<p>In fact, if the way we initialize objects were changed to be more friendly and conducive toward one-off use (with respect to both ease-of-use and performance), we would find ourselves writing code with mostly immutable objects.</p>
<h2 id="why-cocoa-is-pretty-good">Why Cocoa Is Pretty Good</h2>
<p>Cocoa isn’t all bad. In fact, it has one strong point which sets it above all other platforms: this is its UI libraries. I’ll be the very first in line to criticize the design of these libraries, but it must be recognized that they are what facilitate the creation of the most beautiful expressions of software the world has ever seen.</p>
<p>Because AppKit and UIKit model the design and guidelines of the two most polished environments ever, they are inherently the best systems for producing beautiful user interfaces. I strongly believe that it is because of Cocoa that we have beautiful Mac and iOS applications, where competing platforms have close to zero beautiful applications.</p>
<h2 id="making-our-tools-suck-less">Making Our Tools Suck Less</h2>
<p>What I’m about to suggest represents some dramatic departures from the current Cocoa API design, and will therefore most assuredly never be implemented. But this is my map to Oz.</p>
<h3 id="convention-over-configuration">convention over configuration</h3>
<p>The front of the Cocoa API needs to be simplified dramatically: we should have with simple method signatures that do simple things the way we want to do them 99.99% of the time. Then, let us use the complex messages when we need that extra configuration.</p>
<p>Blocks-based APIs need to stop over-specifying; mapping over an array, for instance, should require a block of single arity, not quadruple. In almost every case, for instance, we will have no desire to break enumeration at some point; hence a pointer to a boolean for halting enumeration is almost always superfluous.</p>
<h3 id="type-constraint-specification-and-composition">type constraint specification and composition</h3>
<p>We need more smart use of protocols: an <code>&lt;NSCollection&gt;</code> API (presumably based around <code>&lt;NSFastEnumeration&gt;</code>) would be welcome. APIs that don’t depend on the idiosyncrasies of internal, hidden concrete subclasses of abstract clusters, would be a breath of fresh air, and the way to get there is by composing protocols. Another benefit would be the ability for developers to design their own, pluggable collections that could be used instead of Cocoa’s existing collection classes. This sort of rigorous separation of interface from implementation would have the added benefit of enforcing that the behavior of APIs be based only on predictable aspects of collections as specified by some composition of protocols.</p>
<h3 id="immutable-design">immutable design</h3>
<p>We need to stop modeling immutable concepts mutably; in order to make this feasible, a few things need to happen.</p>
<p>If this paradigm-shift is to work, it must taste good to API consumers: one of the main reasons APIs use mutable constructs is that it is so painful to initialize objects with everything needed all at once. It’s not that we actually need to mutate properties of an object during its lifecycle: it’s that we want to have a nice way to set them before we use it. Hence, I propose lazy objects, which allow for pseudo-mutable setup, but become locked once they begin their work. A nice way to do this would be to write have an immutable class whose parameters are set at initialization, and wrap it in a generic proxy which would cache mutations in an <code>NSDictionary</code> until things are ready to roll. Then, the proxy would construct an object of the required type and set it up according to the cached mutations. If I feel like it, I may even create a prototype of this model. But be warned: proxies are cool, but they are also scary. <em>So I may change my mind on this one.</em></p>
<h2 id="haters-gonna-hate">Haters Gonna Hate</h2>
<p>There’s more to say, but I’ve said enough for now. I believe that there are a lot of things that need to change in Cocoa, but the still-living-in-the–1980s-NeXTie-thought-police will probably disagree with me. <em>C’est la vie.</em></p>
<p>Namaste,<br />JS</p>]]></description>
    <pubDate>Thu, 04 Nov 2010 00:00:00 UT</pubDate>
    <guid>http://jonmsterling.com//posts/2010-11-04-thoughts-on-the-future-of-cocoa.html</guid>
</item>
<item>
    <title>Of Leeches and Learners</title>
    <link>http://jonmsterling.com//posts/2010-12-04-of-leeches-and-learners.html</link>
    <description><![CDATA[<p>There is a difference. I started thinking about this a while ago, but recent run-ins on the Internet have brought my thoughts to a head on this matter.</p>
<p>So what is this all about? It’s about “noobs”: they’re here, they’re there, they’re everywhere. In software, as certain platforms reach new heights of popularity, the onslaught of confused masses is felt like never before, and <strong><em>yet, we miss a distinction of great importance</em></strong>: the difference between a <em>Learner</em> and a <em>Leech</em>.</p>
<p>The Learner and the Leech have one thing in common: they don’t know something. But the way the two archetypes approach that issue is as opposite as their personalities. The Leech realizes that he has a problem, because he “Hello there i cant mke teh site chaange plz many best regards,, RJ” and he has trouble “(x-code) impirting teh Clas in I-phone XCODE on MAC pC cmputar”. Certainly, realizing the existence of a problem is an admirable step. Indeed, the Leech goes even further, and even asks people for a solution to his problem.</p>
<p>But this is where he distinguishes himself from the Learner; for the Learner realizes that his problem is not that he hasn’t a solution, but that he hasn’t yet understood his problem. Hence, when he asks for help, his question is phrased in terms that will facilitate a more experienced learner to clarify his problem for him. Thence, the solution will follow.</p>
<p>He asks, “What part of this is making <em>X</em> get all weird?” instead of “plz tryin to maek teh simple Rssreader for x-Code, how to rlease object then? thnx”. The Leech asks something that is specific to his desired outcome, but usually over-specifies the circumstances required for success (because he misunderstands the fundamentals of his problem). The Learner, on the other hand, tries to understand his problem in the most general, non-specific terms possible, so that what he learns in that instance will be repeatedly applicable.</p>
<h1 id="being-nice">being nice</h1>
<p>Criticizing a Leech on form (grammar, semantics, spelling, coherence) seems to be considered bad form for a few reasons:</p>
<ol style="list-style-type: decimal">
<li>We were all once beginners.</li>
<li>English is not their first language.</li>
<li>It’s not helpful, and it discourages growth of <em>X</em> question/answer site.</li>
</ol>
<p>At least, so I have heard. In fact, these are all pretty terrible bits of reasoning. That we were all once beginners is irrelevant: in fact, I posit that anyone who truly values learning is <strong><em>always</em></strong> a beginner. What really matters is how we deal with that beginnerhood: are we leeching or learning?</p>
<p>As for English being the second language of many of these people, I remain as steadfastly vengeful as ever. The truth of the matter is that you need to be able to at least write English properly to get anywhere in programming, and to be able to learn from the masters in your field. I know from personal experience that one need not even be close to verbal fluency to be able to write acceptable prose in a foreign language. Hence, I will not exhibit empathy for those who write English like baboons.</p>
<p>The language issue is really an issue of respect: when you write outstandingly poorly while asking for help, you are telling your potential teachers exactly what you think they are worth.</p>
<p>The most interesting of all the assumptions is that criticism of these people is not helpful. For in order to understand this issue, it must be clear what the possible end-states are:</p>
<ul>
<li>That the Leech be turned into a Learner.s</li>
<li>That he should go away, really, just leave. Oh my god. Thank Aqua Buddha.</li>
</ul>
<p>I think that blunt correction and criticism (<strong><em>criticism without correction is never helpful</em></strong>) will serve to make one of these two things happen to everyone within the Leech community. For in fact, some Leeches are capable of being turned toward Learning, and I suspect that these are the ones who will respond positively to sharp criticism from someone they admire (I know I do!). Upon being criticized sharply, the remaining Leeches will become angry and emotional; if they are criticized often enough, they will become discouraged and leave the rest of the community alone. <em>Thank God.</em></p>
<p>The ones who leave never to come back are the ones that we most wanted to be rid of:</p>
<ul>
<li>They clutter our favorite websites.</li>
<li>They make us sad during our morning coffee.</li>
<li>They drive us to the bottle.</li>
<li>They drive down the cost of labor by their willingness to work for crumbs.</li>
</ul>
<p><strong>Problem solved.</strong></p>]]></description>
    <pubDate>Sat, 04 Dec 2010 00:00:00 UT</pubDate>
    <guid>http://jonmsterling.com//posts/2010-12-04-of-leeches-and-learners.html</guid>
</item>
<item>
    <title>JSBag: A Modern Class Cluster</title>
    <link>http://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>
<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"><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"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode ObjectiveC">- (id)copyWithZone:(NSZone *)zone {<br />  <span class="kw">return</span> [[JSBag allocWithZone:zone] initWithCollection:<span class="kw">self</span>];<br />}<br /><br />- (id)mutableCopyWithZone:(NSZone *)zone {<br />  <span class="kw">return</span> [[JSMutableBag allocWithZone:zone] initWithCollection:<span class="kw">self</span>];<br />}</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://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://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>
<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://jonmsterling.com//posts/2011-02-04-making-your-web-app-not-suck.html</guid>
</item>
<item>
    <title>On the reading of U.GUD in Sumerian stock phrases</title>
    <link>http://jonmsterling.com//posts/2011-03-09-on-the-reading-of-U.GUD-in-sumerian-stock-phrases.html</link>
    <description><![CDATA[<p>In two common Sumerian stock phrases, there is the problem of the word <code>níŋ-U.GUD</code>, which can be read as either <code>níŋ-ul</code> or <code>níŋ-du7</code>. The first reading means something like “ancient/traditional things”, and the second reading means something along the lines of “propriety” or “appropriate things”.</p>
<p>The two common formulae are:</p>
<pre><code>(1) níŋ-U.GUD-e pa        mu-na-è
    niŋ??=e     pa=0      mu-na-e-0
    ??=LOCT     CVNE=ABS  CP-DAT3-manifest-ABS3I
    'For him, he made manifest the ancient things.'
    'For him, he made manifest the appropriate things.'


(2) ur-saŋ   níŋ-U.GUD-e gù        ba-a-dé
    ursaŋ=0  niŋ??=e     gu=0      ba-?-de-0
    hero=VOC ??=LOCT     voice=ABS CP-ERG2-pour-ABS3I
    'Hero, you called for (=pour voice) for the ancient things.'
    'Hero, you called for propriety.'
</code></pre>
<p><strong>Formula 2</strong> appears in the Stele of the Vultures of Eannatum (albeit in slightly altered form):</p>
<pre><code>é-an-na-túm á tuku-e mu-pàd-da &lt;d&gt;nin-ŋír-sú-ka-ke4
'I, powerful Eannatum, called by Ningirsu,'
é-an-na-túm-me kur a-ne-šè ŋá-̵ŋá-dè
'(I) Eannatum, in order to lay down the land before him,'
níŋ-ul-lí-a-da gù nam-mi-dé
'I called for (?/ proclaimed) the ancient things!'
</code></pre>
<p>The main difference beyond the use of the comitative instead of the locative-terminative is that in this instance, we get a longer form of <code>ul</code> (<code>ul-lí</code>), wherefore we know that <code>du7</code> is not a plausible reading for this instance.</p>
<p><strong>Formula 1</strong> gets a similar break in Ur-Namma:</p>
<pre><code>&lt;d&gt;nanna dumu-sag &lt;d&gt;en-líl-lá lugal-a-ni
'For his master Nanna, sweet son of Enlil:'
ur-&lt;d&gt;namma nita kal-ga lugal úri&lt;ki&gt;-ma
'Ur-Namma, a mighty man, King of Ur,'
lugal ki-en-gi ki-uri-ke4 lú é &lt;d&gt;nanna in-dù-a
'King of Sumer and Akkad, who built Nanna's Temple:'
níŋ úl-lí-a-ke4 pa mu-na-è
'He made manifest the things of the distant past.'
</code></pre>
<p>Again, there is a slight difference from the more common formula (the extra genitive, <code>uli-ak=e</code> instead of <code>uli=e</code>). But the basic meaning here is quite clear.</p>
<p>Because we find both Formulae (with slight variation) occasionally using longer stems of <code>ul</code>, which are incompatible with a reading <code>du7</code>, it is tempting to say that the correct reading is <code>ul</code> instead of <code>du7</code> in all instances of these formulae. But I err on the side of caution: in all instances which have only <code>níŋ-U.GUD-e</code>, <code>du7</code> as a reading for <code>U.GUD</code> works just fine semantically. So, either <code>ul</code> is the correct reading in all cases, or there are variants of the formulae which also refer to propriety.</p>]]></description>
    <pubDate>Wed, 09 Mar 2011 00:00:00 UT</pubDate>
    <guid>http://jonmsterling.com//posts/2011-03-09-on-the-reading-of-U.GUD-in-sumerian-stock-phrases.html</guid>
</item>
<item>
    <title>Recurring Memes: Cooperation and Sexism</title>
    <link>http://jonmsterling.com//posts/2011-06-14-recurring-memes-cooperation-and-sexism.html</link>
    <description><![CDATA[<p>It seems like every few months, there is a new article which is widely circulated, about one of two things:</p>
<ul>
<li><p>how “nerds” (what a lot of us have inexplicably taken on as a positive term for our demographic) are awful to each other, and need to lighten up and return to the old days of mutual good-feelings and social hacking. We apparently need to be more “excellent to each other”.</p></li>
<li><p>how women are constantly and consistently disrespected in our community. They don’t get invited to conferences, or some brave guy tried to hit on them at a party, or they are assumed to not be software developers, or some other grievance.</p></li>
</ul>
<h2 id="be-excellent-to-each-other">Be Excellent To Each Other</h2>
<p>I’ve encountered my fair share of impatient disrespect on the internet. It tends to come from two sorts of people:</p>
<ul>
<li>idiot teenagers who think they know something, and refuse to stop arguing obscure topics with experts</li>
<li>cranky old veterans who disagree with unorthodox ideas</li>
</ul>
<p>The first category is unforgivable, but I have a lot of respect for the veterans. Whether I’m right or not (I usually am under the impression that I am), discussions I’ve had with cranky veterans have always been extremely valuable to me. These are folks who have been doing this stuff for so long that they are bound to at least have really good reasons for their strongly-held opinions. I like to figure things out the hard way, so I often ignore their advice; but frequently (though not always), I’ll come back several months later and decide that the cranky veteran was right. I’m actually glad these folks are so hard on me, since it impresses the importance of their opinion upon me all the more.</p>
<p>I don’t take rude comments from my betters personally, and neither should you. You should listen very carefully to what they say, and you might learn something.</p>
<p>I believe that arguments are more effective the more civilly they are conducted; there comes a point, however, when someone must be given license to throw away the rules of politeness in order to inflict intellectual justice on a small soul like me.</p>
<p>My experience is that if you interpret things correctly, most of our community really <em>are</em> excellent to each other. And yet it remains so fashionable go complain and moralize about the state of our interpersonal skills.</p>
<h2 id="sexist-atmosphere">Sexist Atmosphere</h2>
<p>The other irritating meme that keeps coming up is that our community is <em>horrible</em> to women. Apparently, we are supposed to:</p>
<ul>
<li>invite conference speakers based on their gender, as opposed to their fame and talent</li>
<li>assume that all women we meet at or near technical conferences are software developers</li>
<li>not acknowledge a woman’s gender in a friendly way</li>
<li>ignore our sexual imperative and never introduce ourselves to women at technical conferences with the purpose of establishing a more-than-friendly relationship with them</li>
<li>never try to explain our work in layman’s terms to women who have introduced themselves to us as nontechnical beauty-models</li>
</ul>
<p>Many of the examples brought up by ever-active sexism-crusaders either involve false pretenses and entrapment (in the case of our supermodels-pretending-to-be-Luddites), or idiot douche-bag teenagers trying to be macho. I’ve never met a real male software craftsman who is not thrilled at the idea of more women entering the workforce, or who would behave inappropriately to a female colleague, or who would purposely exclude women from panels or conferences. Sexism in our industry is tragic when it happens, but there seems to be a lot more complaining about sexism than there is actual sexism going on.</p>
<h3 id="sidebar">Sidebar</h3>
<blockquote>
<p>“You don’t know what it’s like being a woman. Grow a vagina and then come back and argue with me about sexism.”</p>
</blockquote>
<p>Ugh. I’ve heard this desperate argument more times than I’d like to admit. The idea that men have no say in discussions of sexism (discussions, mind you, which are designed to generalize and condemn members of my sex as bigots) is laughable. If I need a vulva in order to discuss gender-politics with you, I think I may be in need of a better conversational partner.</p>
<p>Let’s make nice stuff, and stop politicizing every little thing. In essence, I’m asking the brigade of angry sexism-crusaders to stop assuming that the average male software developer is a pig: I suppose I could say that I’m asking them to be “excellent” to us.</p>]]></description>
    <pubDate>Tue, 14 Jun 2011 00:00:00 UT</pubDate>
    <guid>http://jonmsterling.com//posts/2011-06-14-recurring-memes-cooperation-and-sexism.html</guid>
</item>
<item>
    <title>More useful snapping for NSSlider</title>
    <link>http://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>
<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"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode ObjectiveC">-[NSSliderCell startTrackingAt:inView:],<br />-[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"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode ObjectiveC"><span class="kw">@interface</span> JSSnappingSliderCell : NSSliderCell<br /><span class="kw">@end</span><br /><br /><span class="kw">@implementation</span> JSSnappingSliderCell<br /><span class="dt">static</span> <span class="dt">const</span> CGFloat kSnappingZone = <span class="fl">10.</span>0f;<br /><br />- (BOOL)continueTracking:(NSPoint)lastPoint at:(NSPoint)currentPoint inView:(NSView *)controlView <br />{<br />  CGPoint snapToPoint = currentPoint;<br /><br />  <span class="kw">for</span> (NSUInteger i = <span class="dv">0</span>; i &lt; <span class="kw">self</span>.numberOfTickMarks; i++)<br />  {<br />    NSRect tickMarkRect = [<span class="kw">self</span> rectOfTickMarkAtIndex:i];<br />    <span class="kw">if</span> (ABS(tickMarkRect.origin.x - currentPoint.x) &lt;= kSnappingZone) <br />    {<br />      snapToPoint = [<span class="kw">self</span> rectOfTickMarkAtIndex:i].origin;<br />      <span class="kw">break</span>;<br />    }<br />  }<br /><br />  <span class="kw">return</span> [<span class="kw">super</span> continueTracking:lastPoint at:snapToPoint inView:controlView];<br />}<br /><br /><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://jonmsterling.com//posts/2011-11-13-more-useful-snapping-for-nsslider.html</guid>
</item>
<item>
    <title>The Road Not Taken: Trite Retrospection</title>
    <link>http://jonmsterling.com//posts/2011-12-23-the-road-not-taken.html</link>
    <description><![CDATA[<p>It seems fitting to title this with a cliché, in conformance with the entire genre of essays like this one: the self-indulgent end-of-year reflections on the things you chose to do, and the things you chose not to do, complete with trite moralisms and anecdotes of personal growth.</p>
<p>I’m currently in my second year at UC Berkeley as a Linguistics major, and next year will be my last. As I am drawn nearer to the point at which I likely leave academia (and linguistics) forever, I realize that over the past few years, I’ve had a lot of little turning points which have marked changes in my life which can’t be reversed. Each of these aborted paths is, however, but a siren along the route toward what I really want out of life.</p>
<h2 id="jazz-musician">Jazz Musician</h2>
<p>When I was in middle school, I played piano in the “Jazz” band there, and I thought I was pretty hot shit. As I learned when I entered high school, I was quite the opposite. My brother was the guitarist in the Jazz band there, and my family had developed a relationship with the director. I suspect that when I auditioned to join the group, I was admitted not because I was any good (for I wasn’t), but because the director saw my brother’s talent and had high hopes that I was capable of being coached toward an equal level of skill.</p>
<p>The story from there is one that is often repeated in trite sports sagas: this awkward kid who can’t do shit is thrown in with the wolves, makes a fool of himself every day, and at some point starts to get it. Not to say that he had become adequate; rather, he had grown enough that his teammates gained some level of respect for him, and his coach treated him like family.</p>
<p>Then came Junior year. Most of the kids who were better than me had graduated, and I had been promoted to rhythm section leader. I was starting to come into my own. The veterans in the group looked at me with that “Yeah, you’re all right” face, and, even though I knew that I was only OK, I started to think that I was pretty great. On a few occasions, my real inadequacy surfaced and I remembered how much I really sucked. The problem was that a lot of people sucked even more than I did, so they mistakenly looked up to me.</p>
<p>Senior year, I actually was some hot shit. I was the assistant director of the band, and the director of the quintet. And I was actually pretty OK. Whereas in previous years, I had the dubious honor at all the festivals of winning “soloist awards” (which were basically given to anyone who got up and played something, no matter how poorly), this year I was getting recognized as best pianist in show, or best rhythm section soloist, and so forth. That was actually pretty neat; it tickled my ego to be distinguished among young musicians who have today gone on to accomplish great things.</p>
<p>The last time I played piano in concert, I was accompanied by Mel Brown himself, the grandfather of the Portland Jazz scene; during my solo on the Dexter Gordon tune, he smiled at me in surprise, and afterwards he shook my hand and told me how proud he was of me, how far he knew I had come. And then I was done with that part of my life. I was going to college to study something entirely different.</p>
<h2 id="linguist-assyriologist-classicist">Linguist, Assyriologist, Classicist</h2>
<p>I didn’t apply to enough colleges, because I was overconfident that Harvard, Yale, Cornell or Berkeley would admit me. Though the latter two were afterthoughts, they were the only ones to offer me admittance. Cornell seemed like a bleak place that would make me insane, and I’d had my heart set on Boston; I ended up “settling” for Berkeley.</p>
<p>As soon as I got here, I dived into things that I consider awesome: I became the only undergraduate to take Sumerian, for one. And the story repeats itself: my professor nurtured my interest in the field of Cuneiform languages, provided me with research opportunities, and did everything in his power to help me progress in my path to graduate school.</p>
<p>Next semester, my Sumerian professor goes on sabbatical, but he has invented a cuneiform reading group to essentially keep our class going; I suspect that he did this at least partly in order to help me continue in my studies.</p>
<p>I also took Ancient Greek, and was distinguished as the best student of elementary Greek in that year by the man who wrote the textbook. This year, I continued my Greek education with mostly the same group of Classics comrades in reading Plato’s <em>Apology</em>. And as the rest of them move on next semester to read Homer, I abandon them for the purpose of knocking out school requirements so I can graduate early. And because I simply won’t take a class that goes past 4PM.</p>
<p>So, I bade my Greek comrades (τοῖς Ἑλληνικοῖς ἑταίροις ταῖς τε Ἑλληνικαῖς) farewell after exams, and went on my way. Next year, I shall have to do the same to the graduate students and geriatric auditors in my Sumerian group, of whom I’ve grown quite fond in the past few years.</p>
<h2 id="&#955;x.-software-developer-x-landowner-x-retiree-x">λ<em>x</em>. Software Developer <em>x</em> ⇒ Landowner <em>x</em> ∧ Retiree <em>x</em></h2>
<p>I’m graduating school early (and probably not doing graduate school) not because I don’t like it, but because I cannot justify going into debt tens of thousands of dollars every year, when I could be making tens of thousands of dollars every year. The life of the starving academic is not for me: by the time I would be experienced enough to deserve tenure, I doubt that the construct will even exist. The way things are going, after all the real professors die, I should think they’ll be replaced by streams of graduate students who are used until exhaustion, and then replaced.</p>
<p>I’m also not leaving because I think that software development is terribly more interesting than Linguistics.<sup><a href="#fn1" class="footnoteRef" id="fnref1">1</a></sup> In fact, there are many aspects of it which I find dull, and even irritating (such as dealing with clients, who will always be several years behind in understanding things). But I’m pretty all right at software development, and at least for now, that profession commands high wages.</p>
<p><a href="http://5by5.tv/mistakes/31">Mike Monteiro says</a> that when faced with a life decision, you must always choose the path which will lead you to your ultimate goal; and whatever that ultimate goal is, you must own it entirely. My goal isn’t to be a software developer living the startup high any more then it is to be a starving academic, or a starving musician: my goal is to be a landowner with a respectable income, who can afford to have a nice house, clothes made for him, a few dogs, and some sheep and goats.</p>
<p>In the meantime, I’m happy to be whatever kind of software developer people are paying for. If that means writing soul-crushing apps for clueless clients, and having to use the word “gamification” with a straight face, then so be it. When I’m seventy, I doubt that retirement will even be “a thing” anymore for most people; I figure I’ll have won the game if I can build for myself a life full of my favorite anachronisms: savings, land, and my own quiet house.</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn1"><p>I’m often asked to comment on how similar software development and learning languages are to each other, and how each must inform the other in my mind. But that couldn’t be farther from the truth; in fact, I would go as far as to say that studying languages is vastly more closely related to studying music than it is to programming computers. A common misconception which has been driven so deeply into popular opinion that resisting it is almost futile. (Certain subfields of <em>linguistics proper</em> which are so far out of the intellectual reach of the layman as to be irrelevant to these conversations, such as syntax and logical semantics, however, do bear a passing resemblance to certain formal aspects of computer science.) <a href="#fnref1" class="footnoteBackLink">↩</a></p></li>
</ol>
</div>]]></description>
    <pubDate>Fri, 23 Dec 2011 00:00:00 UT</pubDate>
    <guid>http://jonmsterling.com//posts/2011-12-23-the-road-not-taken.html</guid>
</item>
<item>
    <title>Expressing Church Pairs with Types</title>
    <link>http://jonmsterling.com//posts/2011-12-28-expressing-church-pairs-with-types.html</link>
    <description><![CDATA[<blockquote>
<strong>Summary.</strong> 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 F<span class="math">$_\omega$</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.
</blockquote>


<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"><code class="sourceCode haskell">&gt; <span class="ot">{-# LANGUAGE MultiParamTypeClasses #-}</span><br />&gt; <span class="ot">{-# LANGUAGE Rank2Types #-}</span><br />&gt; <span class="ot">{-# LANGUAGE FlexibleInstances #-}</span><br />&gt; <span class="ot">{-# LANGUAGE IncoherentInstances #-}</span><br />&gt; <span class="ot">{-# LANGUAGE UnicodeSyntax #-}</span></code></pre>
<pre class="sourceCode"><code class="sourceCode haskell">&gt; <span class="kw">module</span> <span class="dt">ChurchPair</span> <span class="kw">where</span><br />&gt; <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"><code class="sourceCode haskell">&gt; <span class="kw">class</span> <span class="dt">TypeOr</span> &#945; &#946; &#947;</code></pre>
<p>and inhabit it with the proper combinations:</p>
<pre class="sourceCode"><code class="sourceCode haskell">&gt; <span class="kw">instance</span> <span class="dt">TypeOr</span> &#945; &#946; &#945;<br />&gt; <span class="kw">instance</span> <span class="dt">TypeOr</span> &#945; &#946; &#946;</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"><code class="sourceCode haskell">&gt; <span class="kw">type</span> <span class="dt">Pair</span> &#945; &#946; <span class="fu">=</span> <span class="ot">&#8704;</span> &#947;<span class="fu">.</span> <span class="dt">TypeOr</span> &#945; &#946; &#947; <span class="ot">&#8658;</span> (&#945; <span class="ot">&#8594;</span> &#946; <span class="ot">&#8594;</span> &#947;) <span class="ot">&#8594;</span> &#947;</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"><code class="sourceCode haskell">&gt; <span class="ot">pair </span><span class="ot">::</span> &#945; <span class="ot">&#8594;</span> &#946; <span class="ot">&#8594;</span> <span class="dt">Pair</span> &#945; &#946;<br />&gt; 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"><code class="sourceCode haskell">&gt; <span class="fu">fst</span><span class="ot"> </span><span class="ot">::</span> <span class="dt">Pair</span> &#945; &#946; <span class="ot">&#8594;</span> &#945;<br />&gt; <span class="fu">fst</span> p <span class="fu">=</span> p <span class="fu">$</span> \x y <span class="ot">&#8594;</span> x</code></pre>
<pre class="sourceCode"><code class="sourceCode haskell">&gt; <span class="fu">snd</span><span class="ot"> </span><span class="ot">::</span> <span class="dt">Pair</span> &#945; &#946; <span class="ot">&#8594;</span> &#946;<br />&gt; <span class="fu">snd</span> p <span class="fu">=</span> p <span class="fu">$</span> \x y <span class="ot">&#8594;</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"><code class="sourceCode haskell">&gt; fst' p <span class="fu">=</span> p <span class="fu">const</span><br />&gt; snd' 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"><code class="sourceCode haskell"><span class="ot">badAccessor </span><span class="ot">::</span> <span class="dt">Pair</span> &#945; &#946; <span class="ot">&#8594;</span> <span class="dt">String</span><br />badAccessor p <span class="fu">=</span> p <span class="fu">$</span> \x y <span class="ot">&#8594;</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://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://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>
<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"><code class="sourceCode haskell">&gt; <span class="ot">{-# LANGUAGE PolyKinds #-}</span><br />&gt; <span class="ot">{-# LANGUAGE MultiParamTypeClasses #-}</span><br />&gt; <span class="ot">{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}</span><br />&gt; <span class="ot">{-# LANGUAGE UndecidableInstances #-}</span><br />&gt; <span class="ot">{-# LANGUAGE FunctionalDependencies #-}</span><br />&gt; <span class="ot">{-# LANGUAGE RankNTypes #-}</span><br />&gt; <span class="ot">{-# LANGUAGE TypeOperators #-}</span><br />&gt; <span class="ot">{-# LANGUAGE DeriveFunctor #-}</span><br />&gt; <span class="ot">{-# LANGUAGE UnicodeSyntax #-}</span></code></pre>
<pre class="sourceCode"><code class="sourceCode haskell">&gt; <span class="kw">module</span> <span class="dt">GeneralizedMonoid</span> <span class="kw">where</span><br />&gt; <span class="kw">import</span> <span class="dt">Control.Monad</span> (<span class="kw">Monad</span>(<span class="fu">..</span>))<br />&gt; <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"><code class="sourceCode haskell">&gt; <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">&#8594;</span> comp <span class="fu">id</span> <span class="kw">where</span><br />&gt; <span class="ot">  munit </span><span class="ot">::</span> <span class="fu">id</span> <span class="fu">~&gt;</span> m<br />&gt; <span class="ot">  mjoin </span><span class="ot">::</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"><code class="sourceCode haskell">&gt; <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><br />&gt; <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><br />&gt; <span class="kw">instance</span> <span class="kw">Num</span> a <span class="ot">&#8658;</span> <span class="dt">Monoidy</span> (<span class="ot">&#8594;</span>) (,) () (<span class="dt">Sum</span> a) <span class="kw">where</span><br />&gt;   munit _ <span class="fu">=</span> <span class="dt">Sum</span> <span class="dv">0</span><br />&gt;   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<br />&gt; <span class="kw">instance</span> <span class="kw">Num</span> a <span class="ot">&#8658;</span> <span class="dt">Monoidy</span> (<span class="ot">&#8594;</span>) (,) () (<span class="dt">Product</span> a) <span class="kw">where</span><br />&gt;   munit _ <span class="fu">=</span> <span class="dt">Product</span> <span class="dv">1</span><br />&gt;   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"><code class="sourceCode haskell">&gt; <span class="kw">newtype</span> <span class="dt">Id</span> &#945; <span class="fu">=</span> <span class="dt">Id</span> {<span class="ot"> runId </span><span class="ot">::</span> &#945; } <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"><code class="sourceCode haskell">&gt; <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> <span class="ot">&#8704;</span> &#945;<span class="fu">.</span> f &#945; <span class="ot">&#8594;</span> g &#945; }</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"><code class="sourceCode haskell">&gt; <span class="kw">newtype</span> <span class="dt">FC</span> f g &#945; <span class="fu">=</span> <span class="dt">FC</span> {<span class="ot"> runFC </span><span class="ot">::</span> f (g &#945;) }</code></pre>
<p>Now, let us define some type <code>T</code> which should be a monad:</p>
<pre class="sourceCode"><code class="sourceCode haskell">&gt; <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><span class="ot">::</span> a } <span class="kw">deriving</span> (<span class="kw">Show</span>, <span class="kw">Functor</span>)<br />&gt; <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><br />&gt;   munit <span class="fu">=</span> <span class="dt">NT</span> <span class="fu">$</span> <span class="dt">Wrapper</span> <span class="fu">.</span> runId<br />&gt;   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"><code class="sourceCode haskell">ghci<span class="fu">&gt;</span> mjoin (munit (), <span class="dt">Sum</span> <span class="dv">2</span>)<br />      <span class="dt">Sum</span> <span class="dv">2</span><br />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>)<br />      <span class="dt">Product</span> <span class="dv">6</span><br />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>)<br />      <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"><code class="sourceCode haskell">&gt; <span class="ot">(&lt;+&gt;) </span><span class="ot">::</span> <span class="dt">Monoidy</span> (<span class="ot">&#8594;</span>) (,) () m <span class="ot">&#8658;</span> m <span class="ot">&#8594;</span> m <span class="ot">&#8594;</span> m<br />&gt; (<span class="fu">&lt;+&gt;</span>) <span class="fu">=</span> <span class="fu">curry</span> mjoin</code></pre>
<pre class="sourceCode"><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><br />      <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"><code class="sourceCode haskell">&gt; <span class="kw">instance</span> <span class="dt">Monoidy</span> (<span class="ot">&#8594;</span>) (,) () m <span class="ot">&#8658;</span> <span class="dt">Monoid</span> m <span class="kw">where</span><br />&gt;   mempty <span class="fu">=</span> munit ()<br />&gt;   mappend <span class="fu">=</span> <span class="fu">curry</span> mjoin</code></pre>
<pre class="sourceCode"><code class="sourceCode haskell">&gt; <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">&#8658;</span> <span class="kw">Monad</span> m <span class="kw">where</span><br />&gt;   <span class="fu">return</span> x <span class="fu">=</span> runNT munit <span class="fu">$</span> <span class="dt">Id</span> x<br />&gt;   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"><code class="sourceCode haskell">ghci<span class="fu">&gt;</span> mappend mempty (<span class="dt">Sum</span> <span class="dv">2</span>)<br />      <span class="dt">Sum</span> <span class="dv">2</span><br />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>)<br />      <span class="dt">Product</span> <span class="dv">6</span><br />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><br />      <span class="dt">Wrapper</span> {runWrapper <span class="fu">=</span> <span class="st">&quot;hello&quot;</span> }<br />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><br />      <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" class="footnoteBackLink">↩</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" class="footnoteBackLink">↩</a></p></li>
</ol>
</div>]]></description>
    <pubDate>Thu, 12 Jan 2012 00:00:00 UT</pubDate>
    <guid>http://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://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>
<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"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode ObjectiveC"><span class="kw">@protocol</span> OrderedCollection[V]<br />- (V)at:(NSUInteger)index;<br />- (<span class="dt">void</span>)put:(V)object;<br /><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"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode ObjectiveC"><span class="kw">@protocol</span> OrderedCollection<br />- (instancetype)at:(NSUInteger)index;<br />- (<span class="dt">void</span>)put:(id)object;<br /><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"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode ObjectiveC">NSString &lt;OrderedCollection&gt; *strings = ...;<br />[strings put:<span class="st">@&quot;hello,&quot;</span>];<br />[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"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode ObjectiveC"><span class="kw">for</span> (NSString *upperString in [strings.uppercaseString substringFromIndex:<span class="dv">1</span>])<br />  NSLog(<span class="st">@&quot;%@&quot;</span>, upperString);<br /><br /><span class="co">// =&gt; ELLO,</span><br /><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"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode ObjectiveC"><span class="kw">@protocol</span> OrderedCollection &lt;NSFastEnumeration&gt;<br />- (instancetype)at:(NSUInteger)index;<br />- (<span class="dt">void</span>)put:(id)object;<br /><span class="kw">@end</span><br /><br /><span class="kw">@protocol</span> MapCollection &lt;NSFastEnumeration&gt;<br />- (instancetype)at:(id)key;<br />- (<span class="dt">void</span>)put:(id)object at:(id)key;<br /><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"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20<br />21<br />22<br />23<br />24<br />25<br />26<br />27<br />28<br />29<br />30<br />31<br />32<br />33<br />34<br />35<br />36<br />37<br />38<br />39<br />40<br />41<br />42<br />43<br />44<br />45<br />46<br />47<br />48<br />49<br />50<br />51<br />52<br />53<br />54<br />55<br />56<br />57<br />58<br />59<br />60<br />61<br />62<br />63<br />64<br />65<br />66<br />67<br />68<br />69<br />70<br />71<br />72<br />73<br />74<br />75<br />76<br />77<br />78<br />79<br />80<br />81<br />82<br />83<br />84<br />85<br />86<br />87<br />88<br />89<br />90<br />91<br />92<br />93<br />94<br />95<br />96<br />97<br />98<br />99<br />100<br />101<br />102<br />103<br />104<br />105<br />106<br />107<br />108<br />109<br />110<br />111<br />112<br />113<br />114<br />115<br />116<br />117<br />118<br />119<br />120<br />121<br />122<br />123<br />124<br />125<br />126<br />127<br />128<br />129<br />130<br />131<br />132<br />133<br />134<br />135<br />136<br />137<br />138<br />139<br />140<br />141<br />142<br />143<br />144<br />145<br />146<br />147<br />148<br />149<br />150<br />151<br />152<br />153<br />154<br />155<br />156<br />157<br />158<br />159</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode ObjectiveC"><span class="kw">@interface</span> CollectionProxy : NSObject<br />@property (strong) id target;<br />@property (assign) class elementClass;<br /><br />- (id)initWithTarget:(id)target;<br /><br />+ (Class)collectionClass;<br /><br /><span class="co">// Subclasses will provide a technique for mapping an element in one</span><br /><span class="co">// collection to a new element in another.</span><br />- (<span class="dt">void</span>)appendMappedObject:(id)mapped fromObject:(id)original toBuffer:(id)buffer;<br /><br /><span class="co">// Subclasses may wish to map over an object derivable from object</span><br /><span class="co">// given in fast enumeration. For instance, dictionaries map over</span><br /><span class="co">// values, rather than keys.</span><br />- (id)redirectIteration:(id)object;<br /><span class="kw">@end</span><br /><br /><span class="kw">@implementation</span> CollectionProxy<br />@synthesize target, elementClass;<br /><br />- (id)initWithTarget:(id)aTarget {<br />  <span class="kw">if</span> ((<span class="kw">self</span> = [<span class="kw">super</span> init]))<br />    target = aTarget;<br /><br />  <span class="kw">return</span> <span class="kw">self</span>;<br />}<br /><br />- (id)init {<br />  <span class="kw">return</span> [<span class="kw">self</span> initWithTarget:[<span class="kw">self</span>.class.collectionClass new]];<br />}<br /><br />- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {<br />  <span class="kw">if</span> ([<span class="kw">self</span>.class.collectionClass instancesRespondToSelector:sel])<br />    <span class="kw">return</span> [<span class="kw">self</span>.class.collectionClass instanceMethodSignatureForSelector:sel];<br /><br />  <span class="kw">return</span> [<span class="kw">self</span>.elementClass instanceMethodSignatureForSelector:sel];<br />}<br /><br />- (BOOL)respondsToSelector:(SEL)aSelector {<br />  <span class="kw">return</span> [<span class="kw">super</span> respondsToSelector:aSelector] <br />      || [target respondsToSelector:aSelector] <br />      || [<span class="kw">self</span>.elementClass instancesRespondToSelector:aSelector];<br />}<br /><br />- (<span class="dt">void</span>)forwardInvocation:(NSInvocation *)invocation {<br />  <span class="co">// If the collection itself responds to this selector (like if</span><br />  <span class="co">// someone sent -count), we'll forward the message to it.</span><br />  <span class="kw">if</span> ([target respondsToSelector:invocation.selector])<br />    <span class="kw">return</span> [invocation invokeWithTarget:target];<br /><br />  <span class="co">// If the invocation returns void, we still want to invoke it, but</span><br />  <span class="co">// we don't want to try to do anything with its results.</span><br />  BOOL returnsValue = strcmp(<span class="st">&quot;v&quot;</span>, invocation.methodSignature.methodReturnType) != <span class="dv">0</span>;<br />  id buffer = returnsValue ? [<span class="kw">self</span>.class.collectionClass new] : nil;<br /><br />  <span class="kw">for</span> (id obj in target) {<br />    [invocation retainArguments];<br />    [invocation invokeWithTarget:[<span class="kw">self</span> redirectIteration:obj]];<br /><br />    <span class="dt">void</span> *outPtr = NULL;<br />    <span class="kw">if</span> (returnsValue) {<br />      [invocation getReturnValue:&amp;outPtr]; <br /><br />      <span class="co">// We marshall the return value of the invocation back into our space.</span><br />      id mapped;<br />      <span class="kw">if</span> ((mapped = objc_unretainedObject(outPtr)))<br />        [<span class="kw">self</span> appendMappedObject:mapped fromObject:obj toBuffer:buffer];<br />    }<br />  }<br /><br />  <span class="kw">if</span> (returnsValue &amp;&amp; [buffer count] &gt; <span class="dv">0</span>) {<br />    <span class="co">// Build up a new proxy of the same kind to return.</span><br />    CollectionProxy *proxy = [[<span class="kw">self</span>.class alloc] initWithTarget:buffer];<br /><br />    <span class="co">// We marshall the proxy out of our space and set it as the return</span><br />    <span class="co">// value of our invocation.</span><br />    invocation.returnValue = &amp;(<span class="dt">const</span> <span class="dt">void</span> *){<br />      objc_unretainedPointer(proxy)<br />    };<br />  }<br />}<br /><br /><span class="co">// Default behavior</span><br /><br />+ (Class)collectionClass { <span class="kw">return</span> nil; }<br />- (<span class="dt">void</span>)appendMappedObject:(id)mapped fromObject:(id)original toBuffer:(id)buffer {}<br />- (id)redirectIteration:(id)object { <span class="kw">return</span> object; }<br /><br /><span class="kw">@end</span><br /><br /><span class="kw">@interface</span> OrderedCollectionProxy : CollectionProxy<br /><span class="kw">@end</span><br /><br /><span class="kw">@interface</span> MapCollectionProxy : CollectionProxy<br /><span class="kw">@end</span><br /><br /><br /><span class="kw">@implementation</span> OrderedCollectionProxy<br /><br />- (id)initWithTarget:(id)target {<br />  <span class="kw">if</span> ((<span class="kw">self</span> = [<span class="kw">super</span> initWithTarget:target]) &amp;&amp; [target count])<br />    <span class="kw">self</span>.elementClass = [[target lastObject] class];<br /><br />  <span class="kw">return</span> <span class="kw">self</span>;<br />}<br /><br />+ (Class)collectionClass {<br />  <span class="kw">return</span> [NSMutableArray class];<br />}<br /><br />- (<span class="dt">void</span>)appendMappedObject:(id)mapped fromObject:(id)original toBuffer:(id)buffer {<br />  [buffer addObject:mapped];<br />}<br /><br />- (<span class="dt">void</span>)put:(id)object {<br />  assert([object isKindOfClass:<span class="kw">self</span>.elementClass]);<br />  [<span class="kw">self</span>.target addObject:object];<br />}<br /><br />- (instancetype)at:(NSUInteger)index {<br />  <span class="kw">return</span> [<span class="kw">self</span>.target objectAtIndex:index];<br />}<br /><br /><span class="kw">@end</span><br /><br /><br /><span class="kw">@implementation</span> MapCollectionProxy<br /><br />- (id)initWithTarget:(id)target {<br />  <span class="kw">if</span> ((<span class="kw">self</span> = [<span class="kw">super</span> initWithTarget:target]) &amp;&amp; [target count])<br />    <span class="kw">self</span>.elementClass = [[target allValues].lastObject class];<br /><br />  <span class="kw">return</span> <span class="kw">self</span>;<br />}<br /><br /><br />+ (Class)collectionClass {<br />  <span class="kw">return</span> [NSMutableDictionary class];<br />}<br /><br />- (<span class="dt">void</span>)appendMappedObject:(id)mapped fromObject:(id)key toBuffer:(id)buffer {<br />  [buffer setObject:mapped forKey:key];<br />}<br /><br />- (id)redirectIteration:(id)key {<br />  <span class="kw">return</span> [<span class="kw">self</span>.target objectForKey:key];<br />}<br /><br />- (<span class="dt">void</span>)put:(id)object at:(id)key {<br />  assert([object isKindOfClass:<span class="kw">self</span>.elementClass]);<br />  [<span class="kw">self</span>.target setObject:object forKey:key];<br />}<br /><br />- (instancetype)at:(id)key {<br />  <span class="kw">return</span> [<span class="kw">self</span>.target objectForKey:key];<br />}<br /><br /><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"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16<br />17<br />18<br />19<br />20</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode ObjectiveC"><span class="kw">@interface</span> NSObject (Collections)<br />+ (instancetype)orderedCollection;<br />+ (instancetype)mapCollection;<br /><span class="kw">@end</span><br /><br /><span class="kw">@implementation</span> NSObject (Collections)<br /><br />+ (instancetype)orderedCollection {<br />  CollectionProxy *proxy = [OrderedCollectionProxy new];<br />  proxy.elementClass = <span class="kw">self</span>;<br />  <span class="kw">return</span> proxy<br />}<br /><br />+ (instancetype)mapCollection {<br />  CollectionProxy *proxy = [MapCollectionProxy new];<br />  proxy.elementClass = <span class="kw">self</span>;<br />  <span class="kw">return</span> proxy;<br />}<br /><br /><span class="kw">@end</span></code></pre></td></tr></table>
<h2 id="see-it-in-action">See it in action</h2>
<table class="sourceCode"><tr><td class="lineNumbers" title="Click to toggle line numbers" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }"><pre>1<br />2<br />3<br />4<br />5<br />6<br />7<br />8<br />9<br />10<br />11<br />12<br />13<br />14<br />15<br />16</pre></td><td class="sourceCode"><pre class="sourceCode"><code class="sourceCode ObjectiveC">NSURL &lt;MapCollection&gt; *sites = (id)[NSURL mapCollection];<br />[sites put:[NSURL URLWithString:<span class="st">@&quot;http://www.jonmsterling.com/&quot;</span>]<br />        at:<span class="st">@&quot;jon&quot;</span>];<br />[sites put:[NSURL URLWithString:<span class="st">@&quot;http://www.reddit.com/&quot;</span>]<br />        at:<span class="st">@&quot;reddit&quot;</span>];<br />[sites put:[NSURL URLWithString:<span class="st">@&quot;git://github.com/jonsterling/Foam.git&quot;</span>]<br />        at:<span class="st">&quot;foam_repo&quot;</span>];<br /><br />NSURL *jonsSite = [sites at:<span class="st">@&quot;jon&quot;</span>];<br /><span class="co">// =&gt; http://www.jonmsterling.com/</span><br /><br />NSString &lt;MapCollection&gt; *schemes = (id)sites.scheme.uppercaseString;<br /><span class="co">/* =&gt; { jon: &quot;HTTP://&quot;,</span><br /><span class="co">        reddit: &quot;HTTP://&quot;,</span><br /><span class="co">        foam_repo: &quot;GIT://&quot; }</span><br /><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" class="footnoteBackLink">↩</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" class="footnoteBackLink">↩</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" class="footnoteBackLink">↩</a></p></li>
</ol>
</div>]]></description>
    <pubDate>Sun, 05 Feb 2012 00:00:00 UT</pubDate>
    <guid>http://jonmsterling.com//posts/2012-02-05-typed-collections-with-self-types-in-objective-c.html</guid>
</item>

    </channel> 
</rss>

