<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

 <title>Colin Drake</title>
 <link href="http://colindrake.me/atom.xml" rel="self"/>
 <link href="http://colindrake.me/"/>
 <updated>2016-04-01T17:43:53-04:00</updated>
 <id>http://colindrake.me</id>
 <author>
   <name>Colin Drake</name>
   <email>colin.f.drake@gmail.com</email>
 </author>

 
 <entry>
   <title>You Could Have Invented Objects</title>
   <link href="http://colindrake.me/2016/03/21/you-could-have-invented-objects/"/>
   <updated>2016-03-21T00:00:00-04:00</updated>
   <id>http://colindrake.me/2016/03/21/you-could-have-invented-objects</id>
   <content type="html">&lt;p&gt;I’ve always been interested in programming languages and paradigms.&lt;/p&gt;

&lt;p&gt;Usually, this manifests itself in reading about functional programming, the Lisp
family of languages, compilers, and lately,
&lt;a href=&quot;https://en.wikipedia.org/wiki/Protocol_(object-oriented_programming)&quot;&gt;protocol-oriented programming&lt;/a&gt;
with Swift and Clojure.&lt;/p&gt;

&lt;p&gt;However, I recently found myself circling back to a paradigm that most of us take
for granted: object-oriented programming. After reading many articles on the
&lt;a href=&quot;http://c2.com/cgi/wiki&quot;&gt;c2.com&lt;/a&gt; wiki, I ended up playing around with a
&lt;a href=&quot;http://pharo.org/&quot;&gt;Pharo&lt;/a&gt; Smalltalk installation on my Mac. While I can’t
say that I plan on using Smalltalk for my next project, my curiosity was piqued.&lt;/p&gt;

&lt;p&gt;The sheer level of &lt;a href=&quot;https://www.youtube.com/watch?v=HOuZyOKa91o&quot;&gt;interaction and introspection&lt;/a&gt;
supported by the Pharo object
system/environment was amazing. So naturally, I wondered if I could build a small
home-grown object system myself… The following is a short exploration in creating a (primitive) object system in Swift.&lt;/p&gt;

&lt;h2 id=&quot;overview&quot;&gt;Overview&lt;/h2&gt;

&lt;p&gt;Let’s take a step back to CS 101: what are some of the basic, core facets of object oriented programming? &lt;a href=&quot;https://en.wikipedia.org/wiki/Object-oriented_programming&quot;&gt;Wikipedia&lt;/a&gt;
lists a few:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Message Passing&lt;/li&gt;
  &lt;li&gt;Encapsulation&lt;/li&gt;
  &lt;li&gt;Composition/Inheritance/Delegation&lt;/li&gt;
  &lt;li&gt;Open Recusion&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, pretend for a while that &lt;code class=&quot;highlighter-rouge&quot;&gt;class&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;struct&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;enum&lt;/code&gt;, and friends don’t
exist in Swift. What type of (more fundamental) structure is capable of expressing
the above features? How about functions, or closures?&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Message Passing: perform “procedures” dispatching based off of a passed-in message name parameter&lt;/li&gt;
  &lt;li&gt;Encapsulation: closures already capture lexical scope&lt;/li&gt;
  &lt;li&gt;Composition: isn’t this what the functional paradigm is about? 😃&lt;/li&gt;
  &lt;li&gt;Inheritance/Delegation: simply call another closure!&lt;/li&gt;
  &lt;li&gt;Open Recusion: well… we’ll get there…&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;With the above in mind, let’s jump in.&lt;/p&gt;

&lt;h2 id=&quot;message-passing&quot;&gt;Message Passing&lt;/h2&gt;

&lt;p&gt;For our purposes, we’ll define a &lt;code class=&quot;highlighter-rouge&quot;&gt;Message&lt;/code&gt; as a &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt; and an object as some
type that interprets a &lt;code class=&quot;highlighter-rouge&quot;&gt;Message&lt;/code&gt; to (possibly) return some value.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;typealias&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Message&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;typealias&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Message&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Any&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Unfortunately, as you can see, we’ll be… sidestepping the type
system for this hacky experiment 😉&lt;/p&gt;

&lt;p&gt;Let’s start by defining our first “object” that can respond to messages.
Our convention will be as such: messages that are not known by the objects will
return &lt;code class=&quot;highlighter-rouge&quot;&gt;nil&lt;/code&gt;, and all others will return some value.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;obj1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Message&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;switch&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;do-something&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;sure!&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;nil&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Great! Now we have an arbitrary object that can dispatch to code based off of messages.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;obj1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;do-something&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; &quot;sure!&quot;&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;obj1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;do-other-thing&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; nil&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;This buys us the simplest benefit of OOP: the ability to abstract out procedures
packaged with data based off of some known interface.&lt;/p&gt;

&lt;h2 id=&quot;encapsulation&quot;&gt;Encapsulation&lt;/h2&gt;

&lt;p&gt;The above code snippets are fine and dandy, but we don’t really want to be
defining our own objects ad-hoc all the time: we all know the benefits of using
classes as reusable blueprints for creating objects. Luckily for us, this can
be represented as… you guess it – another closure!&lt;/p&gt;

&lt;p&gt;For us, a “class” is really just comprised of a constructor function that returns
a new object/instance (another closure, as demonstrated above).&lt;/p&gt;

&lt;p&gt;Additionally, closures can capture the lexical environment, so any parameters
passed into our constructor function can act as a sort of read-only instance
variable for our internal object. In a nutshell, we get encapsulation for free.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// Constructors are uppercase by convention...&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;Person&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;firstName&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;lastName&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;ln&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Message&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Any&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;switch&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;full-name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ln&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;description&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&amp;lt;Person&amp;gt;&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;nil&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;…and to use it…&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// Define a person and test out methods...&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;p&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;firstName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Colin&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;lastName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Drake&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;full-name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; &quot;Colin Drake&quot;&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;description&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; &quot;&amp;lt;Person&amp;gt;&quot;&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;address&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;     &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; nil&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Immutability is nice, but we can also package up mutable state pretty easily.
All it really takes is copying the constructor parameters to a mutable local variable.
Take, for instance, this &lt;code class=&quot;highlighter-rouge&quot;&gt;Counter&lt;/code&gt; example:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;Counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;initial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Message&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;switch&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;count&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;increment&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;decrement&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
            &lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;counter&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;nil&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h2 id=&quot;composition-inheritance-and-delegation&quot;&gt;Composition, Inheritance, and Delegation&lt;/h2&gt;

&lt;p&gt;One of the biggest attractions to OOP is the ability for code reuse. Both object
composition and inheritance allow for this, but in two different ways. Composition
allows us to delegate messages out to another object, and inheritance allows us
to do the same, but specifically to some object we deem a “parent” to the current one.&lt;/p&gt;

&lt;p&gt;We’ll implement inheritance as a simple delegated call to our known parent, if
the object itself doesn’t know how to interpret the message. Most languages and
object systems have this as a built-in to the syntax/model, but we’ll keep things
simple and explicit.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;/// Represents possible speeds at which atheletes can run.&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;enum&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;RunSpeed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Slow&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Fast&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;/// Represents an Athelete, a subclass of Person.&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;Athelete&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;firstName&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;lastName&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;ln&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                  &lt;span class=&quot;n&quot;&gt;runningSpeed&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;rs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;RunSpeed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// Create a person &quot;super&quot; object to delegate to.&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;superInstance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;firstName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fn&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;lastName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ln&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Message&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Any&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;switch&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// Simple instance method.&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;how-fast?&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rs&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// Override behavior of a Person.&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;description&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&amp;lt;A &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rawValue&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;-Moving Athelete&amp;gt;&quot;&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// Delegate unknown messages to superclass.&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;superInstance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;And example usage:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;a&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Athelete&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;firstName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Colin&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;nv&quot;&gt;lastName&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Drake&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                 &lt;span class=&quot;nv&quot;&gt;runningSpeed&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Slow&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;how-fast?&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; RunSpeed.Slow&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;description&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; &quot;&amp;lt;A Slow-Moving Athelete&amp;gt;&quot;&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;full-name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;   &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; &quot;Colin Drake&quot; (a Person method)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h2 id=&quot;open-recursion&quot;&gt;Open Recursion&lt;/h2&gt;

&lt;p&gt;Within the context of OOP, open recursions refers to the ability to dispatch
methods on yourself. As an object, you want the ability to call one of your own
methods, but you don’t want the responsibility of needing to know the
whereabouts of the raw implementation yourself.&lt;/p&gt;

&lt;p&gt;This self-referential dispatch is pretty trivial (and IMHO more elegant) in a Lisp-like
language, but we’re in the Swift world: a closure recursively calling itself will
raise a compiler error indicating that a value is attempting to use itself in its
own definition.&lt;/p&gt;

&lt;p&gt;To get around this, we’ll use the &lt;a href=&quot;http://stackoverflow.com/a/94056&quot;&gt;Y-combinator&lt;/a&gt;,
a function that “enables recursion, when you can’t refer to the function from
within itself.” It’s a bit tricky to define, but easy to use.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;// h/t: http://bit.ly/1U2N0HP&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;R&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;R&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;R&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;R&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;t&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;f&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;t&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;With that mess out of the way, let’s try to use it in the OOP context
to recursively call our dispatch function:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;Cat&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;name&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;age&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;a&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Y&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;dispatch&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Message&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Any&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;?&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;switch&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;n&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; the Cat&quot;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;description&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
                &lt;span class=&quot;c1&quot;&gt;// Dispatch on ourself.&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;me&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;dispatch&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;
                &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&amp;lt;A Feline named &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;me&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&amp;gt;&quot;&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;default&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;nil&lt;/span&gt;
            &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;leo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Cat&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;name&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Leo&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;age&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;leo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; &quot;Leo the Cat&quot;&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;leo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;description&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; &quot;&amp;lt;A Feline named Leo the Cat&amp;gt;&quot;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The value of this is that we don’t care if we implemented the method we’re
calling, or if it is delegated to a super instance. All of that is abstracted
from us via the call to &lt;code class=&quot;highlighter-rouge&quot;&gt;dispatch&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;And with that, our simple homegrown object system is complete! However,
I’ve got one more trick up my sleeve…&lt;/p&gt;

&lt;h2 id=&quot;goodies&quot;&gt;Goodies&lt;/h2&gt;

&lt;p&gt;Using metaprogramming to aid in code readability is one of my favorite features of
Ruby. An expressive, powerful example of this is the ability to call a
&lt;code class=&quot;highlighter-rouge&quot;&gt;find_by_&amp;lt;column&amp;gt;&lt;/code&gt; method on ActiveRecord models in Rails without needing to
define said method. Rails achieves this via the &lt;code class=&quot;highlighter-rouge&quot;&gt;method_missing&lt;/code&gt; feature in Ruby’s
object system.&lt;/p&gt;

&lt;p&gt;In Ruby, if a message is
sent to an object, and that object doesn’t have an implementation for it, the
&lt;code class=&quot;highlighter-rouge&quot;&gt;method_missing&lt;/code&gt; method is called instead with the original method name as a parameter. By
default, this raises an exception, but developers have the ability to override
and provide custom behavior. This is where Rails builds and caches customized
database query functions.&lt;/p&gt;

&lt;p&gt;It turns out, we can emulate this dynamic nature
pretty easily within our system:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;SQLBuilder&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;table&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Object&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Message&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;field&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;stringByReplacingOccurrencesOfString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;
            &lt;span class=&quot;s&quot;&gt;&quot;sort-by-&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
            &lt;span class=&quot;nv&quot;&gt;withString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;field&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;msg&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;SELECT * FROM &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;table&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; ORDER BY &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;field&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;nil&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;s&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;SQLBuilder&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;user&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;nf&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;sort-by-age&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; &quot;SELECT * FROM user ORDER BY age&quot;&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;sort-by-name&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; &quot;SELECT * FROM user ORDER BY name&quot;&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;s&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;group-by-something&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;c1&quot;&gt;// =&amp;gt; nil&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;We’re missing the robustness of a dynamic &lt;code class=&quot;highlighter-rouge&quot;&gt;Object&lt;/code&gt; superclass to route things,
but hey, we’ve got the same results 😉&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;In the end, our object system is neither featureful nor expressive.&lt;/p&gt;

&lt;p&gt;But to me, the most important takeaway is that given certain fundamental functional
language features, any developer could have come up with and implemented OOP.
At its core, the concepts and &lt;em&gt;patterns&lt;/em&gt; of OOP are very simple – and it’s just that.&lt;/p&gt;

&lt;p&gt;OOP can be thought of as a set of (helpful!) &lt;em&gt;patterns&lt;/em&gt; that can be implemented
on top of a more fundamental, functional paradigm.
We can truly &lt;a href=&quot;http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html&quot;&gt;say&lt;/a&gt;
that “objects are a poor man’s closures”.&lt;/p&gt;

&lt;p&gt;The code in this article is available as a &lt;a href=&quot;https://gist.github.com/cfdrake/2a20fe432547d92b50a8&quot;&gt;gist&lt;/a&gt;.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Implementing a Small DSL in Swift</title>
   <link href="http://colindrake.me/2015/10/28/implementing-a-small-dsl-in-swift/"/>
   <updated>2015-10-28T00:00:00-04:00</updated>
   <id>http://colindrake.me/2015/10/28/implementing-a-small-dsl-in-swift</id>
   <content type="html">&lt;p&gt;I was working on an iOS project earlier today when I ended up running into an annoying bug in my Swift Core Data stack.  My seemingly correct &lt;code class=&quot;highlighter-rouge&quot;&gt;NSFetchRequest&lt;/code&gt; code was returning &lt;code class=&quot;highlighter-rouge&quot;&gt;nil&lt;/code&gt; for all inputs, and I couldn’t figure out why.&lt;/p&gt;

&lt;p&gt;After inspecting and thinking through totally different parts of the codebase, I had an ah-hah moment! I went back to my fetch request code and sure enough I saw something resembling the following:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;predicate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSPredicate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;format&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;%@ = %@&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Those acquainted with Core Data will probably notice my error pretty quickly: I accidentally formatted &lt;code class=&quot;highlighter-rouge&quot;&gt;key&lt;/code&gt; as a value type! The &lt;a href=&quot;https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Predicates/Articles/pSyntax.html&quot;&gt;format string&lt;/a&gt; should actually be &lt;code class=&quot;highlighter-rouge&quot;&gt;%K = %@&lt;/code&gt;, that way Core Data will know that &lt;code class=&quot;highlighter-rouge&quot;&gt;key&lt;/code&gt; is in fact, a substitutable key. Otherwise, it will simply perform string comparison between the two &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt; values.&lt;/p&gt;

&lt;p&gt;I lamented that there was no error checking in format strings and quickly moved on. However, I had the idea in the back of my mind that a small, focused, problem-driven language, or &lt;a href=&quot;https://en.wikipedia.org/wiki/Domain-specific_language&quot;&gt;Domain Specific Language&lt;/a&gt;, could easily be built in Swift to aid in basic validation/cleanliness of &lt;code class=&quot;highlighter-rouge&quot;&gt;NSPredicate&lt;/code&gt; construction.&lt;/p&gt;

&lt;h2 id=&quot;overview&quot;&gt;Overview&lt;/h2&gt;
&lt;p&gt;I figured a limited proof of concept DSL for &lt;code class=&quot;highlighter-rouge&quot;&gt;NSPredicate&lt;/code&gt; construction could be made pretty quickly for “fun” 😉 As a baseline, all I wanted to support was:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Referencing keypaths and simple &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt;-convertible constant values&lt;/li&gt;
  &lt;li&gt;Checking keys against values with comparison operators&lt;/li&gt;
  &lt;li&gt;Combining expressions with logical operators, such as &lt;code class=&quot;highlighter-rouge&quot;&gt;AND&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;OR&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;My goal syntax was something resembling the following:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;predicate&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSPredicate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;foo&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;bar&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Luckily for me, this experiment turned out to be relatively straightforward thanks to many of Swift’s powerful language features. Let’s dive straight into the implementation!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; This article is also available as an &lt;a href=&quot;https://github.com/cfdrake/swift-dsl-example&quot;&gt;Xcode Playground&lt;/a&gt; on Github.&lt;/p&gt;

&lt;h2 id=&quot;keys-and-values&quot;&gt;Keys and Values&lt;/h2&gt;
&lt;p&gt;We’ll start with the most simple object to represent: a keypath. A keypath is simply a string that represents a (potentially nested) property, for example &lt;code class=&quot;highlighter-rouge&quot;&gt;amountDeposited&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;parent.firstName&lt;/code&gt;. To encode this in our DSL, we’ll simply represent a &lt;code class=&quot;highlighter-rouge&quot;&gt;KeyPath&lt;/code&gt; as a &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;typealias&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;KeyPath&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The second most simple object type to represent is a constant value. Again, in our simplified DSL, we’ll only be supporting values that can be directly represented as strings. Thus, we simply want &lt;code class=&quot;highlighter-rouge&quot;&gt;ValueType&lt;/code&gt; to be those objects that are &lt;code class=&quot;highlighter-rouge&quot;&gt;CustomStringConvertible&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;typealias&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ValueType&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CustomStringConvertible&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;A more full-featured DSL would not be encoding values into strings, but this representation will suit our small experiment 👍🏼&lt;/p&gt;

&lt;h2 id=&quot;operators&quot;&gt;Operators&lt;/h2&gt;
&lt;p&gt;Now we can represent the names and values of things we want to query. However, we need a way to relate the two: this is where operators come into play.&lt;/p&gt;

&lt;p&gt;We’ll support a small subset of comparison and logical operators for querying data. These can be easily represented by Swift’s ever-helpful &lt;code class=&quot;highlighter-rouge&quot;&gt;RawRepresentable&lt;/code&gt;-backed &lt;code class=&quot;highlighter-rouge&quot;&gt;enum&lt;/code&gt; type:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;enum&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Comparison&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;EqualTo&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;=&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;GreaterThan&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&amp;gt;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;LessThan&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&amp;lt;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;And&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;&amp;amp;&amp;amp;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Or&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;||&quot;&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Given that we’ll eventually want to convert these &lt;code class=&quot;highlighter-rouge&quot;&gt;Comparison&lt;/code&gt; values into a &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt; representation, we’ll adhere to &lt;code class=&quot;highlighter-rouge&quot;&gt;CustomStringConvertible&lt;/code&gt; ourselves. Because we’ve already defined a nice string for the &lt;code class=&quot;highlighter-rouge&quot;&gt;rawValue&lt;/code&gt;, we’ll simply return that for our implementation.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Comparison&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CustomStringConvertible&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;description&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rawValue&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Tip:&lt;/strong&gt; We could have easily made calls to &lt;code class=&quot;highlighter-rouge&quot;&gt;rawValue&lt;/code&gt; in our code later for &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt; versions of our operators, but I consider implementing &lt;code class=&quot;highlighter-rouge&quot;&gt;CustomStringConvertible&lt;/code&gt; a cleaner mechanism. For one, it gives you a free initializer: &lt;code class=&quot;highlighter-rouge&quot;&gt;let str = String(Comparison.EqualTo)&lt;/code&gt;. But more importantly, it keeps the “storage mechanism” of &lt;code class=&quot;highlighter-rouge&quot;&gt;Comparison&lt;/code&gt; abstracted out.&lt;/p&gt;

&lt;h2 id=&quot;expressions&quot;&gt;Expressions&lt;/h2&gt;
&lt;p&gt;The &lt;code class=&quot;highlighter-rouge&quot;&gt;Expression&lt;/code&gt; type will represent a value or compound comparison of values that we can convert to an &lt;code class=&quot;highlighter-rouge&quot;&gt;NSPredicate&lt;/code&gt;. In our DSL’s simplified model, there are four types of values:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;A property&lt;/li&gt;
  &lt;li&gt;A constant&lt;/li&gt;
  &lt;li&gt;A negated expression&lt;/li&gt;
  &lt;li&gt;A compound expression connecting two subexpressions&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These concepts can be directly translated into Swift via yet another &lt;code class=&quot;highlighter-rouge&quot;&gt;enum&lt;/code&gt;. However, this time we’ll be creating a &lt;a href=&quot;https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Enumerations.html#//apple_ref/doc/uid/TP40014097-CH12-ID145&quot;&gt;recursive enumeration&lt;/a&gt;:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;n&quot;&gt;indirect&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;enum&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Property&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;KeyPath&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Constant&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;CustomStringConvertible&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Negated&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Binary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Comparison&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The complex cases to explain here are &lt;code class=&quot;highlighter-rouge&quot;&gt;Negated&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;Binary&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;An &lt;code class=&quot;highlighter-rouge&quot;&gt;Expression&lt;/code&gt; of type &lt;code class=&quot;highlighter-rouge&quot;&gt;Negated&lt;/code&gt; is simply a subexpression with an additional tag attached saying that it should be negated. Likewise, &lt;code class=&quot;highlighter-rouge&quot;&gt;Binary&lt;/code&gt; is composed of two subexpressions related by a &lt;code class=&quot;highlighter-rouge&quot;&gt;Comparison&lt;/code&gt; operator. In both of these cases, the subexpressions could be anything from a simple &lt;code class=&quot;highlighter-rouge&quot;&gt;Property&lt;/code&gt; to another &lt;code class=&quot;highlighter-rouge&quot;&gt;Binary&lt;/code&gt; relation.&lt;/p&gt;

&lt;p&gt;Feel free to read up on &lt;a href=&quot;https://en.wikipedia.org/wiki/Algebraic_data_type&quot;&gt;Algebraic Data Types&lt;/a&gt; if you want to learn more about structuring data like this!&lt;/p&gt;

&lt;p&gt;At this point, we have enough ground-level types to &lt;em&gt;represent&lt;/em&gt; what we want to eventually generate. Next, let’s take a look at how we can build up an &lt;code class=&quot;highlighter-rouge&quot;&gt;NSPredicate&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;nspredicate-creation&quot;&gt;NSPredicate Creation&lt;/h2&gt;
&lt;p&gt;Our DSL implementation will create &lt;code class=&quot;highlighter-rouge&quot;&gt;NSPredicates&lt;/code&gt; by concatenating &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt; representations of our query together. Keypaths, constants, and operators are already strings (or string convertible) but how do we stringify an &lt;code class=&quot;highlighter-rouge&quot;&gt;Expression&lt;/code&gt;?&lt;/p&gt;

&lt;p&gt;You might have guessed it: Recursion again!&lt;/p&gt;

&lt;p&gt;By defining how to convert the simple cases of &lt;code class=&quot;highlighter-rouge&quot;&gt;Expression&lt;/code&gt; to a &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt; (the &lt;code class=&quot;highlighter-rouge&quot;&gt;Property&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;Constant&lt;/code&gt; cases), we can implement the more complicated cases on top. Let’s take a look at the code:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;CustomStringConvertible&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;description&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;switch&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Property&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;key&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Constant&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Negated&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;!(&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expression&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&quot;&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;case&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Binary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;op&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;(&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;) &lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;op&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt; (&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;\(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt;&lt;span class=&quot;se&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;)&quot;&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Now that we can fully convert an &lt;code class=&quot;highlighter-rouge&quot;&gt;Expression&lt;/code&gt;, our simplified &lt;em&gt;representation&lt;/em&gt; of an &lt;code class=&quot;highlighter-rouge&quot;&gt;NSPredicate&lt;/code&gt;, to a &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt;, we simply need a clean way to pass it to &lt;code class=&quot;highlighter-rouge&quot;&gt;NSPredicate&lt;/code&gt; itself. To do this, we can define a convenience initializer:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSPredicate&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;convenience&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;format&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;After all this work, let’s stop, take a look, and verify that we’ve got something that works:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;expr1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Property&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;amount&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;expr2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Constant&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;300&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;expr3&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Binary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expr1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Comparison&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;EqualTo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;expr2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSPredicate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expr3&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// amount == 300&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Cool, but it’s still a lot of typing 😒 Now for the fun part…&lt;/p&gt;

&lt;h2 id=&quot;syntactic-sugar&quot;&gt;Syntactic Sugar&lt;/h2&gt;
&lt;p&gt;The main problem with the current state of our DSL is that we have no clean way to create and combine expressions.&lt;/p&gt;

&lt;p&gt;Swift’s &lt;a href=&quot;http://nshipster.com/swift-literal-convertible/&quot;&gt;literal convertible protocols&lt;/a&gt; will aid in being able to construct values and keypaths easily, while &lt;a href=&quot;http://nshipster.com/swift-operators/#overloading&quot;&gt;operator overloading&lt;/a&gt; will provide the basis of a sugary combination syntax.&lt;/p&gt;

&lt;p&gt;Literal protocols will allow us to type a value such as &lt;code class=&quot;highlighter-rouge&quot;&gt;3&lt;/code&gt; and have it automatically converted to &lt;code class=&quot;highlighter-rouge&quot;&gt;Expression.Constant(3)&lt;/code&gt;, for example. Likewise, it’d be great if strings were automatically interpreted as keypaths. We support this behavior by adhering to a number of different protocols and defining specialized initializers.&lt;/p&gt;

&lt;p&gt;I’ve implemented &lt;code class=&quot;highlighter-rouge&quot;&gt;Bool&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;String&lt;/code&gt;, and &lt;code class=&quot;highlighter-rouge&quot;&gt;Integer&lt;/code&gt; conversion in the snippet below - it’s pretty much plug ‘n’ chug mapping values into &lt;code class=&quot;highlighter-rouge&quot;&gt;Constant&lt;/code&gt;, etc. cases:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;extension&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;BooleanLiteralConvertible&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;IntegerLiteralConvertible&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;StringLiteralConvertible&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;typealias&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ExtendedGraphemeClusterLiteralType&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;StringLiteralType&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;typealias&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UnicodeScalarLiteralType&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;StringLiteralType&lt;/span&gt;

    &lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;booleanLiteral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Bool&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Constant&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;booleanLiteral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;integerLiteral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Constant&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;integerLiteral&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;unicodeScalarLiteral&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UnicodeScalarLiteralType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Property&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;extendedGraphemeClusterLiteral&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ExtendedGraphemeClusterLiteralType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Property&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;stringLiteral&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;StringLiteralType&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Property&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Next, we’ll use (abuse?) some operators for combining expressions. The most obvious way of implementing a simple, readable DSL for predicates is by overloading the relevant comparison and logical operators to work on &lt;code class=&quot;highlighter-rouge&quot;&gt;Expression&lt;/code&gt; objects as well.&lt;/p&gt;

&lt;p&gt;Here’s a snippet of a couple of implementations as an example:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;lhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;rhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Binary&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;lhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Comparison&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;EqualTo&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;rhs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// ...other operators omitted for brevity...&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;prefix&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;expr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Negated&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;expr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Implementing the syntactic sugar for this DSL ends up being little more than tying an operator with the matching &lt;code class=&quot;highlighter-rouge&quot;&gt;Expression&lt;/code&gt; case.&lt;/p&gt;

&lt;p&gt;As a note, it’s always worth thinking whether the above is a good idea, or if you should introduce your own operators instead. The second case should almost always be the preferred solution, but if the semantics of an existing operator fits 100% with your data structures (think a &lt;code class=&quot;highlighter-rouge&quot;&gt;Vector&lt;/code&gt; type that could work with &lt;code class=&quot;highlighter-rouge&quot;&gt;+&lt;/code&gt;, etc) then it might be okay to overload.&lt;/p&gt;

&lt;p&gt;Now that we’ve got some of the philosophy out of the way, let’s give it a spin:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;bourbonExpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;proof&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;name&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;Wild Turkey&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;deletedExpr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Expression&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;deleted&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;kc&quot;&gt;true&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h2 id=&quot;final-example&quot;&gt;Final Example&lt;/h2&gt;
&lt;p&gt;As a working final example, we’ll define a &lt;code class=&quot;highlighter-rouge&quot;&gt;Person&lt;/code&gt; structure, and filter an &lt;code class=&quot;highlighter-rouge&quot;&gt;NSArray&lt;/code&gt; of people using an &lt;code class=&quot;highlighter-rouge&quot;&gt;NSPredicate&lt;/code&gt; constructed in our DSL:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSObject&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;tweets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Int&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;age&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Int&lt;/span&gt;

    &lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;tweets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;age&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;tweets&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;tweets&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;age&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;age&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// Setup some contrived, inaccurate data ;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;people&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSArray&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;tweets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;250&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;age&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;),&lt;/span&gt;
                       &lt;span class=&quot;kt&quot;&gt;Person&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;tweets&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;80&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;age&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;22&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// --&amp;gt; [{NSObject, tweets 250, age 18}, {NSObject, tweets 80, age 15}]&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;pred&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSPredicate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;tweets&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;200&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;age&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;18&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// --&amp;gt; &quot;tweets &amp;gt; 200 AND age == 18&quot;&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;filtered&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;people&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;filteredArrayUsingPredicate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pred&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// --&amp;gt; [{NSObject, tweets 250, age 18}]&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Looks neat, plus you get some &lt;em&gt;minor&lt;/em&gt; validation wins done by the compiler. Note, however, it is still entirely possible to construct an invalid &lt;code class=&quot;highlighter-rouge&quot;&gt;NSPredicate&lt;/code&gt; with the existing DSL - it’s more demo/thought experiment than production-ready library!&lt;/p&gt;

&lt;p&gt;Practically speaking, a similar, type-checked, more fleshed out DSL could perhaps end up being useful for Core Data development, where you are limited to the string parsing predicate API. For other applications, however, &lt;a href=&quot;http://nshipster.com/nspredicate/#block-predicates&quot;&gt;block predicates&lt;/a&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;SequenceType&lt;/code&gt;’s &lt;code class=&quot;highlighter-rouge&quot;&gt;filter&lt;/code&gt; function will potentially solve the problem better.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Wrapping a C Library in a Swift Framework</title>
   <link href="http://colindrake.me/2015/10/05/wrapping-a-c-library-in-a-swift-framework/"/>
   <updated>2015-10-05T00:00:00-04:00</updated>
   <id>http://colindrake.me/2015/10/05/wrapping-a-c-library-in-a-swift-framework</id>
   <content type="html">&lt;p&gt;I recently started work on a project where I wanted to wrap up a C library for OS X with a more palatable Swift framework interface. My first thought was to follow what I saw in Apple’s &lt;a href=&quot;https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html&quot;&gt;Mix and Match documentation&lt;/a&gt;, a guide to integrating C/Objective-C with Swift code.&lt;/p&gt;

&lt;p&gt;The guide tells you to create a &lt;a href=&quot;http://www.learnswiftonline.com/getting-started/adding-swift-bridging-header/&quot;&gt;Bridging Header&lt;/a&gt;, a file where you can denote the needed non-Swift dependencies for the compiler to then expose to your Swift code. However, when following this advice with a framework target, Xcode gives you this friendly error:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/public/images/c-library/error.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;After much searching, poking, and prodding, I came across the &lt;a href=&quot;https://github.com/Zewo/SwiftGo&quot;&gt;SwiftGo&lt;/a&gt; project, which appeared to have the same setup as I needed. (Kudos to &lt;a href=&quot;http://loganwright.io/&quot;&gt;@loganwright&lt;/a&gt; from the &lt;a href=&quot;https://ios-developers.io/&quot;&gt;iOS Developers Slack&lt;/a&gt; for pointing this out!)&lt;/p&gt;

&lt;p&gt;I ended up reading the source of SwiftGo and creating an example wrapper project for &lt;a href=&quot;https://github.com/doches/progressbar&quot;&gt;progressbar&lt;/a&gt;, a simple C library to display a progress bar with &lt;a href=&quot;https://en.wikipedia.org/wiki/Ncurses&quot;&gt;ncurses&lt;/a&gt;, as I went along. Check out the final project &lt;a href=&quot;https://github.com/cfdrake/swift-framework-c-library-example&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now, let’s take a look at how it’s set up.&lt;/p&gt;

&lt;h2 id=&quot;creating-the-project&quot;&gt;Creating the Project&lt;/h2&gt;
&lt;p&gt;First, we’ll start out by creating the project. Given that we want to target Mac OS X, we’ll want to start out with a &lt;strong&gt;Cocoa Framework&lt;/strong&gt; type:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/public/images/c-library/fw.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Name the project “Progressbar” and save it somewhere.&lt;/p&gt;

&lt;h2 id=&quot;the-wrapped-library&quot;&gt;The Wrapped Library&lt;/h2&gt;
&lt;p&gt;Next, we’ll want to pull in the progressbar C library, our only dependency:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ cd Progressbar
$ mkdir Dependencies
$ git clone git@github.com:doches/progressbar.git
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;If you take a look at progressbar’s code, you’ll see it is actually comprised of only a few files:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ cd progressbar
$ ls include/
progressbar.h statusbar.h
$ ls lib/
progressbar.c statusbar.c
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;To include these in our wrapper library, open a Finder window and drag all of the above files into the existing Xcode project. I created a few Groups in the project to help organize things:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/public/images/c-library/deps.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;module-mapping&quot;&gt;Module Mapping&lt;/h2&gt;
&lt;p&gt;We’ve now got our C library into our Swift project (and Xcode will even compile it all), but we have no way to &lt;em&gt;call&lt;/em&gt; it from Swift. To remedy this, we use a &lt;strong&gt;Module Map&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;a href=&quot;http://clang.llvm.org/docs/Modules.html#module-maps&quot;&gt;module.map&lt;/a&gt; file is a Clang-specific file that “describes how a collection of existing headers maps on to the (logical) structure of a module.” Luckily for us, these files are simple to create and will allow Clang to do most of the work for us!&lt;/p&gt;

&lt;p&gt;Inside of the main source directory (&lt;code class=&quot;highlighter-rouge&quot;&gt;Progressbar&lt;/code&gt;), create a file called &lt;code class=&quot;highlighter-rouge&quot;&gt;module.map&lt;/code&gt; with the following contents:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;module Libprogressbar [system] {
  header &quot;Dependencies/progressbar/include/progressbar.h&quot;
  export *
}
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Feel free to drag and drop it into Xcode for easy editing (but note this is not actually necessary).&lt;/p&gt;

&lt;p&gt;Next, we need to inform Xcode of the whereabouts of this file. Open up the Project settings for Progressbar, select &lt;strong&gt;Build Settings&lt;/strong&gt;, and look for the one titled &lt;strong&gt;Import Paths&lt;/strong&gt; under &lt;strong&gt;Swift Compiler - Search Paths&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Change it the value of this setting to &lt;code class=&quot;highlighter-rouge&quot;&gt;$(SRCROOT)/Progressbar&lt;/code&gt; and ensure that &lt;code class=&quot;highlighter-rouge&quot;&gt;non-recursive&lt;/code&gt; is selected. Your &lt;code class=&quot;highlighter-rouge&quot;&gt;module.map&lt;/code&gt; file should be in the folder displayed by Xcode.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/public/images/c-library/searchpaths.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Now we can now simply (in Swift parlance) &lt;code class=&quot;highlighter-rouge&quot;&gt;import Libprogressbar&lt;/code&gt; and access all of the C functions, macros, etc. underneath it.&lt;/p&gt;

&lt;h2 id=&quot;the-wrapper&quot;&gt;The Wrapper&lt;/h2&gt;
&lt;p&gt;For this example project, I only ended up writing a minimal wrapper around the original C library for demonstrative purposes. In any case, wrapping a C library like this allows callers to only have to deal with native Swift types, keeping their application layer nice and clean.&lt;/p&gt;

&lt;p&gt;The code for our &lt;code class=&quot;highlighter-rouge&quot;&gt;Progressbar&lt;/code&gt; wrapper is below (any calls to the &lt;code class=&quot;highlighter-rouge&quot;&gt;Libprogressbar&lt;/code&gt; module are interfacing directly with the C library we included):&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Foundation&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Libprogressbar&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;/// Class outputting an animated terminal progress bar.&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Progressbar&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UnsafeMutablePointer&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;progressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;String&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UInt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;cstring&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;text&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;as&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSString&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;UTF8String&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;bar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Libprogressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;progressbar_new&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cstring&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;increment&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;Libprogressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;progressbar_inc&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;finish&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;kt&quot;&gt;Libprogressbar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;progressbar_finish&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;h2 id=&quot;example-usage&quot;&gt;Example Usage&lt;/h2&gt;
&lt;p&gt;With our wrapper defined, we can finally write some simple application code to test our framework:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Cocoa&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Progressbar&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;UInt&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;30&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;bar&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Progressbar&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;text&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;s&quot;&gt;&quot;foo&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;...&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;max&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;increment&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;sleep&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;bar&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;finish&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;// Example Output:&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;// foo |==================================   | ETA: 0h00m02s&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;If you’re following along with the &lt;a href=&quot;https://github.com/cfdrake/swift-framework-c-library-example&quot;&gt;Xcode project&lt;/a&gt;, check out the Playground file under the &lt;code class=&quot;highlighter-rouge&quot;&gt;Example&lt;/code&gt; group. If you have the Console Window open (&lt;strong&gt;⌘-Shift-Y&lt;/strong&gt;), you should see a progress bar animating over the course of 30 seconds.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>An Observable Pattern Implementation in Swift</title>
   <link href="http://colindrake.me/2015/10/01/an-observable-pattern-implementation-in-swift/"/>
   <updated>2015-10-01T00:00:00-04:00</updated>
   <id>http://colindrake.me/2015/10/01/an-observable-pattern-implementation-in-swift</id>
   <content type="html">&lt;p&gt;Over the past few days, I’ve been working a new Mac app in Swift as a part of &lt;a href=&quot;https://gumroad.com/smallproductlab&quot;&gt;Gumroad’s Small Product Lab&lt;/a&gt; challenge. This app contains a simple &lt;code class=&quot;highlighter-rouge&quot;&gt;struct&lt;/code&gt; type, &lt;code class=&quot;highlighter-rouge&quot;&gt;AppConfig&lt;/code&gt;, representing the application’s editable configuration. What I needed to build was a view controller for the user to edit and update said values, and this is where I ran into trouble.&lt;/p&gt;

&lt;p&gt;The normal pattern in the Objective-C world to implement this is to use &lt;a href=&quot;https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CocoaBindings/CocoaBindings.html&quot;&gt;Cocoa Bindings&lt;/a&gt;, an awesome feature implemented on top of &lt;a href=&quot;https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html&quot;&gt;KVO&lt;/a&gt; that allows you to automatically bind your (Mac) UI to instance variables in Interface Builder.&lt;/p&gt;

&lt;p&gt;However, Cocoa Bindings will only work for types that are &lt;a href=&quot;http://stackoverflow.com/q/24092285&quot;&gt;subclasses of NSObject&lt;/a&gt;. I felt that porting my &lt;code class=&quot;highlighter-rouge&quot;&gt;AppConfig&lt;/code&gt; struct over to a class, let alone an &lt;code class=&quot;highlighter-rouge&quot;&gt;NSObject&lt;/code&gt; subclass, conflicted with the fact that it was better represented as a &lt;a href=&quot;https://www.mikeash.com/pyblog/friday-qa-2015-07-17-when-to-use-swift-structs-and-classes.html&quot;&gt;value type&lt;/a&gt;, and I definitely didn’t want to needlessly bring in the Objective-C runtime for this simple case.&lt;/p&gt;

&lt;p&gt;Given that I’ve been working on this app to both scratch an itch and to use Swift in a practical setting, I decided to write my own native Swift implementation of the &lt;a href=&quot;https://en.wikipedia.org/wiki/Observer_pattern&quot;&gt;Observable Pattern&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;protocols-everywhere&quot;&gt;Protocols Everywhere&lt;/h2&gt;
&lt;p&gt;To begin with, I wanted to come up with a &lt;code class=&quot;highlighter-rouge&quot;&gt;protocol&lt;/code&gt; that I could implement to satisfy my data binding woes. I decided on a &lt;code class=&quot;highlighter-rouge&quot;&gt;subscribe&lt;/code&gt;/&lt;code class=&quot;highlighter-rouge&quot;&gt;unsubscribe&lt;/code&gt; type model, passing in an owner/observer as the object to update a subscription off of.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;protocol&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ObservableProtocol&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;typealias&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;get&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;set&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;subscribe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;observer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AnyObject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;
                   &lt;span class=&quot;nv&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;newValue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;oldValue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;())&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;unsubscribe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;observer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AnyObject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Assuming we are in some type of object context with &lt;code class=&quot;highlighter-rouge&quot;&gt;self&lt;/code&gt;, implementing the &lt;code class=&quot;highlighter-rouge&quot;&gt;Observable&lt;/code&gt; protocol would allow code to be written somewhat like this:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;initial&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;3&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;initial&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;obs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Observable&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;initial&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;obs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subscribe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;newValue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;oldValue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
    &lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s&quot;&gt;&quot;Object updated!&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;v&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;newValue&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;n&quot;&gt;obs&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;4&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;// Trigger update.&lt;/span&gt;
&lt;span class=&quot;nf&quot;&gt;print&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;v&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;       &lt;span class=&quot;c1&quot;&gt;// 4!&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Perfect! Now to write it…&lt;/p&gt;

&lt;h2 id=&quot;implementation&quot;&gt;Implementation&lt;/h2&gt;
&lt;p&gt;Given that the &lt;code class=&quot;highlighter-rouge&quot;&gt;Observable&lt;/code&gt; object has state/a lifecycle, I decided to make it a class:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;public&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;final&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Observable&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ObservableProtocol&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// ...&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;We’ll start out by defining a variable and a couple of handy types.&lt;/p&gt;

&lt;p&gt;Our model of subscribers is &lt;code class=&quot;highlighter-rouge&quot;&gt;observers&lt;/code&gt;, a variable array of &lt;code class=&quot;highlighter-rouge&quot;&gt;ObserversEntry&lt;/code&gt; entries. Each  entry is a tuple composed of a listening object and the block it expects to run upon the &lt;code class=&quot;highlighter-rouge&quot;&gt;Observable&lt;/code&gt; firing. By passing in this listening object and associating it with the block to execute, we can easily look for it in the &lt;code class=&quot;highlighter-rouge&quot;&gt;unsubscribe&lt;/code&gt; method to remove it.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;typealias&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ObserverBlock&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;newValue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;oldValue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&amp;gt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;typealias&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ObserversEntry&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;observer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AnyObject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ObserverBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;private&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;observers&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Array&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;ObserversEntry&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Now we’ll need to implement an &lt;code class=&quot;highlighter-rouge&quot;&gt;init&lt;/code&gt; for our class. The default initializer will simply take an initial value for the observable (declaration forthcoming). Given that we’re writing Swift here, we’ll need to initialize our non-optional &lt;code class=&quot;highlighter-rouge&quot;&gt;observers&lt;/code&gt; array as well.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;nf&quot;&gt;init&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;observers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;At this point, when we construct an &lt;code class=&quot;highlighter-rouge&quot;&gt;Observable&lt;/code&gt; we’ll have an initial value. This value is even assignable, but currently we don’t have any way of telling the objects in our &lt;code class=&quot;highlighter-rouge&quot;&gt;observers&lt;/code&gt; array that the value changed. To do this, we’ll implement &lt;code class=&quot;highlighter-rouge&quot;&gt;didSet&lt;/code&gt; for our &lt;code class=&quot;highlighter-rouge&quot;&gt;value&lt;/code&gt; variable. All we need to do is loop through our listeners and call their associated blocks. Simple!&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;didSet&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;observers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;forEach&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;entry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ObserversEntry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// oldValue is an implicit parameter to didSet in Swift!&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;entry&lt;/span&gt;
            &lt;span class=&quot;nf&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;newValue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;oldValue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;oldValue&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Last but not least, the mechanism to notify observers is in place, but we have no way to update the &lt;code class=&quot;highlighter-rouge&quot;&gt;observers&lt;/code&gt; array. We’ll implement &lt;code class=&quot;highlighter-rouge&quot;&gt;subscribe&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;unsubscribe&lt;/code&gt; to package up and add/remove observer tuples into the internal array.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;subscribe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;observer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AnyObject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ObserverBlock&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;entry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ObserversEntry&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;observer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;block&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;observers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;entry&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

&lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;unsubscribe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;observer&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;AnyObject&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;filtered&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observers&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;filter&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;entry&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
        &lt;span class=&quot;nf&quot;&gt;let&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;owner&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;entry&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;owner&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;!==&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;observer&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;observers&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;filtered&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;That’s all it takes!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; Please keep in mind that this is a simple, naïve, implementation without any considerations for performance, etc.&lt;/p&gt;

&lt;h2 id=&quot;syntactic-sugar&quot;&gt;Syntactic Sugar&lt;/h2&gt;

&lt;p&gt;While this works, I figured I could throw in just a little syntactic sugar to reduce the repetition of writing &lt;code class=&quot;highlighter-rouge&quot;&gt;foo.value = &amp;lt;value&amp;gt;&lt;/code&gt;. I decided to override the &lt;code class=&quot;highlighter-rouge&quot;&gt;&amp;lt;&amp;lt;&lt;/code&gt; operator:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;observable&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Observable&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;T&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;observable&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;value&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;&lt;strong&gt;Update:&lt;/strong&gt; It appears I’ve been (fairly!) called out here by none other than &lt;a href=&quot;http://nondot.org/sabre/&quot;&gt;Chris Lattner&lt;/a&gt; (the designer of the Swift language) himself for overriding and repurposing the bit shift operator 😉 I can’t say I disagree:&lt;/p&gt;

&lt;div class=&quot;twitter-wrapper&quot;&gt;&lt;blockquote class=&quot;twitter-tweet&quot; lang=&quot;en&quot;&gt;&lt;p lang=&quot;en&quot; dir=&quot;ltr&quot;&gt;Interesting approach to implementing a bindings like system, but not too enthused about repurposing shift operator! &lt;a href=&quot;https://t.co/qiNqvx6BS2&quot;&gt;https://t.co/qiNqvx6BS2&lt;/a&gt;&lt;/p&gt;&amp;mdash; Chris Lattner (@clattner_llvm) &lt;a href=&quot;https://twitter.com/clattner_llvm/status/650354422430588928&quot;&gt;October 3, 2015&lt;/a&gt;&lt;/blockquote&gt;
&lt;script async=&quot;&quot; src=&quot;//platform.twitter.com/widgets.js&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;&lt;/div&gt;

&lt;p&gt;As such, if you use this code I’d recommend defining the &lt;code class=&quot;highlighter-rouge&quot;&gt;&amp;lt;~&lt;/code&gt; operator instead, or something else similarly unique!&lt;/p&gt;

&lt;h2 id=&quot;example&quot;&gt;Example&lt;/h2&gt;
&lt;p&gt;With the above code, you can now wire up &lt;code class=&quot;highlighter-rouge&quot;&gt;Observable&lt;/code&gt; objects to UI elements and instance variables. Just what I needed! Here’s an example &lt;code class=&quot;highlighter-rouge&quot;&gt;NSViewController&lt;/code&gt; implementation with an editable &lt;code class=&quot;highlighter-rouge&quot;&gt;port&lt;/code&gt; value:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;&lt;span class=&quot;c1&quot;&gt;/// A view controller supporting editing of the app&#39;s config.&lt;/span&gt;
&lt;span class=&quot;kd&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;PreferencesViewController&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSViewController&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;// The model layer.&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;configuration&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;ApplicationConfiguration&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// The view and object supporting the &quot;controller&quot;.&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;@IBOutlet&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;portTextField&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;NSTextField&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;!&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;var&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;port&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Observable&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;kt&quot;&gt;Int&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// ...&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: NSViewController&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;override&lt;/span&gt; &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;viewDidLoad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;k&quot;&gt;super&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;viewDidLoad&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;

        &lt;span class=&quot;n&quot;&gt;port&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;subscribe&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;port&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// Ignore the old value, but update config with the new.&lt;/span&gt;
            &lt;span class=&quot;k&quot;&gt;self&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;configuration&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;port&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;port&lt;/span&gt;

            &lt;span class=&quot;c1&quot;&gt;// You can trigger anything from here! Save to disk, etc...&lt;/span&gt;
            &lt;span class=&quot;c1&quot;&gt;// Keeps action/UI code clean.&lt;/span&gt;
        &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

        &lt;span class=&quot;c1&quot;&gt;// ...&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// Assume `portTextFieldDidUpdate` is wired to be&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// called when portTextField&#39;s value updates.&lt;/span&gt;
        &lt;span class=&quot;c1&quot;&gt;// ...&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;// MARK: Helpers&lt;/span&gt;
    &lt;span class=&quot;kd&quot;&gt;func&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;portTextFieldDidUpdate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;value&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt; &lt;span class=&quot;kt&quot;&gt;Int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;{&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;port&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;value&lt;/span&gt;
    &lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Download this as an &lt;a href=&quot;https://github.com/cfdrake/swift-observables-example&quot;&gt;Xcode Playground&lt;/a&gt;.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Pure Data: An Introduction</title>
   <link href="http://colindrake.me/2015/08/03/puredata-an-introduction/"/>
   <updated>2015-08-03T00:00:00-04:00</updated>
   <id>http://colindrake.me/2015/08/03/puredata-an-introduction</id>
   <content type="html">&lt;h2 id=&quot;overview&quot;&gt;Overview&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;http://puredata.info/&quot;&gt;Pure Data&lt;/a&gt; is a cross platform and open source visual programming language allowing you to work with audio, video, and more in a simple &lt;a href=&quot;https://en.wikipedia.org/wiki/Dataflow#Software_architecture&quot;&gt;dataflow&lt;/a&gt; programming model. Over the past week or so, I’ve been exploring Pd for music and audio use and figured that a series of blog posts documenting my path of learning would be fun, helpful for others, and a good way to reinforce what I’ve covered.&lt;/p&gt;

&lt;p&gt;This is the first entry in this potential series: we’ll be covering installation for Mac OS X, some basic dataflow programming concepts, and a few simple audio object types. In the end, we’ll build a simple Hi-Hat patch with a few tweakable parameters.&lt;/p&gt;

&lt;h2 id=&quot;installation&quot;&gt;Installation&lt;/h2&gt;
&lt;p&gt;Pure Data comes in two flavors:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Pure Data Vanilla&lt;/strong&gt;: A basic setup, but will cover everything you need to get started.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Pure Data Extended&lt;/strong&gt;: Vanilla plus some very helpful documentation, libraries, and packages.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I’d recommend installing &lt;a href=&quot;http://puredata.info/downloads/pd-extended&quot;&gt;Pure Data Extended&lt;/a&gt;, as it comes with a variety of useful objects types that you would otherwise be missing. Additionally, I’ve noticed that many times Cycling74/Pure Data forum threads will reference objects built-in to only the Extended version (the helpful &lt;code class=&quot;highlighter-rouge&quot;&gt;[sfv~]&lt;/code&gt; for instance).&lt;/p&gt;

&lt;p&gt;On Mac OS X, you can either &lt;a href=&quot;http://puredata.info/downloads&quot;&gt;manually download&lt;/a&gt; these or install them with the &lt;code class=&quot;highlighter-rouge&quot;&gt;brew&lt;/code&gt; command, if you are familiar.&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ brew search pd
Caskroom/cask/pd-extended
Caskroom/cask/pd
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;&lt;em&gt;Note: I haven’t tested the Homebrew versions to see how up-to-date or functional they are. YMMV.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Before continuing, I’ll assume you have a little bit of familiarity with the Pd &lt;a href=&quot;http://en.flossmanuals.net/pure-data/the-interface/the-interface/&quot;&gt;interface&lt;/a&gt;, i.e. that you have at least explored around it before reading this article. Additionally, some experience with sound synthesis will help out, but I’ll attempt to link out for further reading when needed.&lt;/p&gt;

&lt;h2 id=&quot;dataflow-model&quot;&gt;Dataflow Model&lt;/h2&gt;
&lt;p&gt;The dataflow programming model of Pure Data allows you to abstract out your ideas into sequences of composable functions that immediately react to new values produced by inputs. In the audio world, this allows you to build out your instruments with a DSP-centric model of the world.&lt;/p&gt;

&lt;p&gt;Within Pure Data, this is graphically represented by objects with wires connecting their inputs to the outputs of other objects. For example, the following patch will print out the number sent as input to the print function. Upon, changing the value of the number in Play mode (Command-E to toggle between Edit/Play modes), &lt;code class=&quot;highlighter-rouge&quot;&gt;[print]&lt;/code&gt; will automatically react and print the value to the console window.&lt;/p&gt;

&lt;p class=&quot;smaller-img&quot;&gt;&lt;img src=&quot;/public/images/pure-data/pd-print.png&quot; title=&quot;WIP Hi-Hat Patch&quot; /&gt;&lt;/p&gt;

&lt;p&gt;This automatic reaction to inputs is what lets us easily build interactive synthesizers, instruments, etc. Note that these inputs may come from a variety of sources: manual user input, MIDI messages, &lt;a href=&quot;https://en.wikipedia.org/wiki/Open_Sound_Control&quot;&gt;OSC&lt;/a&gt;, serial port data from an &lt;a href=&quot;http://playground.arduino.cc/Interfacing/PD&quot;&gt;Arduino&lt;/a&gt;, and more. We’ll stick with manual user input from the GUI for now.&lt;/p&gt;

&lt;p&gt;Next, we’ll cover some of the object and data types that are available for us to use and start building with.&lt;/p&gt;

&lt;h2 id=&quot;object-types&quot;&gt;Object Types&lt;/h2&gt;
&lt;p&gt;The following are the most basic forms of data and types that Pure Data supports:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;strong&gt;Object&lt;/strong&gt;: Think of this as similar to a function. &lt;code class=&quot;highlighter-rouge&quot;&gt;[print]&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;[+]&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;[*]&lt;/code&gt; are examples. They may take input via pins at the top, and will produce output via pins at the bottom.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Number Box&lt;/strong&gt;: This data type allows you to input and edit a numerical (integer or float) value. This may be sent to an input pin of an object and will re-send whenever the value changes.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Message Box&lt;/strong&gt;: List of data that may be sent to an object upon click from the user. For example, you may describe a sequence of sampled amplitudes to send to an audio object. In a way, these are similar to function arguments.&lt;/li&gt;
  &lt;li&gt;&lt;strong&gt;Bang&lt;/strong&gt;: Upon clicking, this will “trigger” another object in realtime. May be used to begin a sound’s audio envelope, etc.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Additionally, many UI components such as sliders, VU meters, etc. are supported to make your patch more usable to other people.&lt;/p&gt;

&lt;p&gt;When it comes to the audio domain, most of what we’ll work with will be simple Object types, or functions. Sound generators, audio filters, and more are all provided as objects in Pure Data that generate potentially constantly changing signals over time. It’s worthy of note that audio objects typically have names ending in &lt;code class=&quot;highlighter-rouge&quot;&gt;~&lt;/code&gt;, such as &lt;code class=&quot;highlighter-rouge&quot;&gt;[phasor~]&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;audio-patches&quot;&gt;Audio Patches&lt;/h2&gt;
&lt;p&gt;Let’s start out by exploring the simplest generator available to us.&lt;/p&gt;

&lt;h4 id=&quot;generating-sound&quot;&gt;Generating Sound&lt;/h4&gt;

&lt;p&gt;The &lt;code class=&quot;highlighter-rouge&quot;&gt;[osc~]&lt;/code&gt; object outputs a &lt;a href=&quot;https://en.wikipedia.org/wiki/Pure_tone&quot;&gt;constant (co)sine wave&lt;/a&gt; at the specified frequency. You can provide a frequency to this object via a couple of methods:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;[osc~ 440]&lt;/code&gt; will generate a constant 440-Hz sine wave.&lt;/li&gt;
  &lt;li&gt;A plain &lt;code class=&quot;highlighter-rouge&quot;&gt;[osc~]&lt;/code&gt; with a Number Box connected to the top left pin will allow you to adjust the frequency of the wave at will. You may also use the first form with a Number Box attached, providing a default value that is user changeable.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;[dac~]&lt;/code&gt;, the digital to analog convertor object, allows you to output a signal to the left and right output stereo channels of your computer. When you create this object, you’ll note it has two pins: the left and right pins (obviously) map to the left and right sound output channels.&lt;/p&gt;

&lt;p&gt;Try to set up the two prior configurations (one at a time) with output connected to the DAC in Pure Data. Press Command-/ to enable audio and Command-. to disable it. You should hear a pure, constantly sounding tone. Your patches should look something like these:&lt;/p&gt;

&lt;p class=&quot;small-img&quot;&gt;&lt;img src=&quot;/public/images/pure-data/osc.png&quot; title=&quot;Osc Patch&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Next, we’ll try to modify (process) this audio signal before sending it to the speaker.&lt;/p&gt;

&lt;h4 id=&quot;processing-sound&quot;&gt;Processing Sound&lt;/h4&gt;
&lt;p&gt;The simplest case for modifying a signal is by affecting the the amplitude. The &lt;code class=&quot;highlighter-rouge&quot;&gt;[*~]&lt;/code&gt; object will multiply N audio signals together over time. By multiplying a signal by zero, you silence it, and by multiplying it by one, you leave it unaffected. Less than one is negative gain, and greater than one is positive gain. Lets build a user-editable volume control for our oscillator by using a Number box:&lt;/p&gt;

&lt;p class=&quot;smaller-img&quot;&gt;&lt;img src=&quot;/public/images/pure-data/amplitude.png&quot; title=&quot;Volume Control Patch&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Be careful when entering gain values greater than one for this patch. Given that &lt;code class=&quot;highlighter-rouge&quot;&gt;[osc~]&lt;/code&gt; produces a waveform with a peak of one for amplitude, increasing this value will cause the signal to hard-clip.&lt;/p&gt;

&lt;p&gt;By connecting up some additional machinery, we can verify that the signal is being affected as we’re expecting. Here’s a graph showing the output of the oscillator (you can see that the amplitude looks like one-quarter of the height of the graph, per the 0.25 amplitude factor):&lt;/p&gt;

&lt;p class=&quot;small-img&quot;&gt;&lt;img src=&quot;/public/images/pure-data/volgraph.png&quot; title=&quot;Volume Control Patch with Graph&quot; /&gt;&lt;/p&gt;

&lt;p&gt;It’s actually possible for the &lt;code class=&quot;highlighter-rouge&quot;&gt;[*~]&lt;/code&gt; object to multiply two changing audio signals as well, creating a sort of amplitude/volume modulation. Instead of passing in a constant number, let’s replace it with another sine wave so that the volume changes periodically over time. You’re able to see how the amplitude of the wave changes from the graph:&lt;/p&gt;

&lt;p class=&quot;small-img&quot;&gt;&lt;img src=&quot;/public/images/pure-data/volmod.png&quot; title=&quot;Volume Control Patch with Graph&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Feel free to experiment with the frequency at which the volume is modulating. By setting the frequency of the modulation to a frequency in the audible spectrum (for example, 880), you can achieve what’s known to musicians as a &lt;a href=&quot;https://en.wikipedia.org/wiki/Tremolo&quot;&gt;tremelo&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here’s a fun exercise: Create a &lt;a href=&quot;https://en.wikipedia.org/wiki/Vibrato&quot;&gt;vibrato&lt;/a&gt; effect by &lt;em&gt;ever so slightly&lt;/em&gt; modulating the frequency, not amplitude, of the original oscillator over time at an audible speed.&lt;/p&gt;

&lt;h2 id=&quot;sample-patch&quot;&gt;Sample Patch&lt;/h2&gt;
&lt;p&gt;Next, we’re going to take what we now know and turn it into a playable patch. This section is going to cover how to create a classic white-noise based &lt;a href=&quot;https://en.wikipedia.org/wiki/Hi-hat&quot;&gt;Hi-Hat&lt;/a&gt; instrument.&lt;/p&gt;

&lt;p&gt;We’re going to start with the &lt;code class=&quot;highlighter-rouge&quot;&gt;[noise~]&lt;/code&gt; object, an audio generator that outputs &lt;a href=&quot;https://en.wikipedia.org/wiki/White_noise&quot;&gt;white noise&lt;/a&gt;, a random signal with each area of the audible spectrum equally represented. This harsh sound actually can form the basis of many other percussion instruments, such as a snare drum. If you connect &lt;code class=&quot;highlighter-rouge&quot;&gt;[noise~]&lt;/code&gt; directly to &lt;code class=&quot;highlighter-rouge&quot;&gt;[dac~]&lt;/code&gt;, you’ll hear a sound that’s quite harsh, so we’re going to filter out some frequencies using a &lt;a href=&quot;https://en.wikipedia.org/wiki/Band-pass_filter&quot;&gt;bandpass filter&lt;/a&gt;.&lt;/p&gt;

&lt;p class=&quot;smaller-img&quot;&gt;&lt;img src=&quot;/public/images/pure-data/noise.png&quot; title=&quot;WIP Hi-Hat Patch&quot; /&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code class=&quot;highlighter-rouge&quot;&gt;[vcf~]&lt;/code&gt; (voltage-controlled filter) object takes three parameters: an input audio signal to filter, the base frequency at which the filtering will occur, and a Q (resonance) value that determines how “far out” the filtering will reach. Go ahead and connect the output of &lt;code class=&quot;highlighter-rouge&quot;&gt;[noise~]&lt;/code&gt; to the input of a new &lt;code class=&quot;highlighter-rouge&quot;&gt;[vcf~]&lt;/code&gt;, with number boxes inputting 1.1kHZ (11000) and 5 for frequency and Q, respectively. Connecting this to &lt;code class=&quot;highlighter-rouge&quot;&gt;[dac~]&lt;/code&gt; will produce something a &lt;em&gt;little&lt;/em&gt; less irritating, however it’s still just a constantly playing sound, not an instrument. What we’ve done here is setup a tight &lt;a href=&quot;http://en.flossmanuals.net/pure-data/ch027_filters/&quot;&gt;filter&lt;/a&gt; that only allows a specific range of high frequencies from the original signal to come through, emulating the high pitch of a real hi-hat.&lt;/p&gt;

&lt;p class=&quot;smaller-img&quot;&gt;&lt;img src=&quot;/public/images/pure-data/noise-filtered.png&quot; title=&quot;WIP Hi-Hat Patch&quot; /&gt;&lt;/p&gt;

&lt;p&gt;An &lt;a href=&quot;https://en.wikipedia.org/wiki/Synthesizer#ADSR_envelope&quot;&gt;ASDR envelope&lt;/a&gt; can shape a waveform’s amplitude over a period of time, which is what we’ll want to be able to trigger. By triggering changes in the amplitude (which should be at zero normally) on a button press, we can get the distinctive short, percussive “blip” sound of a Hi-Hat from this filtered noise. The &lt;code class=&quot;highlighter-rouge&quot;&gt;[line~]&lt;/code&gt; object is a simple way to accomplish this in Pure Data.&lt;/p&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;[line~]&lt;/code&gt; takes a list of amplitudes and times and generates a linearly interpolated audio waveform according to the values passed in. For example, if you use a message box to feed in &lt;code class=&quot;highlighter-rouge&quot;&gt;1, 0.7 40, 0 30&lt;/code&gt; to &lt;code class=&quot;highlighter-rouge&quot;&gt;[line~]&lt;/code&gt;, when triggered it will generate a waveform that initially has an amplitude of 1, moves down to 0.7 after 40ms, and falls back down to 0 after 30ms. By multiplying (&lt;code class=&quot;highlighter-rouge&quot;&gt;*~&lt;/code&gt;) this with our white noise audio signal, we can create a new, snappy signal that varies over time when the envelope is triggered (via a click in Play Mode), and otherwise stays quiet. This is the basis of creating “playable” instruments within Pure Data.&lt;/p&gt;

&lt;p&gt;For bonus points, you can hook up a Button to the ASDR message box, providing a more user-friendly (in a way) mechanism to toggle the sound. Clicking the button in Play mode will send a &lt;code class=&quot;highlighter-rouge&quot;&gt;bang&lt;/code&gt; to the message box, triggering the envelope and temporarily lifting the amplitude.&lt;/p&gt;

&lt;p&gt;If you’ve followed the above, you’ll hopefully have something similar to the following:&lt;/p&gt;

&lt;p class=&quot;small&quot;&gt;&lt;img src=&quot;/public/images/pure-data/hihat.png&quot; title=&quot;Hi-Hat Patch&quot; /&gt;&lt;/p&gt;

&lt;audio controls=&quot;&quot;&gt;
  &lt;source src=&quot;/public/audio/pure-data/HiHat.wav&quot; type=&quot;audio/wav&quot; /&gt;
  Your browser does not support the audio element.
&lt;/audio&gt;

&lt;p&gt;It turns out that many classic drum synthesizers create sounds in similar (but perhaps more complex) ways. Bass drums can be synthesized using low-frequency sine waves, and snares can be also be created by combining a low-frequency sine wave mixed with some white noise to simulate the “snap”. Once you get started here, the possibilities are pretty much endless, only limited by your imagination.&lt;/p&gt;

&lt;h2 id=&quot;further-tips-and-notes&quot;&gt;Further Tips and Notes&lt;/h2&gt;

&lt;h4 id=&quot;midimock&quot;&gt;MidiMock&lt;/h4&gt;

&lt;p&gt;I’ve found it helpful to download &lt;a href=&quot;https://itunes.apple.com/us/app/midi-mock/id438240325?mt=12&quot;&gt;MidiMock&lt;/a&gt; from the App Store, and create a setup similar to the Input Stage of the demo synthesizer from the Pd tutorial on &lt;a href=&quot;http://en.flossmanuals.net/pure-data/ch032_4-stage-sequencer/&quot;&gt;FLOSS Manuals&lt;/a&gt; to explore your patch more naturally with an onscreen piano.&lt;/p&gt;

&lt;p&gt;Check the “Mac OS X” section of the Pure Data documentation on &lt;a href=&quot;https://puredata.info/docs/faq/midiinput&quot;&gt;MIDI Input&lt;/a&gt; to get your computer wired properly.&lt;/p&gt;

&lt;h4 id=&quot;maxmsp-and-max4live&quot;&gt;Max/MSP and Max4Live&lt;/h4&gt;

&lt;p&gt;&lt;a href=&quot;https://cycling74.com/&quot;&gt;Max/MSP&lt;/a&gt; and &lt;a href=&quot;https://www.ableton.com/en/live/max-for-live/&quot;&gt;Max4Live&lt;/a&gt; are two excellent products by Cycling74 and Ableton. The former is a commercial Pure Data-like programming environment with an excellent GUI, documentation, and more, and the latter is a collaboration between C74 and Ableton allowing you to seamlessly interact with Max patches as an Ableton device in your tracks. I would highly recommend both.&lt;/p&gt;

&lt;h4 id=&quot;other-resources&quot;&gt;Other Resources&lt;/h4&gt;

&lt;p&gt;&lt;a href=&quot;http://en.flossmanuals.net/pure-data/index/&quot;&gt;FLOSS Manuals&lt;/a&gt; provides an excellent, deep guide to getting started using Pure Data. Additionally, they also maintain a glossary of available &lt;a href=&quot;http://en.flossmanuals.net/pure-data/list-of-objects/introduction/&quot;&gt;objects&lt;/a&gt;.&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Overall, I’ve found Pure Data/Max wonderful to work with, and it’s nice to have the ability to open up some M4L patches and see what’s going on under the covers. Additionally, just having the ability to quickly mock up an instrument idea without having to learn a VST library, etc. is phenomenal. Hopefully this guide was able to transfer some of my excitement over to you! My plan for the next article in this series is to build a MIDI-capable, monophonic, two-oscillator synthesizer.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Vim for iOS Development: Setting up ctags</title>
   <link href="http://colindrake.me/2015/06/25/objective-c-ctags-vim/"/>
   <updated>2015-06-25T00:00:00-04:00</updated>
   <id>http://colindrake.me/2015/06/25/objective-c-ctags-vim</id>
   <content type="html">&lt;h2 id=&quot;overview&quot;&gt;Overview&lt;/h2&gt;
&lt;p&gt;With projects like &lt;a href=&quot;https://github.com/msanders/cocoa.vim&quot;&gt;cocoa.vim&lt;/a&gt; and &lt;a href=&quot;https://github.com/eraserhd/vim-ios&quot;&gt;vim-ios&lt;/a&gt;, iOS developers have a variety of helpful tools when deciding to build an app in Vim. However, with implementation files, header files, and the numerous set of frameworks we use to build apps, I’ve always found auto-completion and code navigation to be particularly difficult when writing Objective-C, especially when dealing with larger projects.&lt;/p&gt;

&lt;p&gt;To remedy this, I’ve started using a very old tool, called &lt;a href=&quot;https://en.wikipedia.org/wiki/Ctags&quot;&gt;ctags&lt;/a&gt;. ctags is able to parse source code and index methods, functions, classes, etc. for quick access later. Modern versions of Vim are built with ctags support by default, so this makes for a very easy integration.&lt;/p&gt;

&lt;p&gt;Let’s get started.&lt;/p&gt;

&lt;h2 id=&quot;setup&quot;&gt;Setup&lt;/h2&gt;
&lt;p&gt;Luckily for us, Mac OS X comes with ctags installed by default …but unfortunately for us, this version (despite what the documentation says) doesn’t support Objective-C. We’ll have to use &lt;a href=&quot;http://brew.sh&quot;&gt;Homebrew&lt;/a&gt; to install a newer version. Start by executing the following to install the latest and greatest version of ctags:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;$ brew install ctags --HEAD&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Next, let’s define a few default flags to always use when running ctags. These can be specified in a &lt;code class=&quot;highlighter-rouge&quot;&gt;.ctags&lt;/code&gt; file in your home directory:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;$ cat ~/.ctags
--recurse=yes
--tag-relative=yes
--exclude=.git&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Finally, we’ll set up a bash alias to make our lives easier when running ctags. Unfortunately, ctags assumes all &lt;code class=&quot;highlighter-rouge&quot;&gt;.m&lt;/code&gt; files are Matlab files, not Objective-C implementation files, so we’ll create a new command we can use that will ensure &lt;code class=&quot;highlighter-rouge&quot;&gt;.m&lt;/code&gt; files are treated in the way that we need. Go ahead and add the following line of code to the &lt;code class=&quot;highlighter-rouge&quot;&gt;.bash_profile&lt;/code&gt; file in your home directory:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-bash&quot; data-lang=&quot;bash&quot;&gt;&lt;span class=&quot;nb&quot;&gt;alias &lt;/span&gt;ctags-objc&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;ctags --languages=objectivec --langmap=objectivec:.h.m&quot;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;At this point, we’re ready to start processing our code.&lt;/p&gt;

&lt;h2 id=&quot;indexing-your-project&quot;&gt;Indexing Your Project&lt;/h2&gt;
&lt;p&gt;If you’ve been following along word-for-word so far, you can simply run the following command from your project’s root directory to create a local tag index:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;$ ctags-objc&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;This will create a file called &lt;code class=&quot;highlighter-rouge&quot;&gt;tags&lt;/code&gt; that Vim is smart enough to read. Now, if you open Vim in this directory, you should be able to start jumping through your project’s source code already. Try the following command from within Vim:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-vim&quot; data-lang=&quot;vim&quot;&gt;    &lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;tag &lt;span class=&quot;p&quot;&gt;&amp;lt;&lt;/span&gt;ClassFromYourProject&lt;span class=&quot;p&quot;&gt;&amp;gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;You should be taken directly to the &lt;code class=&quot;highlighter-rouge&quot;&gt;@interface&lt;/code&gt; declaration for your class.&lt;/p&gt;

&lt;p&gt;This is a great start, but oftentimes as iOS developers we find that we need to take a deeper look and check out the headers or documentation for an Apple Framework instead of our own code.&lt;/p&gt;

&lt;h2 id=&quot;indexing-system-headers&quot;&gt;Indexing System Headers&lt;/h2&gt;
&lt;p&gt;Let’s begin by generating tags for some of the more commonly-used Apple Frameworks. We’ll start by opening up the folder containing  all of the iOS and Mac OS X frameworks and peering inside:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;$ cd /System/Library/Frameworks
$ ls
AGL.framework
AVFoundation.framework
AVKit.framework
Accelerate.framework
Accounts.framework
AddressBook.framework
AppKit.framework
AppKitScripting.framework
AppleScriptKit.framework
AppleScriptObjC.framework
ApplicationServices.framework
AudioToolbox.framework
...&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Here, every Framework that we can include and link to has a corresponding &lt;code class=&quot;highlighter-rouge&quot;&gt;*.framework&lt;/code&gt; folder with parseable header files inside. We can use these files to generate a global tag list for all of the Frameworks we use on a daily basis. I’d start with just a few Frameworks - a tag file containing all of them gets pretty slow to search, at least on my system.&lt;/p&gt;

&lt;p&gt;By using the &lt;code class=&quot;highlighter-rouge&quot;&gt;--append&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;-f&lt;/code&gt; flags in ctags, we can output and append tags to a file of our choice. I like to keep the &lt;a href=&quot;https://developer.apple.com/library/ios/documentation/MapKit/Reference/MapKit_Framework_Reference/&quot;&gt;MapKit&lt;/a&gt;, &lt;a href=&quot;https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CoreLocation_Framework/&quot;&gt;CoreLocation&lt;/a&gt;, and &lt;a href=&quot;https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/ObjC_classic/index.html#//apple_ref/doc/uid/20001091&quot;&gt;Foundation&lt;/a&gt; frameworks in my database. Anytime you want to add a Framework to your tags database, a command like the following will work:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ cd CoreData.framework/
$ ctags-objc --append -f ~/Documents/global-objc-tags
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;Do this for a couple of your most often-used Frameworks to get a good base.&lt;/p&gt;

&lt;p&gt;Next, we’ll add tags for &lt;a href=&quot;https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKit_Framework/&quot;&gt;UIKit&lt;/a&gt;. The UIKit frameworks are stored on a per-iOS SDK basis deep inside of the &lt;code class=&quot;highlighter-rouge&quot;&gt;Xcode.app&lt;/code&gt; folder, so we’ll need to start by navigating there (make sure to substitute the &lt;code class=&quot;highlighter-rouge&quot;&gt;8.3&lt;/code&gt; in the next command for the iOS version you want):&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;cd /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.3.sdk/System/Library/Frameworks/UIKit.framework/Headers&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Now, we can just run the same command as above to append to our global tag list:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-text&quot; data-lang=&quot;text&quot;&gt;$ ctags-objc --append -f ~/Documents/global-objc-tags&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;At this point we’ve got two tag databases ready — one for our project, and one for the Frameworks we intend to use. Let’s jump back over to Vim.&lt;/p&gt;

&lt;h2 id=&quot;vim-configurations&quot;&gt;Vim Configurations&lt;/h2&gt;
&lt;p&gt;As we saw above, Vim was smart enough to find and automatically take a look at the local &lt;code class=&quot;highlighter-rouge&quot;&gt;tags&lt;/code&gt; file to process our codebase. However, we need to tell Vim about the global Objective-C tags we just generated. Using an &lt;a href=&quot;http://vimdoc.sourceforge.net/htmldoc/autocmd.html&quot;&gt;autocmd&lt;/a&gt; will be a great solution to make this database searchable only when we’re in an Objective-C file.&lt;/p&gt;

&lt;p&gt;Open your &lt;code class=&quot;highlighter-rouge&quot;&gt;.vimrc&lt;/code&gt; file and add the following:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-vim&quot; data-lang=&quot;vim&quot;&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; has&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;autocmd&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
  autocmd &lt;span class=&quot;nb&quot;&gt;BufNewFile&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;BufRead&lt;/span&gt; *&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;h&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;*&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;m&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;set&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;tags&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;+=~&lt;/span&gt;&lt;span class=&quot;sr&quot;&gt;/Documents/&lt;/span&gt;global&lt;span class=&quot;p&quot;&gt;-&lt;/span&gt;objc&lt;span class=&quot;p&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;tags&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;endif&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Now, we’ll be able to automatically search our local and global tag databases for any project that we open.&lt;/p&gt;

&lt;h2 id=&quot;basic-usage&quot;&gt;Basic Usage&lt;/h2&gt;
&lt;p&gt;Now that we’ve built our full tag archive, we can start querying and jumping around our (and Apple’s) codebases. The following commands and key combinations will form a good start for poking around.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-vim&quot; data-lang=&quot;vim&quot;&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;tag &lt;span class=&quot;p&quot;&gt;&amp;lt;&lt;/span&gt;Class&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; Method&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; Protocol&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; Type&lt;span class=&quot;p&quot;&gt;...&amp;gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;This command will let you go to the definition of the given tag (try it with an Apple Framework class this time — &lt;code class=&quot;highlighter-rouge&quot;&gt;UITableViewDataSource&lt;/code&gt; always has details to the method signatures that I forget). Once you’re done, you may use &lt;code class=&quot;highlighter-rouge&quot;&gt;&amp;lt;c-t&amp;gt;&lt;/code&gt; or &lt;code class=&quot;highlighter-rouge&quot;&gt;:bd&lt;/code&gt; to leave.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-vim&quot; data-lang=&quot;vim&quot;&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;tselect&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;&amp;lt;...&amp;gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;This form is the same as the above &lt;code class=&quot;highlighter-rouge&quot;&gt;tag&lt;/code&gt; except that if more than one match is found, a menu is presented where you may choose which definition you want to jump to. Additionally, this is a good command to use the &lt;code class=&quot;highlighter-rouge&quot;&gt;/&lt;/code&gt; search modifier with. For example, to find tags beginning with &lt;code class=&quot;highlighter-rouge&quot;&gt;NSAss&lt;/code&gt; the &lt;code class=&quot;highlighter-rouge&quot;&gt;:tselect /NSAss&lt;/code&gt; command may be issued.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-vim&quot; data-lang=&quot;vim&quot;&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;tags&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;This command provides a menu of previously-found tags from your current session. Simply type the number of the tag you want to view and press Enter to jump to it again.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-vim&quot; data-lang=&quot;vim&quot;&gt;&lt;span class=&quot;p&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;-]&amp;gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;This normal mode command will perform a &lt;code class=&quot;highlighter-rouge&quot;&gt;:tag&lt;/code&gt; command for the currently selected word. Try putting your cursor within a class name and executing this.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-vim&quot; data-lang=&quot;vim&quot;&gt;&lt;span class=&quot;p&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;&amp;gt;&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;In insert mode, this will provide an autocompletion menu based on tag file contents. The arrow keys navigate the list, &lt;code class=&quot;highlighter-rouge&quot;&gt;&amp;lt;c-y&amp;gt;&lt;/code&gt; accepts and inserts, and &lt;code class=&quot;highlighter-rouge&quot;&gt;&amp;lt;c-e&amp;gt;&lt;/code&gt; cancels the prompt.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-vim&quot; data-lang=&quot;vim&quot;&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;CtrlPTag&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Finally, if you’re a &lt;a href=&quot;https://github.com/kien/ctrlp.vim&quot;&gt;ctrlp.vim&lt;/a&gt; user (which you should be!), you can use this command to search tags in realtime. I use this often enough that I’ve bound it to &lt;code class=&quot;highlighter-rouge&quot;&gt;&amp;lt;leader&amp;gt;t&lt;/code&gt;.&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;You should now have a basic working knowledge of how to generate and view tags for Objective-C projects in Vim. However, there are many, many more commands available to aid in navigating your source with ctags. Give the &lt;code class=&quot;highlighter-rouge&quot;&gt;:help tags&lt;/code&gt; page a read for more information.&lt;/p&gt;

&lt;p&gt;Additionally, it’s worth noting that there are a wide variety of user-contributed plugins that can aid your usage of ctags. Check out &lt;a href=&quot;https://github.com/majutsushi/tagbar&quot;&gt;TagBar&lt;/a&gt; and &lt;a href=&quot;https://github.com/xolox/vim-easytags&quot;&gt;EasyTags&lt;/a&gt; for viewing and maintaining your tags, respectively.&lt;/p&gt;

&lt;p&gt;Shameless plug: If you’re a Vim user and iOS developer, you also may enjoy my &lt;a href=&quot;https://github.com/cfdrake/vim-carthage&quot;&gt;vim-carthage&lt;/a&gt; plugin. Give it a shot!&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Visual notifications for nose Tests</title>
   <link href="http://colindrake.me/2011/08/03/visual-notifications-for-nose-tests/"/>
   <updated>2011-08-03T00:00:00-04:00</updated>
   <id>http://colindrake.me/2011/08/03/visual-notifications-for-nose-tests</id>
   <content type="html">&lt;p&gt;I’d like to announce that I’ve written a very simple, but useful, plugin for the nose testing framework. It uses &lt;code class=&quot;highlighter-rouge&quot;&gt;pynotify&lt;/code&gt;, the Python interface to the &lt;a href=&quot;https://wiki.ubuntu.com/NotifyOSD&quot;&gt;Notify OSD server&lt;/a&gt;, to display notifications at the end of test suites. I’ve given it the decidedly uncreative name of &lt;code class=&quot;highlighter-rouge&quot;&gt;nose-pynotify&lt;/code&gt;. Here it is in action after runing a simple test suite:&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;https://camo.githubusercontent.com/86bc53b4eb6a308c17d0093ddb8b6a84be93ae92/687474703a2f2f636f6c696e666472616b652e636f6d2f696d616765732f6e6f73652e706e67&quot; alt=&quot;nose-pynotify running on my Desktop&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;installation&quot;&gt;Installation&lt;/h2&gt;

&lt;p&gt;You have a couple of options to install &lt;code class=&quot;highlighter-rouge&quot;&gt;nose-pynotify&lt;/code&gt;. These include using &lt;code class=&quot;highlighter-rouge&quot;&gt;easy_install&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;pip&lt;/code&gt;, or manually running &lt;code class=&quot;highlighter-rouge&quot;&gt;setuptools&lt;/code&gt; on the code downloaded from the &lt;a href=&quot;https://github.com/cfdrake/nose-pynotify&quot;&gt;repository&lt;/a&gt;:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-bash&quot; data-lang=&quot;bash&quot;&gt;&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;easy_install nose-pynotify

&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;pip install nose-pynotify

&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;python setup.py install&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h2 id=&quot;usage&quot;&gt;Usage&lt;/h2&gt;

&lt;p&gt;To enable &lt;code class=&quot;highlighter-rouge&quot;&gt;nose-pynotify&lt;/code&gt; for a single run, you can simply pass in a command-line switch:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-bash&quot; data-lang=&quot;bash&quot;&gt;&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;nosetests ... --with-pynotify

&lt;span class=&quot;c&quot;&gt;# Or export the environment variable $NOSE_WITH_PYNOTIFY&lt;/span&gt;
&lt;span class=&quot;c&quot;&gt;# to enable the plugin by default:&lt;/span&gt;

&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;cat ~/.zshrc

&lt;span class=&quot;c&quot;&gt;# ...&lt;/span&gt;
&lt;span class=&quot;nb&quot;&gt;export &lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;NOSE_WITH_PYNOTIFY&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;1
&lt;span class=&quot;c&quot;&gt;# ...&lt;/span&gt;

&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;nosetests&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;Naturally, the plugin is hosted on &lt;a href=&quot;https://github.com/cfdrake/nose-pynotify&quot;&gt;Github&lt;/a&gt;. Have fun testing and feel free to send me pull requests!&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>Clustering in Ruby</title>
   <link href="http://colindrake.me/2011/05/28/clustering-in-ruby/"/>
   <updated>2011-05-28T00:00:00-04:00</updated>
   <id>http://colindrake.me/2011/05/28/clustering-in-ruby</id>
   <content type="html">&lt;p&gt;Clustering algorithms play a very important role in many modern web applications that feature machine learning. This article will introduce you to one of the simplest techniques for the unsupervised grouping of related objects, or clustering.&lt;/p&gt;

&lt;p&gt;If you’re at all interested in automated data grouping or sorting you should at least be familiar with one or two types of &lt;a href=&quot;http://en.wikipedia.org/wiki/Cluster_analysis&quot;&gt;these algorithms&lt;/a&gt; (in addition to more advanced Machine Learning topics, but this serves a good start). In this article, I’m going to go through the process of implementing a very simple Ruby program that can group a set of 2D coordinates into clusters, where each group is composed of a center point, and all of the data points closest to it.&lt;/p&gt;

&lt;p&gt;The algorithm that we’ll be using to accomplish this task is a simple one; &lt;a href=&quot;http://en.wikipedia.org/wiki/K-means_clustering&quot;&gt;k-means clustering&lt;/a&gt; will give us the behavior that we want with little fuss.&lt;/p&gt;

&lt;h2 id=&quot;overview&quot;&gt;Overview&lt;/h2&gt;

&lt;p&gt;Our k-means clustering algorithm takes in, as input, a set of points in the 2-dimensional plane. As output, the points will be grouped into k clusters, where k is an integer specified by the user. Unfortunately, the algorithm can’t decide how many groups there are by itself without more complication, so k must be given. Nonetheless, I’ll describe the algorithm below:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Start by choosing k random points within the dataset’s range as an initial guess for the positions of all the clusters. These points form the centroid point of all the clusters. All distances to other points will be measured from here.&lt;/li&gt;
  &lt;li&gt;For each point in the input data, assign it to the cluster that it is nearest to. After this step, each cluster will somehow be associated with a set of nearby points.&lt;/li&gt;
  &lt;li&gt;For each cluster, go through the set of associated datapoints and calculate the average among them. This will give a new centroid point that is directly in the center of all of the member points.&lt;/li&gt;
  &lt;li&gt;If the clusters didn’t move from their previous locations after recentering, or if they all move less than a certain delta value, return the k clusters and their associated points. Otherwise, go back to Step 2 after deassociating all of the associated points with their cluster. This lets the algorithm start fresh, but with more accurate centroid points.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2 id=&quot;implementation&quot;&gt;Implementation&lt;/h2&gt;

&lt;p&gt;To begin with, we’ll need a class to store the points to be clustered by the algorithm. Essentially, we just need a &lt;code class=&quot;highlighter-rouge&quot;&gt;Point&lt;/code&gt; class to hold &lt;code class=&quot;highlighter-rouge&quot;&gt;x&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;y&lt;/code&gt; values. This is implemented below (I won’t insult your intelligence trying to explain it):&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-ruby&quot; data-lang=&quot;ruby&quot;&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Point&lt;/span&gt;
  &lt;span class=&quot;kp&quot;&gt;attr_accessor&lt;/span&gt; &lt;span class=&quot;ss&quot;&gt;:x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;ss&quot;&gt;:y&lt;/span&gt;

  &lt;span class=&quot;c1&quot;&gt;# Constructor that takes in an x,y coordinate&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;initialize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;vi&quot;&gt;@x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;x&lt;/span&gt;
    &lt;span class=&quot;vi&quot;&gt;@y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;y&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;

  &lt;span class=&quot;c1&quot;&gt;# Calculates the distance to Point p&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;dist_to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;xs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;vi&quot;&gt;@x&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;x&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ys&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;vi&quot;&gt;@y&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;p&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;y&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;**&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;Math&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;::&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;sqrt&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xs&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ys&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;

  &lt;span class=&quot;c1&quot;&gt;# Return a String representation of the object&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;to_s&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;(&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;#{&lt;/span&gt;&lt;span class=&quot;vi&quot;&gt;@x&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;, &lt;/span&gt;&lt;span class=&quot;si&quot;&gt;#{&lt;/span&gt;&lt;span class=&quot;vi&quot;&gt;@y&lt;/span&gt;&lt;span class=&quot;si&quot;&gt;}&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;)&quot;&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Next, there has to be a class to hold clusters of data. As the algorithm described, clusters have groups of member points and a center point (not necessarily in the dataset) associated with them. This corresponds to two instance variables: &lt;code class=&quot;highlighter-rouge&quot;&gt;@points&lt;/code&gt;, a list of &lt;code class=&quot;highlighter-rouge&quot;&gt;Point&lt;/code&gt;s, and &lt;code class=&quot;highlighter-rouge&quot;&gt;@center&lt;/code&gt;, a single &lt;code class=&quot;highlighter-rouge&quot;&gt;Point&lt;/code&gt;. Additionally, there needs to be a way for &lt;code class=&quot;highlighter-rouge&quot;&gt;Cluster&lt;/code&gt;s to update by averaging their member points. This is implemented in &lt;code class=&quot;highlighter-rouge&quot;&gt;recenter!&lt;/code&gt;.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-ruby&quot; data-lang=&quot;ruby&quot;&gt;&lt;span class=&quot;k&quot;&gt;class&lt;/span&gt; &lt;span class=&quot;nc&quot;&gt;Cluster&lt;/span&gt;
  &lt;span class=&quot;kp&quot;&gt;attr_accessor&lt;/span&gt; &lt;span class=&quot;ss&quot;&gt;:center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;ss&quot;&gt;:points&lt;/span&gt;

  &lt;span class=&quot;c1&quot;&gt;# Constructor with a starting centerpoint&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;initialize&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;vi&quot;&gt;@center&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;
    &lt;span class=&quot;vi&quot;&gt;@points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;

  &lt;span class=&quot;c1&quot;&gt;# Recenters the centroid and removes associated points&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;recenter!&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;xa&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ya&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;old_center&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;vi&quot;&gt;@center&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# Sum up all x/y coords&lt;/span&gt;
    &lt;span class=&quot;vi&quot;&gt;@points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;each&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;do&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;xa&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;point&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;x&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;ya&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;point&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;y&lt;/span&gt;  
    &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# Average out data&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;xa&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;ya&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;/=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# Reset center and return distance moved&lt;/span&gt;
    &lt;span class=&quot;vi&quot;&gt;@center&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;Point&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;new&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;xa&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ya&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;old_center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dist_to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;    
  &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Finally, the algorithm itself needs to be implemented.&lt;/p&gt;

&lt;p&gt;The parameters to the &lt;code class=&quot;highlighter-rouge&quot;&gt;kmeans&lt;/code&gt; function are a dataset (list of &lt;code class=&quot;highlighter-rouge&quot;&gt;Point&lt;/code&gt;s), data, number of clusters to find, k, and an optional halting delta, delta. The algorithm will halt when all of the clusters are updated by a value less than delta on an iteration.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-ruby&quot; data-lang=&quot;ruby&quot;&gt;&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;kmeans&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delta&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mo&quot;&gt;001&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Initially, the algorithm needs to choose the starting guesses for cluster centers. It does this by generating &lt;code class=&quot;highlighter-rouge&quot;&gt;k&lt;/code&gt; &lt;code class=&quot;highlighter-rouge&quot;&gt;Cluster&lt;/code&gt; objects, and assigning them a center from a randomly selected &lt;code class=&quot;highlighter-rouge&quot;&gt;Point&lt;/code&gt; from data.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-ruby&quot; data-lang=&quot;ruby&quot;&gt;&lt;span class=&quot;n&quot;&gt;clusters&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# Assign intial values for all clusters&lt;/span&gt;
&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;k&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;each&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;do&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;index&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;length&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;*&lt;/span&gt; &lt;span class=&quot;nb&quot;&gt;rand&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;).&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;to_i&lt;/span&gt;

  &lt;span class=&quot;n&quot;&gt;rand_point&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;index&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;Cluster&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;new&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;rand_point&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

  &lt;span class=&quot;n&quot;&gt;clusters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;push&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;

&lt;span class=&quot;c1&quot;&gt;# ... code to follow below ...&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Next is the main meat of the algorithm. The code loops indefinitely and assigns points to clusters by finding, for each point, which cluster center is the closest. This assignment will be updated, and become more accurate, each iteration of the loop while the clusters recenter.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-ruby&quot; data-lang=&quot;ruby&quot;&gt;&lt;span class=&quot;c1&quot;&gt;# Loop&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;kp&quot;&gt;true&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;# Assign points to clusters&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;data&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;each&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;do&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;point&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;min_dist&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;INFINITY&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;min_cluster&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;kp&quot;&gt;nil&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# Find the closest cluster&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;clusters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;each&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;do&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;dist&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;point&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;dist_to&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;center&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;

      &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dist&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;min_dist&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;min_dist&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dist&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;min_cluster&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cluster&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# Add to closest cluster&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;min_cluster&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;points&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;push&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;point&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;

  &lt;span class=&quot;c1&quot;&gt;# ... code from below ...&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# end of while loop&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Finally, in the code at the bottom of the while loop, we recalculate the centers of the clusters for the next iteration. This is done by calling &lt;code class=&quot;highlighter-rouge&quot;&gt;recenter!&lt;/code&gt; on all of the &lt;code class=&quot;highlighter-rouge&quot;&gt;Cluster&lt;/code&gt; objects. Additionally, we do some delta checking because we need to leave the loop eventually. By keeping track of the most that any &lt;code class=&quot;highlighter-rouge&quot;&gt;Cluster&lt;/code&gt; was updated, we can compare it against delta to see if all of the &lt;code class=&quot;highlighter-rouge&quot;&gt;Cluster&lt;/code&gt;s were below the input &lt;code class=&quot;highlighter-rouge&quot;&gt;delta&lt;/code&gt;. If the delta was hit, the algorithm terminates, returning a list of all of the &lt;code class=&quot;highlighter-rouge&quot;&gt;Cluster&lt;/code&gt;s found in the dataset.&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-ruby&quot; data-lang=&quot;ruby&quot;&gt;  &lt;span class=&quot;c1&quot;&gt;# Loop&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;while&lt;/span&gt; &lt;span class=&quot;kp&quot;&gt;true&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# ... code from above ...&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# Check deltas&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;max_delta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;INFINITY&lt;/span&gt;

    &lt;span class=&quot;n&quot;&gt;clusters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;each&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;do&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;dist_moved&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;cluster&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;recenter!&lt;/span&gt;

      &lt;span class=&quot;c1&quot;&gt;# Get largest delta&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dist_moved&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;gt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_delta&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;max_delta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dist_moved&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# Check exit condition&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;max_delta&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;delta&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;clusters&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;

    &lt;span class=&quot;c1&quot;&gt;# Reset points for the next iteration&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;clusters&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;each&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;do&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;cluster&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;|&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;cluster&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;points&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;

  &lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# end of while&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;end&lt;/span&gt;  &lt;span class=&quot;c1&quot;&gt;# end of kmeans()&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;Overall, k-means clustering is a pretty simple algorithm, as you can see from above. The entire source file, along with glue/integration code, is available &lt;a href=&quot;https://gist.github.com/cfdrake/995804#file-kmeans-rb&quot;&gt;here&lt;/a&gt; to download and/or view. Next, let’s see the program in action.&lt;/p&gt;

&lt;h2 id=&quot;example-run&quot;&gt;Example Run&lt;/h2&gt;

&lt;p&gt;As you can see from the link above, I ended up writing some additional shell code to implement reading in data, getting &lt;code class=&quot;highlighter-rouge&quot;&gt;k&lt;/code&gt;, and plotting the output of the algorithm. For the plotting, I used &lt;code class=&quot;highlighter-rouge&quot;&gt;rgplot&lt;/code&gt; (&lt;code class=&quot;highlighter-rouge&quot;&gt;gem install gnuplot&lt;/code&gt;) to pipe commands to a running instance of Gnuplot.&lt;/p&gt;

&lt;p&gt;To run the full program, open up a terminal and execute:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;$ ruby kmeans.rb CSVFILE
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;

&lt;p&gt;The program assumes &lt;code class=&quot;highlighter-rouge&quot;&gt;CSVFILE&lt;/code&gt; has two comma-separated floating point numbers per line, specifying both the x and y coordinates of a single point.&lt;/p&gt;

&lt;p&gt;To give you a feel for the output that k-means generates, I ran it on a random dataset. In the graph below, each set of points plotted with the same color indicates a &lt;code class=&quot;highlighter-rouge&quot;&gt;Cluster&lt;/code&gt; object’s member points. To run this yourself, you can grab my dataset &lt;a href=&quot;https://gist.github.com/cfdrake/995804#file-test-csv&quot;&gt;here&lt;/a&gt;, although creating your own with more definite, pre-designed clusters may be more interesting to see.&lt;/p&gt;

&lt;p&gt;&lt;img src=&quot;/public/images/clustering/plot.png&quot; alt=&quot;Output of k-means Clustering&quot; /&gt;&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;

&lt;p&gt;While this is a very simple example, note that the x and y axis can be whatever you want them to be (latitude/longitude of households, baseball stats, etc). You could even (easily) extend the program to support 3 or more parameters (dimensions). Thus, k-means clustering can actually be a powerful tool for grouping real-world datasets, despite the apparent simplicity.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>tq: A Tool to Stay Focused</title>
   <link href="http://colindrake.me/2011/05/15/tq-a-tool-to-stay-focused/"/>
   <updated>2011-05-15T00:00:00-04:00</updated>
   <id>http://colindrake.me/2011/05/15/tq-a-tool-to-stay-focused</id>
   <content type="html">&lt;p class=&quot;emphasized&quot;&gt;I like simple tools. I like tools that do their one required thing, get out of my way, and let me get stuff done. When looking for a way to keep a task list, I was completely overwhelmed by all the to-do software out there. So I built my own.&lt;/p&gt;

&lt;h2 id=&quot;enter-tq&quot;&gt;Enter tq&lt;/h2&gt;
&lt;p&gt;After reflecting on how I work when I actually get stuff done, I realized I typically like to finish my tasks in a queue, one at a time. I come up with the tasks I need done, break them into a bunch of simple subtasks, write them down sequentially, and hack on down the list. So I wrote a shell script that lets me manage tasks like that. &lt;code class=&quot;highlighter-rouge&quot;&gt;tq&lt;/code&gt;, or &lt;code class=&quot;highlighter-rouge&quot;&gt;task queue&lt;/code&gt;, is the result of this idea. It implements the following actions:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;tq push ITEM&lt;/code&gt; — Add a todo item to the end of the list.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;tq pop&lt;/code&gt; — Mark the current item as “done” and display the next item in line.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;tq peek&lt;/code&gt; — Display the current item.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;tq cheat&lt;/code&gt; — Open the task list in &lt;code class=&quot;highlighter-rouge&quot;&gt;$EDITOR&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is the most basic feature set I could come up with, and from experiments using it, the design seems to work well. It’s easy to stay on task, keep focused, and get stuff done. Just how I like it.&lt;/p&gt;

&lt;h2 id=&quot;example&quot;&gt;Example&lt;/h2&gt;
&lt;p&gt;Here’s a look at how the tool works:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-bash&quot; data-lang=&quot;bash&quot;&gt;&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;tq
  Usage: tq CMD

    CMD can be:
      push ITEM Add ITEM to the end of the queue
      pop       Remove current item from the queue and
                print out the next item
                &lt;span class=&quot;k&quot;&gt;in &lt;/span&gt;the list to work on
      peek      Print the current item being worked on,
                i.e. the front of the queue
      cheat     Edit the taskfile with &lt;span class=&quot;nv&quot;&gt;$EDITOR&lt;/span&gt;

&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;tq push &lt;span class=&quot;s2&quot;&gt;&quot;ponder some ideas...&quot;&lt;/span&gt;
&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;tq push &lt;span class=&quot;s2&quot;&gt;&quot;write resulting CLI app&quot;&lt;/span&gt;
&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;tq push &lt;span class=&quot;s2&quot;&gt;&quot;write blog post&quot;&lt;/span&gt;
&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;tq push &lt;span class=&quot;s2&quot;&gt;&quot;PROFIT?&quot;&lt;/span&gt;
&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;tq peek
ponder some ideas...
&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;tq pop
write resulting CLI app
&lt;span class=&quot;gp&quot;&gt;$ &lt;/span&gt;tq pop
write blog post
...&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h2 id=&quot;source&quot;&gt;Source&lt;/h2&gt;
&lt;p&gt;I wrote &lt;code class=&quot;highlighter-rouge&quot;&gt;tq&lt;/code&gt; as a simple 31-line bash script. It’s not much, but it has paid off its rent, so to speak.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note:&lt;/em&gt; Before using this tool, you should set &lt;code class=&quot;highlighter-rouge&quot;&gt;$TASKFILE&lt;/code&gt; to the file you want to keep your task queue in (I actually keep mine on Dropbox).&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-bash&quot; data-lang=&quot;bash&quot;&gt;&lt;span class=&quot;c&quot;&gt;#!/usr/bin/env bash&lt;/span&gt;
&lt;span class=&quot;c&quot;&gt;# tq - a script to maintain a simple task queue&lt;/span&gt;
 
&lt;span class=&quot;nv&quot;&gt;TASKFILE&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;=&lt;/span&gt;~/Documents/tq.txt
 
&lt;span class=&quot;c&quot;&gt;# File check&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;[&lt;/span&gt; ! -f &lt;span class=&quot;nv&quot;&gt;$TASKFILE&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;]&lt;/span&gt;; &lt;span class=&quot;k&quot;&gt;then
  &lt;/span&gt;touch &lt;span class=&quot;nv&quot;&gt;$TASKFILE&lt;/span&gt;  
&lt;span class=&quot;k&quot;&gt;fi&lt;/span&gt;
 
&lt;span class=&quot;c&quot;&gt;# Main driver&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;[&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$1&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;push&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;]&lt;/span&gt;; &lt;span class=&quot;k&quot;&gt;then
  &lt;/span&gt;&lt;span class=&quot;nb&quot;&gt;shift
  echo&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$*&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt; &amp;gt;&amp;gt; &lt;span class=&quot;nv&quot;&gt;$TASKFILE&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;[&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$1&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;pop&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;]&lt;/span&gt;; &lt;span class=&quot;k&quot;&gt;then
  &lt;/span&gt;tail -n +2 &lt;span class=&quot;nv&quot;&gt;$TASKFILE&lt;/span&gt; | tee &lt;span class=&quot;nv&quot;&gt;$TASKFILE&lt;/span&gt; | head -n 1
&lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;[&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$1&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;peek&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;]&lt;/span&gt;; &lt;span class=&quot;k&quot;&gt;then
  &lt;/span&gt;head -n 1 &lt;span class=&quot;nv&quot;&gt;$TASKFILE&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;elif&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;[&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt;&lt;span class=&quot;nv&quot;&gt;$1&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;cheat&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;]&lt;/span&gt;; &lt;span class=&quot;k&quot;&gt;then&lt;/span&gt;
  &lt;span class=&quot;nv&quot;&gt;$EDITOR&lt;/span&gt; &lt;span class=&quot;nv&quot;&gt;$TASKFILE&lt;/span&gt;
&lt;span class=&quot;k&quot;&gt;else
  &lt;/span&gt;cat &lt;span class=&quot;sh&quot;&gt;&amp;lt;&amp;lt;EOF
Usage: tq CMD
 
CMD can be:
  push ITEM Add ITEM to the end of the queue
  pop       Remove the current item from the queue
            and print out the next item
            in the list to work on
  peek      Print the current item being worked on,
            i.e. the front of the queue
  cheat     Edit the taskfile with \$EDITOR
EOF
&lt;/span&gt;&lt;span class=&quot;k&quot;&gt;fi&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;p&gt;You can &lt;code class=&quot;highlighter-rouge&quot;&gt;wget&lt;/code&gt; the raw source file &lt;a href=&quot;https://gist.githubusercontent.com/cfdrake/973503/raw/3bdddbab15c5f406674b7c039c887a1d58bceca6/tq.sh&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
</content>
 </entry>
 
 <entry>
   <title>A Genetic Algorithm in Python</title>
   <link href="http://colindrake.me/2011/05/01/ga-in-python/"/>
   <updated>2011-05-01T00:00:00-04:00</updated>
   <id>http://colindrake.me/2011/05/01/ga-in-python</id>
   <content type="html">&lt;p&gt;In the spirit of taking biology and artificial intelligence this quarter, I decided to try to throw together a program combining the concepts of the two. I ended up writing a python script that performs “natural selection” of a population of initially random strings towards an ideal “Hello, World” string, implementing a really basic genetic algorithm.&lt;/p&gt;

&lt;h2 id=&quot;the-algorithm-of-evolution&quot;&gt;The Algorithm of Evolution&lt;/h2&gt;
&lt;p&gt;Before we look at the code, I’m going to go over the basics of how the “algorithms” of &lt;a href=&quot;http://en.wikipedia.org/wiki/Evolution&quot;&gt;evolution&lt;/a&gt; and genetics work (or at least the simple model of it that we’ll use).&lt;/p&gt;

&lt;p&gt;To begin, we generate a random initial population of organisms. This will serve as the set of organisms from which we will evolve better, more-fit forms. Next, we implement natural selection by iterating over the following steps for each generation that we would like to simulate:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Assign a fitness value to each organism in the population. This should reflect how well the individual is suited to survival in the current environment.&lt;/li&gt;
  &lt;li&gt;Map the fitness value to a probability of being picked to survive into the next generation. Individuals with more fitness should be more likely to be selected to survive.&lt;/li&gt;
  &lt;li&gt;Create a “working population” by choosing individuals from the population with the chance of each being chosen based on their calculated probabilities. This means that individuals can be chosen many times, once, or even not at all.&lt;/li&gt;
  &lt;li&gt;Create “offspring” between each pair of two organisms from the working population by combining DNA from each parent. In our program, each set of parents will produce 2 offspring to drive the new generation, keeping the population levels constant.&lt;/li&gt;
  &lt;li&gt;Randomly mutate each individual’s genes slightly. This ensures genetic diversity remains within the population.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;At the end of this process (once a certain fitness or generation cap has been hit), the resulting population should be significantly more fit to the environment than in the initial population.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;However:&lt;/strong&gt; while this process can produce optimized solutions difficult for humans to design from the start, it’s important to note that nothing in this algorithm guarantees a &lt;em&gt;perfectly&lt;/em&gt; fit organism in the end.&lt;/p&gt;

&lt;h2 id=&quot;implementation-in-python&quot;&gt;Implementation in Python&lt;/h2&gt;

&lt;p&gt;Now that we know how the algorithm itself will work, we can get to the code. You can either interpret this as an experiment in literate programming or as me being too lazy to write any explanation at all! Here’s the (at least highly annotated) source:&lt;/p&gt;

&lt;figure class=&quot;highlight&quot;&gt;&lt;pre&gt;&lt;code class=&quot;language-ruby&quot; data-lang=&quot;ruby&quot;&gt;&lt;span class=&quot;s2&quot;&gt;&quot;&quot;&quot;
helloevolve.py implements a genetic algorithm that starts with a base
population of randomly generated strings, iterates over a certain number of
generations while implementing &#39;natural selection&#39;, and prints out the most fit
string.
 
The parameters of the simulation can be changed by modifying one of the many
global variables. To change the &quot;&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;most&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fit&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot; string, modify OPTIMAL. POP_SIZE
controls the size of each generation, and GENERATIONS is the amount of 
generations that the simulation will loop through before returning the fittest
string.
 
This program subject to the terms of the BSD license listed below.

Copyright (c) 2011 Colin Drake
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the &quot;&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;Software&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED &quot;&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;AS&lt;/span&gt; &lt;span class=&quot;no&quot;&gt;IS&lt;/span&gt;&lt;span class=&quot;s2&quot;&gt;&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
&quot;&quot;&quot;&lt;/span&gt;
 
&lt;span class=&quot;n&quot;&gt;import&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;
 
&lt;span class=&quot;c1&quot;&gt;#&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Global variables&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Setup optimal string and GA input variables.&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#&lt;/span&gt;
 
&lt;span class=&quot;no&quot;&gt;OPTIMAL&lt;/span&gt;     &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;Hello, World&quot;&lt;/span&gt;
&lt;span class=&quot;no&quot;&gt;DNA_SIZE&lt;/span&gt;    &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;len&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;OPTIMAL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
&lt;span class=&quot;no&quot;&gt;POP_SIZE&lt;/span&gt;    &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;20&lt;/span&gt;
&lt;span class=&quot;no&quot;&gt;GENERATIONS&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;5000&lt;/span&gt;
 
&lt;span class=&quot;c1&quot;&gt;#&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Helper functions&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# These are used as support, but aren&#39;t direct GA-specific functions.&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#&lt;/span&gt;
 
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;weighted_choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
  &lt;span class=&quot;s2&quot;&gt;&quot;&quot;&quot;
  Chooses a random element from items, where items is a list of tuples in
  the form (item, weight). weight determines the probability of choosing its
  respective item. Note: this function is borrowed from ActiveState Recipes.
  &quot;&quot;&quot;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;weight_total&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;sum&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;((&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;items&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;uniform&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight_total&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;ss&quot;&gt;items:
    &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;&lt;/span&gt; &lt;span class=&quot;ss&quot;&gt;weight:
      &lt;/span&gt;&lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;n&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weight&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;item&lt;/span&gt;
 
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;random_char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
  &lt;span class=&quot;s2&quot;&gt;&quot;&quot;&quot;
  Return a random character between ASCII 32 and 126 (i.e. spaces, symbols,
  letters, and digits). All characters returned will be nicely printable.
  &quot;&quot;&quot;&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;chr&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;randrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;32&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;126&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)))&lt;/span&gt;
 
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;random_population&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;():&lt;/span&gt;
  &lt;span class=&quot;s2&quot;&gt;&quot;&quot;&quot;
  Return a list of POP_SIZE individuals, each randomly generated via iterating
  DNA_SIZE times to generate a string of random characters with random_char().
  &quot;&quot;&quot;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;pop&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;i&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;xrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;POP_SIZE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;dna&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;&quot;&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;xrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;DNA_SIZE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;dna&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;pop&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;pop&lt;/span&gt;
 
&lt;span class=&quot;c1&quot;&gt;#&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# GA functions&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# These make up the bulk of the actual GA algorithm.&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#&lt;/span&gt;
 
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;fitness&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
  &lt;span class=&quot;s2&quot;&gt;&quot;&quot;&quot;
  For each gene in the DNA, this function calculates the difference between
  it and the character in the same position in the OPTIMAL string. These values
  are summed and then returned.
  &quot;&quot;&quot;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;fitness&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;xrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;DNA_SIZE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;fitness&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;abs&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ord&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;-&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ord&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;OPTIMAL&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]))&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fitness&lt;/span&gt;
 
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;mutate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
  &lt;span class=&quot;s2&quot;&gt;&quot;&quot;&quot;
  For each gene in the DNA, there is a 1/mutation_chance chance that it will be
  switched out with a random character. This ensures diversity in the
  population, and ensures that is difficult to get stuck in local minima.
  &quot;&quot;&quot;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;dna_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;&quot;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;mutation_chance&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;100&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;c&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;xrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;DNA_SIZE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mutation_chance&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;dna_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_char&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
    &lt;span class=&quot;ss&quot;&gt;else:
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dna_out&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;+=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dna&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;c&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dna_out&lt;/span&gt;
 
&lt;span class=&quot;k&quot;&gt;def&lt;/span&gt; &lt;span class=&quot;nf&quot;&gt;crossover&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dna1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dna2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
  &lt;span class=&quot;s2&quot;&gt;&quot;&quot;&quot;
  Slices both dna1 and dna2 into two parts at a random index within their
  length and merges them. Both keep their initial sublist up to the crossover
  index, but their ends are swapped.
  &quot;&quot;&quot;&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;int&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;random&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;*&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;DNA_SIZE&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;return&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dna1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;ss&quot;&gt;:pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dna2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:],&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;dna2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;ss&quot;&gt;:pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;+&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;dna1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pos&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:])&lt;/span&gt;
 
&lt;span class=&quot;c1&quot;&gt;#&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Main driver&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;# Generate a population and simulate GENERATIONS generations.&lt;/span&gt;
&lt;span class=&quot;c1&quot;&gt;#&lt;/span&gt;
 
&lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;__name__&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;__main__&quot;&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;# Generate initial population. This will create a list of POP_SIZE strings,&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;# each initialized to a sequence of random characters.&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;population&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;random_population&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;()&lt;/span&gt;
 
  &lt;span class=&quot;c1&quot;&gt;# Simulate all of the generations.&lt;/span&gt;
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;generation&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;xrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;GENERATIONS&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
    &lt;span class=&quot;nb&quot;&gt;print&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;Generation %s... Random sample: &#39;%s&#39;&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;generation&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;population&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
    &lt;span class=&quot;n&quot;&gt;weighted_population&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
 
    &lt;span class=&quot;c1&quot;&gt;# Add individuals and their respective fitness levels to the weighted&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# population list. This will be used to pull out individuals via certain&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# probabilities during the selection phase. Then, reset the population list&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# so we can repopulate it after selection.&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;individual&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;ss&quot;&gt;population:
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fitness_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fitness&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;individual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
 
      &lt;span class=&quot;c1&quot;&gt;# Generate the (individual,fitness) pair, taking in account whether or&lt;/span&gt;
      &lt;span class=&quot;c1&quot;&gt;# not we will accidently divide by zero.&lt;/span&gt;
      &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fitness_val&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;==&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;:&lt;/span&gt;
        &lt;span class=&quot;n&quot;&gt;pair&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;individual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;ss&quot;&gt;else:
        &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pair&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;individual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;mi&quot;&gt;1&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fitness_val&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
 
      &lt;span class=&quot;n&quot;&gt;weighted_population&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;pair&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
 
    &lt;span class=&quot;n&quot;&gt;population&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;p&quot;&gt;[]&lt;/span&gt;
 
    &lt;span class=&quot;c1&quot;&gt;# Select two random individuals, based on their fitness probabilites, cross&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# their genes over at a random point, mutate them, and add them back to the&lt;/span&gt;
    &lt;span class=&quot;c1&quot;&gt;# population for the next iteration.&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;_&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;xrange&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;no&quot;&gt;POP_SIZE&lt;/span&gt;&lt;span class=&quot;o&quot;&gt;/&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;):&lt;/span&gt;
      &lt;span class=&quot;c1&quot;&gt;# Selection&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;ind1&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weighted_choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weighted_population&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;ind2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;weighted_choice&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;weighted_population&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
 
      &lt;span class=&quot;c1&quot;&gt;# Crossover&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;ind1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ind2&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;crossover&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ind1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;,&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ind2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
 
      &lt;span class=&quot;c1&quot;&gt;# Mutate and add back into the population.&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;population&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mutate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ind1&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;population&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;.&lt;/span&gt;&lt;span class=&quot;nf&quot;&gt;append&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;mutate&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ind2&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;))&lt;/span&gt;
 
  &lt;span class=&quot;c1&quot;&gt;# Display the highest-ranked string after all generations have been iterated&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;# over. This will be the closest string to the OPTIMAL string, meaning it&lt;/span&gt;
  &lt;span class=&quot;c1&quot;&gt;# will have the smallest fitness value. Finally, exit the program.&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;fittest_string&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;population&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;]&lt;/span&gt;
  &lt;span class=&quot;n&quot;&gt;minimum_fitness&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fitness&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;population&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;[&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;])&lt;/span&gt;
 
  &lt;span class=&quot;k&quot;&gt;for&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;individual&lt;/span&gt; &lt;span class=&quot;k&quot;&gt;in&lt;/span&gt; &lt;span class=&quot;ss&quot;&gt;population:
    &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;ind_fitness&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fitness&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;n&quot;&gt;individual&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;
    &lt;span class=&quot;k&quot;&gt;if&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ind_fitness&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;&amp;lt;=&lt;/span&gt; &lt;span class=&quot;ss&quot;&gt;minimum_fitness:
      &lt;/span&gt;&lt;span class=&quot;n&quot;&gt;fittest_string&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;individual&lt;/span&gt;
      &lt;span class=&quot;n&quot;&gt;minimum_fitness&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;=&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;ind_fitness&lt;/span&gt;
 
  &lt;span class=&quot;nb&quot;&gt;print&lt;/span&gt; &lt;span class=&quot;s2&quot;&gt;&quot;Fittest String: %s&quot;&lt;/span&gt; &lt;span class=&quot;o&quot;&gt;%&lt;/span&gt; &lt;span class=&quot;n&quot;&gt;fittest_string&lt;/span&gt;
  &lt;span class=&quot;nb&quot;&gt;exit&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;(&lt;/span&gt;&lt;span class=&quot;mi&quot;&gt;0&lt;/span&gt;&lt;span class=&quot;p&quot;&gt;)&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/figure&gt;

&lt;h2 id=&quot;result&quot;&gt;Result&lt;/h2&gt;
&lt;p&gt;Here’s an example of output generated by the script:&lt;/p&gt;

&lt;div class=&quot;highlighter-rouge&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;Generation 0... Random sample: &#39;RE}36#qP&#39;_u%&#39;
Generation 1... Random sample: &#39;{z?.;7CEYy#g&#39;
Generation 2... Random sample: &#39;0/5^aGk]yx1=&#39;
Generation 3... Random sample: &#39;lP6]`HBUS|1=&#39;
Generation 4... Random sample: &#39;l,iK%6{;&amp;lt;|Lk&#39;
Generation 5... Random sample: &#39;0/5^aGk]y][j&#39;

Generation 1337... Random sample: &#39;Hdllo-fWorme&#39;

Generation 2717... Random sample: &#39;Hdllo, Worme&#39;

Generation 4999... Random sample: &#39;HeClo, World&#39;
Fittest String: Hello, World
&lt;/code&gt;&lt;/pre&gt;
&lt;/div&gt;
</content>
 </entry>
 
 <entry>
   <title>Why I Like the BSD</title>
   <link href="http://colindrake.me/2011/02/28/why-i-like-the-bsd/"/>
   <updated>2011-02-28T00:00:00-05:00</updated>
   <id>http://colindrake.me/2011/02/28/why-i-like-the-bsd</id>
   <content type="html">&lt;p&gt;Let’s find some common ground here before we start. For those of you that don’t know, the &lt;a href=&quot;http://en.wikipedia.org/wiki/BSD_licenses&quot;&gt;BSD&lt;/a&gt; is an open source software license. It is one of many “competing” licenses that aims at maximizing freedom for some group in the realm of software development and distribution. Specifically, the BSD attempts to maximize this desired freedom by saying as little as possible. Less clauses means less words means less chances to restrict a participant in the software development cycle. This stark simplicity has many implications which I will discuss later in the article.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: I’m not going to provide the text of the BSD license here, however short it may be. There’s Wikipedia for that. I want to discourage copying, pasting, and using without thinking (even though I’d love for the world to have more BSD-licensed software). This article merely reflects my own opinions and preferences. Furthermore, I am not a lawyer, so take what I say about this with a grain of salt. But enough with the disclaimers…&lt;/em&gt;&lt;/p&gt;

&lt;h2 id=&quot;control&quot;&gt;Control&lt;/h2&gt;
&lt;p&gt;As I’ve said before, the BSD is a very simple license. Unlike many of its competitors, it directly restricts only a handful of freedoms, putting it particularly near a declaration of public domain. Most importantly though, the BSD opts to say less about the developer’s liberties, which in turn increases the liberties allowed towards the end user. This is the most important quality of the BSD, because in that regard, it is unique when compared to other open source licenses, such as the &lt;a href=&quot;http://en.wikipedia.org/wiki/GPL&quot;&gt;GPL&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This simple ruleset manages to elegantly retain developer’s most basic rights to their code while keeping other routes of usage, not traditionally allowed by open source, free for use.&lt;/p&gt;

&lt;h2 id=&quot;commercialization&quot;&gt;Commercialization&lt;/h2&gt;
&lt;p&gt;This lack of control allows for corporations, businesses, and users alike to share, copy, sell, and modify the project to their heart’s content. The amount of freedom given to them is very high: users can extend, rebrand, give commercial support for, or even start a business around somebody else’s BSD project. As long as a copy of the BSD license with the original author’s name is retained, the end user basically has the right to do whatever they want with it. The BSD’s sole goal here is the lack of warranty and prevention of somebody claiming other’s work as their own.&lt;/p&gt;

&lt;p&gt;This freedom allowed Microsoft to implement Windows networking systems at a minimal cost, and gave Apple a stable base to start Mac OSX from. Rather than having to redesign and implement the wheel, both of these companies could focus on the facets of their respective project thats were the most important. This helped them get their product out of the door, and gave end users a time-tested infrastructure to work on. In short, the BSD isn’t just free. It’s profitable (both monetarily and pragmatically speaking) for all involved parties.&lt;/p&gt;

&lt;h2 id=&quot;simplicity&quot;&gt;Simplicity&lt;/h2&gt;
&lt;p&gt;If you know me, it’s no big secret that I’m a fan of minimalism. Philip Glass’ simple arpeggios, Hemingway’s “iceburg” writing style, and the BSD all share an underlying philosophy behind them. Make your point with the least amount of extraneous bells and whistles as possible.&lt;/p&gt;

&lt;p&gt;The BSD excels in this arena. &lt;a href=&quot;http://www.youtube.com/watch?v=owGykVbfgUE&quot;&gt;Look at the GPL. Now, look at your man — Err, the BSD&lt;/a&gt;. In a few short paragraphs, the BSD manages to describe a system of distribution that strikes a perfect balance between exclusivity and openness in a way that’s fair and beneficial to everyone.&lt;/p&gt;

&lt;h2 id=&quot;counterarguments&quot;&gt;Counterarguments&lt;/h2&gt;
&lt;p&gt;Typically, I’ve found that the BSD is very versatile. Whether you’re writing your sassy new jQuery plugin to turn all H2 tags baby blue, or a device driver for an OS kernel, the BSD normally has some type of net benefit to offer you. However, I concede that there are special cases where other licenses might be more apt to your interests.&lt;/p&gt;

&lt;p&gt;Sometimes, by choice, you don’t want people to go off and run with your idea or code. This suggests that the GPL may be a better route. This is especially true in academic or learning projects, where your main goal is not utility, but obtaining an increase in personal knowledge. The “cost” of using or modifying your project essentially becomes more open source code given back to you.&lt;/p&gt;

&lt;p&gt;Furthermore, not all source code can or should be open sourced. I like to make as much code as I can free or open source, but sometimes you may find that your business is surviving purely because you are the only one that knows how to do something, or at least do it effectively. In these cases, a more limited, or even proprietary license, may suffice.&lt;/p&gt;

&lt;p&gt;Cases like these don’t illustrate a failing of the BSD. They only show that you should always take into consideration your goals for any given project. Software licenses should not be a dogmatic matter. No matter how much I like the BSD, I still evaluate different licenses on a per-project basis, because sometimes a different license is just flat out better suited.&lt;/p&gt;

&lt;h2 id=&quot;conclusion&quot;&gt;Conclusion&lt;/h2&gt;
&lt;p&gt;Again, I’d like to state that the goal of this article is not to undermine the efforts of the GPL, WTFPL, et. al. I’m only here to provide a rationale for my own preference. That being said, I think the BSD is, in general, a good choice for many kinds of projects. It is open, allows authors to get credit for their work, is compatible with for-profit software, and yet still provides freedom all around the table.&lt;/p&gt;
</content>
 </entry>
 

</feed>
