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

<channel>
	<title>bluegrayblog</title>
	<atom:link href="http://www.bluegraybox.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bluegraybox.com/blog</link>
	<description>so much to do, so little time...</description>
	<lastBuildDate>Thu, 10 May 2012 12:52:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Remedial Javascript</title>
		<link>http://www.bluegraybox.com/blog/2012/05/10/remedial-javascript/</link>
		<comments>http://www.bluegraybox.com/blog/2012/05/10/remedial-javascript/#comments</comments>
		<pubDate>Thu, 10 May 2012 12:52:45 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[personal]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=271</guid>
		<description><![CDATA[My background here is that I&#8217;ve worked with Javascript on and off for years, but I never actually wrapped my head around how its inheritance works until just recently. I started out doing little bits of UI bling, then moved onto dynamic forms and simple ajax requests (pre-jQuery), then fancier stuff with jQuery and friends. [...]]]></description>
			<content:encoded><![CDATA[<p>My background here is that I&#8217;ve worked with Javascript on and off for years, but I never actually wrapped my head around how its inheritance works until just recently.  I started out doing little bits of UI bling, then moved onto dynamic forms and simple ajax requests (pre-jQuery), then fancier stuff with jQuery and friends.  So I&#8217;ve been able to get a lot done.  It&#8217;s only when reading something like <a href="http://shop.oreilly.com/product/9780596517748.do">Javascript: the Good Parts</a> that I&#8217;d get this nagging sense that I was missing something fundamental.  Lately though, I&#8217;ve started working with backbone.js, doing serious model-view-controller programming in the browser, and that nagging has become loud and persistent.</p>
<p>Part of the problem is that I&#8217;m coming from a Java background, and Javascript looks a lot like it.  It <em>looks</em> like it has the Java-style class inheritance that I&#8217;m familiar with.  It&#8217;s got syntax like:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="javascript"><pre class="de1"><span class="kw2">var</span> o <span class="sy0">=</span> <span class="kw2">new</span> Object<span class="sy0">;</span></pre></div></div></div></div></div></div></div>


<p>So I instinctively think, &#8220;Great, <strong>Object</strong> is a class, and <strong>o</strong> is an instance of that class.&#8221; You can think that, and Javascript will mostly work the way you expect.  You can write a fair amount of code believing that.</p>
<p>But it&#8217;s wrong.</p>
<p>Javascript has prototypal inheritance, not class inheritance.  I knew that, and seeing this class-y syntax gave me the feeling of being lied to.  Not a malicious lie, but a little white &#8220;I&#8217;m glossing over the details here&#8221; lie.  And once I got into trying to create my own class hierarchy, or extending someone else&#8217;s, those details started to matter.  Things just didn&#8217;t work quite the way I expected.  Mostly, I&#8217;d be missing values that I thought I&#8217;d inherited from somewhere.  Even then, I could figure out what had gone wrong and fix it on a case-by-case basis, but that made it clear that there was something important I really just didn&#8217;t understand.</p>
<p>I&#8217;ve read a number of books and articles that talk about Javascript&#8217;s prototypal nature, and how you construct and extend objects, but my sense of what was going on under the hood never quite clicked.  So I finally did what I always end up having to do to make sense of some bit of programming weirdness: step away from the big program I&#8217;m working on, and sit down at a shell to run some little experiments.  In this case, it&#8217;s Chrome&#8217;s Javascript console.  (Lines with a <strong>&gt;</strong> are what I type. Lines without are the console&#8217;s response.) Starting off with the previous example:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="javascript"><pre class="de1"><span class="sy0">&gt;</span> o <span class="sy0">=</span> <span class="kw2">new</span> Object<span class="sy0">;</span>
Object</pre></div></div></div></div></div></div></div>


<p>Great, I&#8217;ve created a new Object.  But what is this &#8220;Object&#8221; thing really?</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="javascript"><pre class="de1"><span class="sy0">&gt;</span> Object
<span class="kw2">function</span> Object<span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="br0">&#91;</span>native code<span class="br0">&#93;</span> <span class="br0">&#125;</span></pre></div></div></div></div></div></div></div>


<p>Wait, so Object is a function. Huh?</p>
<p>The deal is that <strong>new</strong> is what&#8217;s actually doing the heavy lifting here, creating a new object.  The Object function is just filling in the details.  There&#8217;s nothing magic about it.  You could call <strong>new</strong> on any function, and you&#8217;d get a new object.  If that function sets any properties on <strong>this</strong>, they&#8217;ll show up in it.  If that function has a property named <strong>prototype</strong>, the new object will inherit properties from it.  <strong>prototype</strong> <em>should</em> be an object, but since functions are also objects, you won&#8217;t get an error if you mess up.</p>
<p>For example:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="javascript"><pre class="de1"><span class="sy0">&gt;</span> A <span class="sy0">=</span> <span class="kw2">function</span> <span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw1">this</span>.<span class="me1">kingdom</span> <span class="sy0">=</span> <span class="st0">&quot;Animalia&quot;</span><span class="sy0">;</span> <span class="br0">&#125;</span>
<span class="kw2">function</span> <span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw1">this</span>.<span class="me1">kingdom</span> <span class="sy0">=</span> <span class="st0">&quot;Animalia&quot;</span><span class="sy0">;</span> <span class="br0">&#125;</span>
<span class="sy0">&gt;</span> B <span class="sy0">=</span> <span class="kw2">function</span> <span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw1">this</span>.<span class="me1">phylum</span> <span class="sy0">=</span> <span class="st0">&quot;Chordata&quot;</span><span class="sy0">;</span> <span class="br0">&#125;</span>
<span class="kw2">function</span> <span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw1">this</span>.<span class="me1">phylum</span> <span class="sy0">=</span> <span class="st0">&quot;Chordata&quot;</span><span class="sy0">;</span> <span class="br0">&#125;</span>
<span class="sy0">&gt;</span> B.<span class="me1">prototype</span> <span class="sy0">=</span> A  <span class="co1">// wrong!</span>
<span class="kw2">function</span> <span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span> <span class="kw1">this</span>.<span class="me1">kingdom</span> <span class="sy0">=</span> <span class="st0">&quot;Animalia&quot;</span><span class="sy0">;</span> <span class="br0">&#125;</span>
<span class="sy0">&gt;</span> b <span class="sy0">=</span> <span class="kw2">new</span> B
B
<span class="sy0">&gt;</span> b.<span class="me1">kingdom</span>
undefined</pre></div></div></div></div></div></div></div>


<p>Here, everything looks fine until you try to get <strong>b.kingdom</strong>.  The trouble is that kingdom is not a property of <strong>A</strong>; it&#8217;s just a property that <strong>A</strong> sets on <strong>this</strong>.</p>
<p>The right thing would be:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="javascript"><pre class="de1"><span class="sy0">&gt;</span> a <span class="sy0">=</span> <span class="kw2">new</span> A
A
<span class="sy0">&gt;</span> B.<span class="me1">prototype</span> <span class="sy0">=</span> a
A
<span class="sy0">&gt;</span> b <span class="sy0">=</span> <span class="kw2">new</span> B
B
<span class="sy0">&gt;</span> b.<span class="me1">kingdom</span>
<span class="st0">&quot;Animalia&quot;</span></pre></div></div></div></div></div></div></div>


<p>Now, any properties you add to <strong>a</strong> will be inherited by <strong>b</strong>:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="javascript"><pre class="de1"><span class="sy0">&gt;</span> a.<span class="kw2">class</span> <span class="sy0">=</span> <span class="st0">&quot;Mammalia&quot;</span>
<span class="st0">&quot;Mammalia&quot;</span>
<span class="sy0">&gt;</span> b.<span class="kw2">class</span>
<span class="st0">&quot;Mammalia&quot;</span></pre></div></div></div></div></div></div></div>


<p>But the properties that <strong>B</strong> set on <strong>b</strong> override <strong>a</strong>&#8216;s properties:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="javascript"><pre class="de1"><span class="sy0">&gt;</span> a.<span class="me1">phylum</span> <span class="sy0">=</span> <span class="st0">&quot;whatever&quot;</span>
<span class="st0">&quot;whatever&quot;</span>
<span class="sy0">&gt;</span> b.<span class="me1">phylum</span>
<span class="st0">&quot;Chordata&quot;</span></pre></div></div></div></div></div></div></div>


<p><strong>b</strong> doesn&#8217;t inherit properties from <strong>B</strong>:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="javascript"><pre class="de1"><span class="sy0">&gt;</span> B.<span class="me1">order</span> <span class="sy0">=</span> <span class="st0">&quot;Carnivora&quot;</span>
<span class="st0">&quot;Carnivora&quot;</span>
<span class="sy0">&gt;</span> b.<span class="me1">order</span>
undefined</pre></div></div></div></div></div></div></div>


<p>And <strong>b</strong> keeps its relation to <strong>a</strong> even if <strong>B</strong> changes its prototype</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="javascript"><pre class="de1"><span class="sy0">&gt;</span> B.<span class="me1">prototype</span> <span class="sy0">=</span> <span class="br0">&#123;</span><span class="br0">&#125;</span>
Object
<span class="sy0">&gt;</span> b.<span class="me1">kingdom</span>
<span class="st0">&quot;Animalia&quot;</span></pre></div></div></div></div></div></div></div>


<p>So that&#8217;s what it does, but what are the relationships between all these objects and functions?</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="javascript"><pre class="de1"><span class="sy0">&gt;</span> b <span class="kw1">instanceof</span> B
<span class="kw2">true</span>
<span class="sy0">&gt;</span> b <span class="kw1">instanceof</span> A
<span class="kw2">true</span>
<span class="sy0">&gt;</span> b <span class="kw1">instanceof</span> a
TypeError<span class="sy0">:</span> Expecting a <span class="kw2">function</span> <span class="kw1">in</span> <span class="kw1">instanceof</span> check<span class="sy0">,</span> but got #<span class="sy0">&lt;</span>error<span class="sy0">&gt;</span>
<span class="sy0">&gt;</span> b.__proto__ <span class="sy0">===</span> a
<span class="kw2">true</span>
<span class="sy0">&gt;</span> B <span class="kw1">instanceof</span> A
<span class="kw2">false</span></pre></div></div></div></div></div></div></div>


<p>So we have this odd sort of dual inheritance going on.  <strong>b</strong> is an instance of <strong>B</strong>, and has a prototype of <strong>a</strong>.  The <strong>instanceof</strong> relationship is purely historical: Changes to <strong>B</strong> don&#8217;t affect <strong>b</strong> after its construction.  The prototype relation is ongoing and dynamic.  Changes to <strong>a</strong>&#8216;s properties show up in <strong>b</strong> (unless <strong>b</strong> overrides them).  Perhaps even more oddly, <strong>b</strong> is an instance of <strong>a</strong>&#8216;s constructor, but there&#8217;s no direct connection from <strong>B</strong> to <strong>A</strong>, only through <strong>a</strong>.  It looks like this in my head:</p>
<pre>
  B   A
 / \ /
b---a
</pre>
<p>In short, an object inherits a type from its constructor and behavior from its prototype.  In a class-based language, an object gets both of these from its class, but in Javascript, &#8220;What is it?&#8221; and &#8220;What can it do?&#8221; are different questions with different answers.</p>
<p>If you got all the way through this article and this stuff still doesn&#8217;t make sense, grab a Javascript console and try it out yourself. Work through the examples. Type them in by hand; don&#8217;t copy-paste them. (Seriously, that makes a huge difference.) Ask your own questions, come up with your own experiments. Tinker.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2012/05/10/remedial-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Remedial CSS</title>
		<link>http://www.bluegraybox.com/blog/2012/03/25/remedial-css/</link>
		<comments>http://www.bluegraybox.com/blog/2012/03/25/remedial-css/#comments</comments>
		<pubDate>Mon, 26 Mar 2012 01:51:45 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[web design]]></category>
		<category><![CDATA[css]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=245</guid>
		<description><![CDATA[In my defense, let me point out that I&#8217;ve always been a back-end developer, and when I have had to do web front end stuff, it&#8217;s usually been something deliberately simple, for the lowest common denominator of browsers. So it&#8217;s only been in the last couple weeks at $new_gig that I&#8217;ve had to sit down [...]]]></description>
			<content:encoded><![CDATA[<p>In my defense, let me point out that I&#8217;ve always been a back-end developer, and when I have had to do web front end stuff, it&#8217;s usually been something deliberately simple, for the lowest common denominator of browsers. So it&#8217;s only been in the last couple weeks at <code>$new_gig</code> that I&#8217;ve had to sit down and really understand all the clever stuff you can do with CSS layout.</p>
<p>It seems like it should be pretty straightforward: you basically have block, inline, float, and relative and absolute positioning; they can have fixed or percentage widths. But these sometimes interact in surprising ways, and I&#8217;d find that a common-sense design goal would be difficult-to-impossible to implement. The <a href="http://www.w3.org/TR/CSS2/visuren.html" title="official W3 formatting model doc" target="_blank">official W3 formatting model doc</a> is thorough but it&#8217;s a lot to wade through. It also documents each feature in isolation, without much explanation of how they interact.</p>
<p>So I worked up a kind of <a href="http://bluegraybox.com/div_placement.html" title="cheat sheet" target="_blank">cheat sheet</a>, that shows what happens when you throw all this crap together on the same page. To really get the most out of it, you should bring up Firebug or the Chrome inspector, and play around with the width, position and other style settings.</p>
<p>Let me know if it&#8217;s useful, or what I&#8217;m missing.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2012/03/25/remedial-css/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How Steve Jobs Got Me to Buy an Android</title>
		<link>http://www.bluegraybox.com/blog/2012/03/03/how-steve-jobs-got-me-to-buy-an-android/</link>
		<comments>http://www.bluegraybox.com/blog/2012/03/03/how-steve-jobs-got-me-to-buy-an-android/#comments</comments>
		<pubDate>Sat, 03 Mar 2012 19:07:42 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[philosophy]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=232</guid>
		<description><![CDATA[Back around Christmas, I saw an old video of Steve Jobs at the &#8217;97 Apple World-Wide Developer Conference. This was just as he was coming back to Apple, so he&#8217;s talking a lot about their new direction. Part of that came out of his experience at Next. Next was all unix under the hood (or [...]]]></description>
			<content:encoded><![CDATA[<p>Back around Christmas, I saw an old <a href="http://www.youtube.com/watch?v=GnO7D5UaDig">video of Steve Jobs at the &#8217;97 Apple World-Wide Developer Conference</a>. This was just as he was coming back to Apple, so he&#8217;s talking a lot about their new direction. Part of that came out of his experience at Next. Next was all unix under the hood (or unix-y), so their systems were networked in a way that Macs and PCs just weren&#8217;t at that point. Jobs is talking about how all of his stuff just lives on the network: His machine at work, his machine at home, and any corporate machine he logs into all have equally easy access to the same files. He doesn&#8217;t have to worry about backup and recovery; that&#8217;s all taken care of by sysadmins. This is back when you&#8217;d usually just copy a few critical files onto a floppy disk and hope your hard drive didn&#8217;t crash. He was living in the future, and his vision was to simply make that available to everyone. As Willam Gibson pointed out, &#8220;The future is already here; it&#8217;s just not evenly distributed.&#8221;</p>
<p>It struck me while I was watching this that back then, I was also living in the future. I was working at an ISP, so I had network access that was years ahead of its time. Back when 28.8K dialup was the norm, my work computer had a 10MB connection straight into the Internet backbone. Even more importantly, it was always on; it was just <em>there</em>. Individual machines were expendable; it was the network and the data that mattered. That changed the whole way I worked with computers.</p>
<p>It also changed the way we played and socialized. We played net-Quake with imperceptible lag. We had a private mp3 server with thousands of tracks before most people knew what mp3s were. We chatted on IRC all day with our co-workers and similarly wired sysadmin buddies around the country (or world in a few cases). We could drag in a scratch-build Linux box and set it up as a public server: Give our friends email accounts and web sites and bring the future a little closer for them.</p>
<p>To be honest, I was never one of the ringleaders, the early adopters. I didn&#8217;t rush out to buy the latest gadget. I spent a fair amount of time tinkering with my home Linux machine, but I wasn&#8217;t really pushing the envelope. But I spent all my time around folks who were, and I was conscious that I was getting a sneak preview of the future. They were living and working the way that everyone would once all this tech got cheaper and easier to use.</p>
<p>In the years since, I haven&#8217;t really been in that sort of environment, and without it for balance, my skeptical tendencies took over. Or maybe I just got tired of having to rebuild my kernel to get sound working. In any case, I pretty much stopped tinkering and focused on The Simplest Thing that Works. I started buying Macs and their attendant accessories: The iPod that auto-synched my music, and the Time Capsule that did automated backups.</p>
<p>I didn&#8217;t get an iPhone, though. I had a pre-paid cell phone that you could buy at 7-11 for $20, and cost me $80 a <em>year</em>. The iPhone was nearly that much a month. It had a lot of nice-to-haves, but nothing that justified the cost. It&#8217;s actually exciting to me that perfectly serviceable technology is that cheap. Ditto for computers: As long as you&#8217;re not gaming, a $500 machine is plenty. (I&#8217;m writing this on a sub-$300 netbook. It&#8217;s text. How hard is that?)</p>
<p>Listening to Steve Jobs reminded me of that feeling of living in the future. It also struck me that that&#8217;s supposed to be part of my job &#8211; maybe not my day job, but some bigger social role as someone who understands machines and isn&#8217;t afraid to tinker with them. I shouldn&#8217;t be just a technology consumer. I should be bushwhacking my way into the future, cobbling together half-working prototypes to see what it&#8217;s like to live with them; figuring out how the tech works and how to polish it up and make it usable for everyone else. I&#8217;m no visionary, but there&#8217;s a lot of work to be done out on the frontier, just making things a little more civilized.</p>
<p>The catch is that that&#8217;s not what Apple is about. They build sleek, elegant, easy to use gifts from the Future. It all Just Works. That&#8217;s great, and I seriously applaud them, but you don&#8217;t learn much from a working machine. If you want to do some exploring on your own, and maybe figure out something useful that hasn&#8217;t already been productized &#8211; or to just pop the hood and get a better understanding of what makes this thing tick &#8211; you need something a little more open. You even kinda want something that doesn&#8217;t work <em>quite</em> right, something that&#8217;ll bug you to go in and fix it yourself. That&#8217;s just not how Apple wants you to relate to their technology.</p>
<p>So in the end, I got an Android phone. I can&#8217;t justify it as a phone, but I was able to rationalize it as a development machine. It&#8217;s got its own restrictions, and I&#8217;ve been too anxious to root it, but I&#8217;m still more comfortable with it than I would be with an iPhone. It plays well with Linux. I can develop in Eclipse on any platform; I&#8217;m not locked into the Mac/Xcode tools. Maybe what it comes down to is that I trust developer communities more than any single corporation.</p>
<p>I went through the standard Android programming tutorial, where you build a little notepad app. Then I hacked around on it a bit: added tagging, tweaked the page flow. It&#8217;s still rough around the edges, but it works. There are a few features I&#8217;d like to add, but I can do that. That&#8217;s the important thing. It&#8217;s not awesome, but it&#8217;s mine. I can keep sanding away at the things that bug me, and it may eventually become pretty awesome. It&#8217;ll be tailored to the way I use it. It&#8217;ll do the things I need it to, and it won&#8217;t be cluttered with features I don&#8217;t want. Nobody will be trying to get me to upgrade to the pay version.</p>
<p>In a very real way, I also need to do this to survive as a programmer. I need to keep that love of tinkering alive. If it&#8217;s just a day job, I don&#8217;t see how I can keep doing it for another twenty or thirty years. It needs to be more than that. I have to find that passion and the sense of something bigger. I need to care about it.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2012/03/03/how-steve-jobs-got-me-to-buy-an-android/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Crafty Erlang</title>
		<link>http://www.bluegraybox.com/blog/2011/12/06/crafty-erlang/</link>
		<comments>http://www.bluegraybox.com/blog/2011/12/06/crafty-erlang/#comments</comments>
		<pubDate>Wed, 07 Dec 2011 01:43:16 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[talks]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=202</guid>
		<description><![CDATA[An elegant language for small projects This is based on the talk I gave at ErlangDC. The common perception of Erlang is that it&#8217;s a good language for big projects where you need massive scalability, distribution, fault-tolerance and so on. The language itself is weird and ugly, and it&#8217;s got a lot of annoying restrictions, [...]]]></description>
			<content:encoded><![CDATA[<h3>An elegant language for small projects</h3>
<p><em>This is based on the talk I gave at <a href="http://erlangdc.com/">ErlangDC</a></em>.</p>
<p>The common perception of Erlang is that it&#8217;s a good language for big projects where you need massive scalability, distribution, fault-tolerance and so on.  The language itself is weird and ugly, and it&#8217;s got a lot of annoying restrictions, but that&#8217;s what you have to put up with to get the good stuff.  I want to challenge both sides of that, and say that Erlang is also a great language for small projects &#8211; even little scripts &#8211; and that it&#8217;s really beautiful once you understand it.  It just has its own way of doing things.  And a key here is that it does have A Way of Doing Things; There are design patterns and programming idioms that you can follow.  It&#8217;s not rocket science; you can learn it.  So what I&#8217;m going to do here is show you some of those patterns and idioms, walk through a couple of simple programs, and hopefully give you what you need to know (and a bit of a nudge) to get started having fun with Erlang.</p>
<h2>Synergistic Weirdness</h2>
<p>Erlang has what I&#8217;ve come to think of as &#8220;synergistic weirdness&#8221;.  When I was first starting out with Erlang, there were all these things that struck me as weird.  Like, I want to write a <code>for</code> loop that increments a counter, and Erlang&#8217;s like, &#8220;Nope. No can do.&#8221; You can&#8217;t increment a counter because variables are immutable, and there&#8217;s no <code>for</code> loop.  There are no loop controls, period.  And there are no classes or objects, while we&#8217;re at it.  How do I <em>do</em> anything in this language?</p>
<p>Then there&#8217;s all this weird extra stuff.  There&#8217;s efficient tail recursion.  Ok, fine, but how often do I write recursive functions? About never.  There&#8217;s pattern matching and guard clauses.  That&#8217;s kinda cool, but I&#8217;m still not sure how much I&#8217;d use it.  All of the inter-process communication (IPC) stuff &#8211; process spawning and message passing &#8211; is definitely cool if you&#8217;re writing a big concurrent app, but otherwise?  All this stuff is fine, but how often would you actually use any of it?  The answer is, &#8220;All the time.&#8221; All these isolated bits of weirdness combine to something very elegant.  For example, let&#8217;s take a look at&#8230;</p>
<h2>Recursion</h2>
<p>You don&#8217;t use recursion much in OO languages because (a) you rarely need to, and (b) it&#8217;s scary &#8211; you have to be careful about how you update your data structures.  Recursive methods tend to have big warning comments, and nobody dares touch them.  And this is self-reinforcing: Since it&#8217;s not used much, it remains this scary, poorly-understood concept.</p>
<p>In Erlang, recursion takes the place of all of the looping constructs and iterators that you would use in an object-oriented (OO) language.  Because it&#8217;s used for everything, there are well-established patterns for writing recursive functions.  Since you use it all the time, you get used to it.  Erlang&#8217;s immutable variables actually simplify recursion, because they force you to be clear about how you&#8217;re changing your data at each step of the recursion.  Pattern matching and guard expressions make recursion really powerful and expressive, because they let you break out the stages of a recursion in a very declarative way.  Let&#8217;s look at the basics of recursion in Erlang with a very simple example: munging a list of data.</p>
<p>Like a story, a recursive function has a beginning, a middle, and an end.  The beginning and end are usually the easiest parts, so let&#8217;s tackle those first.  The beginning of a recursion is just a function that takes the input, sets up any initial state, ouput accumulators, etc., and recurses.  In this case, we take an Input list and set up an empty output list.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="co1">%% beginning</span>
    <span class="re3">func</span><span class="br0">&#40;</span><span class="re5">Input</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re5">Output</span> <span class="sy3">=</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="sy1">,</span>
        <span class="re3">func</span><span class="br0">&#40;</span><span class="re5">Input</span><span class="sy1">,</span> <span class="re5">Output</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>The end stage is also easy to define.  We pattern-match on an empty input list, and return our output list.  (I&#8217;ll get to why we reverse the output list in a minute.)</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="co1">%% end</span>
    <span class="re3">func</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Output</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="kw5">lists</span>:<span class="re3">reverse</span><span class="br0">&#40;</span><span class="re5">Output</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>The middle stage defines what we do with any single element in the list, and how we move on to the next one.  Here, we just pop the first element off the input list, munge it to create a new element, push that onto the output list, and recurse with the newly-diminished input and newly-extended output.  (And note that we add our new element at the beginning of the list, rather than the end.)</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="co1">%% middle</span>
    <span class="re3">func</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">First</span> | <span class="re5">Rest</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Output</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re5">NewFirst</span> <span class="sy3">=</span> <span class="re3">munge</span><span class="br0">&#40;</span><span class="re5">First</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="re3">func</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">NewFirst</span> | <span class="re5">Output</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">;</span></pre></div></div></div></div></div></div></div>


<p>That&#8217;s all there is to the basics of recursion.  You may have multiple inputs and outputs, and there could be multiple middle and end functions to handle different cases (and we&#8217;ll see a more interesting example in a minute), but the basic pattern is the same.</p>
<h2>Digression: Backwards Lists</h2>
<p>Why do build our output list backwards?  Why don&#8217;t we just add new elements to the end, and not have to reverse it when we&#8217;re done?  This was one of those little Erlang weirdnesses that really bugged me until I understood it.  The key is that lists in Erlang are not just arrays; they&#8217;re linked lists, and critically, <em>singly</em>-linked lists.  So when you create a list like</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re5">Foo</span> <span class="sy3">=</span> <span class="br0">&#91;</span>cat<span class="sy1">,</span> dog<span class="br0">&#93;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>You get a logical list structure that looks like</p>
<pre>
    Foo
    |
    cat - dog
</pre>
<p>If you create a new list by prepending an element to Foo,</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re5">Bar</span> <span class="sy3">=</span> <span class="br0">&#91;</span>monkey | <span class="re5">Foo</span><span class="br0">&#93;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>The logical structure now looks like</p>
<pre>
    Bar      Foo
    |        |
    monkey - cat - dog
</pre>
<p>And if you create another new list by prepending more elements to Foo,</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re5">Baz</span> <span class="sy3">=</span> <span class="br0">&#91;</span>elephant<span class="sy1">,</span> tiger | <span class="re5">Foo</span><span class="br0">&#93;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>The logical structure will now look like</p>
<pre>
    Baz       Bar      Foo
    |         |        |
    |         monkey - cat - dog
    |                 /
    elephant - tiger /
</pre>
<p>So the new lists are efficiently re-using Foo&#8217;s elements, but this only works because Foo itself is immutable.  If you could add elements onto the end of Foo, or modify its elements in place, you&#8217;d see that change in every list built off of Foo.</p>
<h2>Back to recursion: Bowling Game</h2>
<p>A more interesting example of recursion is the bowling game.  This is a standard programming exercise &#8211; write a program to calculate the score for bowling.  It&#8217;s fairly simple, but not trivial.  Your input is a list of rolls (number of pins knocked down), and your output is just a number, a final score.  There&#8217;s also this concept of frames you have to keep track of; the game has a fixed number of frames, but the number of rolls may vary.  The score for a frame may depend on rolls you made in other frames.  Writing this in an OO language, and trying to break this functionality cleanly out into classes, can be tricky.  In Erlang, we&#8217;re just going to define a recursive function that takes a list of rolls and returns a number.</p>
<p>Again, we start by defining the beginning of the recursion.  We get a list of rolls, set our initial frame to 1 and score to 0, and recurse.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="co1">%% Beginning: score/1 -&gt; score/3</span>
    <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re5">Frame</span> <span class="sy3">=</span> <span class="nu0">1</span><span class="sy1">,</span>
        <span class="re5">Score</span> <span class="sy3">=</span> <span class="nu0">0</span><span class="sy1">,</span>
        <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>The end is even simpler.  There are ten frames in a game, so when our frame count gets to 11, we&#8217;re done.  Just return our score.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="co1">%% End</span>
    <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">_Rolls</span><span class="sy1">,</span> <span class="nu0">11</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Score</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>For the middle, we&#8217;re going to start with the normal case for scoring a frame, ignoring strikes and spares.  Here, we just pop the next two rolls off the input, add them to our total score, and recurse with an incremented frame.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="co1">%% Middle</span>
    <span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Roll1</span><span class="sy1">,</span> <span class="re5">Roll2</span> | <span class="re5">Rest</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re5">NewScore</span> <span class="sy3">=</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="re5">Roll1</span> <span class="sy3">+</span> <span class="re5">Roll2</span><span class="sy1">,</span>
        <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">NewScore</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>Now we need to deal with the strike and spare cases.  Erlang&#8217;s pattern matching lets us do this very cleanly.  For strikes, define a score function (in proper terms, a clause of the score function) that matches when the first roll is a 10.  For spares, we use a guard expression to match only when the next two rolls add up to 10.  In both cases, we need to look at rolls in following frames (2 for a strike, 1 for a spare) and add those to our score.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="co1">%% Strike</span>
    <span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="nu0">10</span> | <span class="re5">Rest</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="br0">&#91;</span><span class="re5">Bonus1</span><span class="sy1">,</span> <span class="re5">Bonus2</span> | <span class="re5">_</span><span class="br0">&#93;</span> <span class="sy3">=</span> <span class="re5">Rest</span><span class="sy1">,</span>
        <span class="re5">NewScore</span> <span class="sy3">=</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="nu0">10</span> <span class="sy3">+</span> <span class="re5">Bonus1</span> <span class="sy3">+</span> <span class="re5">Bonus2</span><span class="sy1">,</span>
        <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">NewScore</span><span class="br0">&#41;</span><span class="sy1">;</span>
&nbsp;
    <span class="co1">%% Spare</span>
    <span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Roll1</span><span class="sy1">,</span> <span class="re5">Roll2</span> | <span class="re5">Rest</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="re5">Roll1</span> <span class="sy3">+</span> <span class="re5">Roll2</span> <span class="sy3">==</span> <span class="nu0">10</span> <span class="sy1">-&gt;</span>
        <span class="br0">&#91;</span><span class="re5">Bonus1</span> | <span class="re5">_</span><span class="br0">&#93;</span> <span class="sy3">=</span> <span class="re5">Rest</span><span class="sy1">,</span>
        <span class="re5">NewScore</span> <span class="sy3">=</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="nu0">10</span> <span class="sy3">+</span> <span class="re5">Bonus1</span><span class="sy1">,</span>
        <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">NewScore</span><span class="br0">&#41;</span><span class="sy1">;</span></pre></div></div></div></div></div></div></div>


<p>That&#8217;s pretty much it for the scoring rules.  We still need to handle incomplete frames, so by the time we&#8217;re done with that, the whole thing looks like this.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">0</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
    <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">_Rolls</span><span class="sy1">,</span> <span class="nu0">11</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Score</span><span class="sy1">;</span>
&nbsp;
    <span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="nu0">10</span> | <span class="re5">Rest</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="nu0">10</span> <span class="sy3">+</span> <span class="re3">strike_bonus</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy1">;</span>
&nbsp;
    <span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Roll1</span><span class="sy1">,</span> <span class="re5">Roll2</span> | <span class="re5">Rest</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="re5">Roll1</span> <span class="sy3">+</span> <span class="re5">Roll2</span> <span class="sy3">==</span> <span class="nu0">10</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="nu0">10</span> <span class="sy3">+</span> <span class="re3">spare_bonus</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy1">;</span>
&nbsp;
    <span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Roll1</span><span class="sy1">,</span> <span class="re5">Roll2</span> | <span class="re5">Rest</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="re5">Roll1</span> <span class="sy3">+</span> <span class="re5">Roll2</span><span class="br0">&#41;</span><span class="sy1">;</span>
&nbsp;
    <span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Roll1</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">_Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="re5">Roll1</span><span class="sy1">;</span>
    <span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">_Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Score</span><span class="sy1">.</span>
&nbsp;
&nbsp;
    <span class="re3">spare_bonus</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="nu0">0</span><span class="sy1">;</span>
    <span class="re3">spare_bonus</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Bonus1</span> | <span class="re5">_Rest</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Bonus1</span><span class="sy1">.</span>
&nbsp;
    <span class="re3">strike_bonus</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="nu0">0</span><span class="sy1">;</span>
    <span class="re3">strike_bonus</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Only</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Only</span><span class="sy1">;</span>
    <span class="re3">strike_bonus</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Bonus1</span><span class="sy1">,</span> <span class="re5">Bonus2</span> | <span class="re5">_Rest</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Bonus1</span> <span class="sy3">+</span> <span class="re5">Bonus2</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>Ok, that&#8217;s an algorithm.  To turn it into a usable application, we need to put some sort of interface in front of it, and we need some way to store our data as the game progresses.  The simplest interface is the command line, so let&#8217;s start with that.</p>
<h2>Sketching the CLI</h2>
<p>We can start sketching out the command-line interface in the Erlang shell.  <code>io:get_line/1</code> prompts the user and reads a line from standard input.  We can enter a player name and a roll.  <code>string:tokens/2</code> will split that into separate strings.  <code>string:to_integer/1</code> will convert the roll to a number we can work with.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re5">Eshell</span> <span class="re5">V5</span><span class="sy1">.</span>8<span class="sy1">.</span>4  <span class="br0">&#40;</span>abort with ^G<span class="br0">&#41;</span>
    <span class="nu0">1</span><span class="sy3">&gt;</span> <span class="re5">Line</span> <span class="sy3">=</span> <span class="kw5">io</span>:<span class="kw3">get</span>_<span class="re3">line</span><span class="br0">&#40;</span><span class="st0">&quot;Next&gt; &quot;</span><span class="br0">&#41;</span><span class="sy1">.</span>
    <span class="re5">Next</span><span class="sy3">&gt;</span> colin <span class="nu0">4</span>
    <span class="st0">&quot;colin 4<span class="es0">\n</span>&quot;</span>
    <span class="nu0">2</span><span class="sy3">&gt;</span> <span class="br0">&#91;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">RollText</span><span class="br0">&#93;</span> <span class="sy3">=</span> <span class="kw5">string</span>:<span class="re3">tokens</span><span class="br0">&#40;</span><span class="re5">Line</span><span class="sy1">,</span> <span class="st0">&quot; <span class="es0">\t</span><span class="es0">\n</span>&quot;</span><span class="br0">&#41;</span><span class="sy1">.</span>
    <span class="br0">&#91;</span><span class="st0">&quot;colin&quot;</span><span class="sy1">,</span><span class="st0">&quot;4&quot;</span><span class="br0">&#93;</span>
    <span class="nu0">3</span><span class="sy3">&gt;</span> <span class="br0">&#123;</span><span class="re5">Roll</span><span class="sy1">,</span> <span class="re5">_</span><span class="br0">&#125;</span> <span class="sy3">=</span> <span class="kw5">string</span>:<span class="re3">to_integer</span><span class="br0">&#40;</span><span class="re5">RollText</span><span class="br0">&#41;</span><span class="sy1">.</span>
    <span class="br0">&#123;</span><span class="nu0">4</span><span class="sy1">,</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#125;</span></pre></div></div></div></div></div></div></div>


<p>Now we need somewhere to store it.  A dictionary will let us keep track of multiple players.  <code>dict:new/0</code> creates it.  <code>dict:append/3</code> takes a key-value pair and adds the value to the list of values for that key.  Note that it does <em>not</em> replace the key&#8217;s value (<code>dict:store/3</code> does that).  <code>dict:find/2</code> returns the value for a key, which in this case is a list of rolls.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="nu0">4</span><span class="sy3">&gt;</span> <span class="re5">GameData</span> <span class="sy3">=</span> <span class="kw5">dict</span>:<span class="re3">new</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy1">.</span>
    <span class="br0">&#123;</span>dict<span class="sy1">,</span><span class="nu0">0</span><span class="sy1">,...</span>
    <span class="nu0">5</span><span class="sy3">&gt;</span> <span class="re5">NewGameData</span> <span class="sy3">=</span> <span class="kw5">dict</span>:<span class="re3">append</span><span class="br0">&#40;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">Roll</span><span class="sy1">,</span> <span class="re5">GameData</span><span class="br0">&#41;</span><span class="sy1">.</span>
    <span class="br0">&#123;</span>dict<span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,...</span>
    <span class="nu0">6</span><span class="sy3">&gt;</span> <span class="br0">&#123;</span>ok<span class="sy1">,</span> <span class="re5">Rolls</span><span class="br0">&#125;</span> <span class="sy3">=</span> <span class="kw5">dict</span>:<span class="re3">find</span><span class="br0">&#40;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">NewGameData</span><span class="br0">&#41;</span><span class="sy1">.</span>
    <span class="br0">&#123;</span>ok<span class="sy1">,</span><span class="br0">&#91;</span><span class="nu0">4</span><span class="br0">&#93;</span><span class="br0">&#125;</span></pre></div></div></div></div></div></div></div>


<p>Finally, we pass the list of rolls to our scoring function (not very interesting yet).</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="nu0">7</span><span class="sy3">&gt;</span> <span class="re5">Score</span> <span class="sy3">=</span> bowling_game:<span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="br0">&#41;</span><span class="sy1">.</span>
    <span class="nu0">4</span></pre></div></div></div></div></div></div></div>


<p>Normally now, you&#8217;d throw a while loop arounds this stuff, but this is Erlang, so we wrap it in a recursive function.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re3">loop</span><span class="br0">&#40;</span><span class="re5">GameData</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re5">Line</span> <span class="sy3">=</span> <span class="kw5">io</span>:<span class="kw3">get</span>_<span class="re3">line</span><span class="br0">&#40;</span><span class="st0">&quot;Next&gt; &quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="br0">&#91;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">RollText</span><span class="br0">&#93;</span> <span class="sy3">=</span> <span class="kw5">string</span>:<span class="re3">tokens</span><span class="br0">&#40;</span><span class="re5">Line</span><span class="sy1">,</span> <span class="st0">&quot; <span class="es0">\t</span><span class="es0">\n</span>&quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="br0">&#123;</span><span class="re5">Roll</span><span class="sy1">,</span> <span class="re5">_</span><span class="br0">&#125;</span> <span class="sy3">=</span> <span class="kw5">string</span>:<span class="re3">to_integer</span><span class="br0">&#40;</span><span class="re5">RollText</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="re5">NewGameData</span> <span class="sy3">=</span> <span class="kw5">dict</span>:<span class="re3">append</span><span class="br0">&#40;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">Roll</span><span class="sy1">,</span> <span class="re5">GameData</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="br0">&#123;</span>ok<span class="sy1">,</span> <span class="re5">Rolls</span><span class="br0">&#125;</span> <span class="sy3">=</span> <span class="kw5">dict</span>:<span class="re3">find</span><span class="br0">&#40;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">NewGameData</span><span class="br0">&#41;</span><span class="sy1">.</span>
        <span class="re5">Score</span> <span class="sy3">=</span> bowling_game:<span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="br0">&#41;</span><span class="sy1">.</span>
        <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;New score for ~s: ~p~n&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="re3">loop</span><span class="br0">&#40;</span><span class="re5">NewGameData</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>This is the middle of a recursion, so we need to add a beginning.  That&#8217;s simple enough &#8211; invoke loop with a new dictionary.  We could put this in a module and call it from the Erlang shell, but it&#8217;s easier if we wrap it in an Escript.  (If you&#8217;re not familiar with Escript, it lets you run Erlang code as a script, the way you would with Perl, Python, Ruby, or whatever.  You don&#8217;t even need to define a module, just a main/1 function that takes the command-line parameters as a list of strings.)</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    #<span class="sy3">!/</span>usr<span class="sy3">/</span>local<span class="sy3">/</span>bin<span class="sy3">/</span>escript
    #
    # scorekeeper<span class="sy1">.</span>erl 
&nbsp;
    <span class="sy3">-</span><span class="re2">import</span><span class="br0">&#40;</span>bowling_game<span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
    <span class="re3">main</span><span class="br0">&#40;</span><span class="re5">_</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re3">loop</span><span class="br0">&#40;</span><span class="kw5">dict</span>:<span class="re3">new</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
    <span class="re3">loop</span><span class="br0">&#40;</span><span class="re5">GameData</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="sy1">...</span></pre></div></div></div></div></div></div></div>


<p>That&#8217;s the beginning and middle of the recursion.  We&#8217;re not going to bother defining an end &#8211; you can just <code>ctrl-c</code> out of the loop.  Here&#8217;s a sample of what we get when we run it:</p>
<pre>
    $ ./scorekeeper.erl
    Next> colin 3
    New score for colin: 3
    Next> colin 4
    New score for colin: 7
    Next> colin 10
    New score for colin: 17
    Next> colin 3
    New score for colin: 23
    Next>
</pre>
<p>(Note that it correctly handles the strike!)</p>
<h2>Webify!</h2>
<p>So that&#8217;s a command-line interface.  Now let&#8217;s turn it into a simple web app.  We&#8217;re going to have a single-page rich web client that will send Ajax requests to a REST service, and use Javascript to update its display.  The REST service will have pretty much the same API: It&#8217;ll take a player and a roll, and return the player&#8217;s new score.  We&#8217;ll use jQuery on the front end and Spooky on the back end.  Spooky is a very simple web application framework, much Ruby&#8217;s Sinatra, if you&#8217;re familiar with that.</p>
<p>The other change here is that we&#8217;ll have to deal with concurrency.  The command line is inherently sequential, but web services are inherently concurrent.  We&#8217;ll need to create a mini-service which will control access to our bowling data.</p>
<h2>Bowling Service</h2>
<p>A bit of a digression: I&#8217;ve seen it argued that Erlang is one of the most truly object-oriented languages.  The original theory behind object-oriented design was that objects would be like living things that talk to each other.  Rather than having a dumb data structure that you manipulate, you would send messages to an object, requesting that it give you information, update its state, perform a calculation, or whatever.  You would have an interface to talk to it, but you couldn&#8217;t know or manipulate its state directly.  Most OO languages implement this by wrapping a dumb data structure in a bunch of smart (or not so smart) accessor methods &#8211; usually optional.  What Erlang does is create processes to manage access to data.  Rather than data having associated methods, Erlang has processes that own data.  The only way to get to the data is to talk to the process, and that&#8217;s where IPC comes in.</p>
<p>So what does that look like?  Well, remember the command-line loop?  Let&#8217;s break that up into sections.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re3">loop</span><span class="br0">&#40;</span><span class="re5">GameData</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="co1">%% receive input</span>
        <span class="re5">Line</span> <span class="sy3">=</span> <span class="kw5">io</span>:<span class="kw3">get</span>_<span class="re3">line</span><span class="br0">&#40;</span><span class="st0">&quot;Next&gt; &quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="br0">&#91;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">RollText</span><span class="br0">&#93;</span> <span class="sy3">=</span> <span class="kw5">string</span>:<span class="re3">tokens</span><span class="br0">&#40;</span><span class="re5">Line</span><span class="sy1">,</span> <span class="st0">&quot; <span class="es0">\t</span><span class="es0">\n</span>&quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
&nbsp;
        <span class="co1">%% process input</span>
        <span class="br0">&#123;</span><span class="re5">Roll</span><span class="sy1">,</span> <span class="re5">_</span><span class="br0">&#125;</span> <span class="sy3">=</span> <span class="kw5">string</span>:<span class="re3">to_integer</span><span class="br0">&#40;</span><span class="re5">RollText</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="re5">NewGameData</span> <span class="sy3">=</span> <span class="kw5">dict</span>:<span class="re3">append</span><span class="br0">&#40;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">Roll</span><span class="sy1">,</span> <span class="re5">GameData</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="br0">&#123;</span>ok<span class="sy1">,</span> <span class="re5">Rolls</span><span class="br0">&#125;</span> <span class="sy3">=</span> <span class="kw5">dict</span>:<span class="re3">find</span><span class="br0">&#40;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">NewGameData</span><span class="br0">&#41;</span><span class="sy1">.</span>
        <span class="re5">Score</span> <span class="sy3">=</span> bowling_game:<span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
        <span class="co1">%% print new score</span>
        <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;New score for ~s: ~p~n&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
&nbsp;
        <span class="co1">%% recurse with new state</span>
        <span class="re3">loop</span><span class="br0">&#40;</span><span class="re5">NewGameData</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>Now here&#8217;s the message-handling loop.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re3">loop</span><span class="br0">&#40;</span><span class="re5">GameData</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="co1">%% receive input</span>
        <span class="kw1">receive</span> <span class="br0">&#123;</span><span class="re5">From</span><span class="sy1">,</span> <span class="br0">&#123;</span>append<span class="sy1">,</span> <span class="re5">Player</span><span class="sy1">,</span> <span class="re5">RollText</span><span class="br0">&#125;</span><span class="br0">&#125;</span> <span class="sy1">-&gt;</span>
&nbsp;
            <span class="co1">%% process input - this is the same</span>
            <span class="br0">&#123;</span><span class="re5">Roll</span><span class="sy1">,</span> <span class="re5">_</span><span class="br0">&#125;</span> <span class="sy3">=</span> <span class="kw5">string</span>:<span class="re3">to_integer</span><span class="br0">&#40;</span><span class="re5">RollText</span><span class="br0">&#41;</span><span class="sy1">,</span>
            <span class="re5">NewGameData</span> <span class="sy3">=</span> <span class="kw5">dict</span>:<span class="re3">append</span><span class="br0">&#40;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">Roll</span><span class="sy1">,</span> <span class="re5">GameData</span><span class="br0">&#41;</span><span class="sy1">,</span>
            <span class="br0">&#123;</span>ok<span class="sy1">,</span> <span class="re5">Rolls</span><span class="br0">&#125;</span> <span class="sy3">=</span> <span class="kw5">dict</span>:<span class="re3">find</span><span class="br0">&#40;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">NewGameData</span><span class="br0">&#41;</span><span class="sy1">,</span>
            <span class="re5">Score</span> <span class="sy3">=</span> bowling_game:<span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="br0">&#41;</span><span class="sy1">,</span>
&nbsp;
            <span class="co1">%% respond with new score</span>
            <span class="re5">From</span> <span class="sy3">!</span> <span class="re5">Score</span><span class="sy1">,</span>
&nbsp;
            <span class="co1">%% recurse with new state</span>
            <span class="re3">loop</span><span class="br0">&#40;</span><span class="re5">NewGameData</span><span class="br0">&#41;</span>
        <span class="kw1">end</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>That&#8217;s it.  Instead of waiting for command-line input, we wait for a message.  Instead of printing our response, we send a message back.  GameData is a local variable to loop/1.  Nobody else can see it; there&#8217;s only one process that can change it.</p>
<p>Again, that&#8217;s the middle; how do we start this recursion?  As with the CLI, we need a beginning function that creates the dictionary.  The difference here is that instead of calling <code>loop/1</code> directly, we wrap it in a closure and spawn it off as a new process.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re3">init</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re5">Data</span> <span class="sy3">=</span> <span class="kw5">dict</span>:<span class="re3">new</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="re5">Start</span> <span class="sy3">=</span> <span class="kw1">fun</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re3">loop</span><span class="br0">&#40;</span><span class="re5">Data</span><span class="br0">&#41;</span> <span class="kw1">end</span><span class="sy1">,</span>
        <span class="kw3">spawn</span><span class="br0">&#40;</span><span class="re5">Start</span><span class="br0">&#41;</span><span class="sy1">.</span>  <span class="co1">% returns process id</span></pre></div></div></div></div></div></div></div>


<p>For convenience, we&#8217;ll add an <code>append/3</code> function for our clients.  It hides the message format, and makes the asynchronous request synchronous.  This makes it look a lot like we&#8217;re creating an object and updating it.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re3">append</span><span class="br0">&#40;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">RollText</span><span class="sy1">,</span> <span class="re5">Pid</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re5">Pid</span> <span class="sy3">!</span> <span class="br0">&#123;</span><span class="kw3">self</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy1">,</span> <span class="br0">&#123;</span>append<span class="sy1">,</span> <span class="re5">Player</span><span class="sy1">,</span> <span class="re5">RollText</span><span class="br0">&#125;</span><span class="br0">&#125;</span><span class="sy1">,</span>
        <span class="kw1">receive</span> <span class="re5">Resp</span> <span class="sy1">-&gt;</span> <span class="re5">Resp</span> <span class="kw1">end</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<h2>REST API</h2>
<p>Now that our back-end service is done, we move to the REST interface.  Let&#8217;s keep this simple.  Let&#8217;s just take a GET request &#8211; a straight URL &#8211; something like this:</p>
<pre>

http://localhost:8000/add/Player/Roll
</pre>
<p>So for example:</p>
<pre>

http://localhost:8000/add/colin/4
</pre>
<p>Yes, I know this isn&#8217;t entirely kosher for a REST API &#8211; we shouldn&#8217;t be modifying state with a GET &#8211; but we&#8217;re just doing the simplest thing that works here.</p>
<h2>Spooky App</h2>
<p>To create a Spooky web application, we just need to create a module that has the &#8220;spooky&#8221; behavior and exports Spooky&#8217;s callback functions.  To use our bowling module, we&#8217;ll need to import that.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="sy3">-</span><span class="re2">module</span><span class="br0">&#40;</span>bowling_web<span class="br0">&#41;</span><span class="sy1">.</span>
    <span class="sy3">-</span><span class="re2">behaviour</span><span class="br0">&#40;</span>spooky<span class="br0">&#41;</span><span class="sy1">.</span>
    <span class="sy3">-</span><span class="re2">export</span><span class="br0">&#40;</span><span class="br0">&#91;</span>init<span class="sy3">/</span><span class="nu0">1</span><span class="sy1">,</span> <span class="kw3">get</span><span class="sy3">/</span><span class="nu0">2</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">.</span>  <span class="co1">% Spooky API</span>
    <span class="sy3">-</span><span class="re2">import</span><span class="br0">&#40;</span>bowling_service<span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p><code>init/1</code> is called once, when the server starts up.  It starts up the bowling service we just defined, and registers its process id as <code>bowl_svc</code>.  That lets us refer to it by name, so we don&#8217;t have to pass the PID around somehow.  This would be especially useful in a situation where the service might be restarted and get a new process id.  Other processes could continue to use it without needing to know the new PID.  The return value configures Spooky to start up on port 8000.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re3">init</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">-&gt;</span>
        <span class="kw3">register</span><span class="br0">&#40;</span>bowl_svc<span class="sy1">,</span> bowling_service:<span class="re3">init</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="br0">&#91;</span><span class="br0">&#123;</span>port<span class="sy1">,</span> <span class="nu0">8000</span><span class="br0">&#125;</span><span class="br0">&#93;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p><code>get/2</code> is called to handle each HTTP GET request.  Spooky splits up the URL&#8217;s resource path into a list of strings.  That makes it easy to match on patterns, like so.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">     <span class="co1">%% REST handler</span>
    <span class="kw3">get</span><span class="br0">&#40;</span><span class="re5">_Req</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="st0">&quot;add&quot;</span><span class="sy1">,</span> <span class="re5">Player</span><span class="sy1">,</span> <span class="re5">RollText</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">-&gt;</span>
        <span class="re5">Score</span> <span class="sy3">=</span> bowling_service:<span class="re3">append</span><span class="br0">&#40;</span><span class="re5">Player</span><span class="sy1">,</span> <span class="re5">RollText</span><span class="sy1">,</span> bowl_svc<span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="br0">&#123;</span><span class="nu0">200</span><span class="sy1">,</span> <span class="kw5">io_lib</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;~p&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">Score</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="br0">&#125;</span><span class="sy1">;</span></pre></div></div></div></div></div></div></div>


<p>We&#8217;ll also need to define handlers for the base web page and any associated resources, such as Javascript or CSS files, or images.  If there is no resource path &#8211; the URL is just the host and port &#8211; we&#8217;ll return our base page.  Otherwise, we treat the resource path as a relative path to a file, and try to return that.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">     <span class="co1">%% static page handlers</span>
    <span class="kw3">get</span><span class="br0">&#40;</span><span class="re5">Req</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">-&gt;</span> <span class="kw3">get</span><span class="br0">&#40;</span><span class="re5">Req</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="st0">&quot;form.html&quot;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">;</span>  <span class="co1">% main page</span>
&nbsp;
    <span class="kw3">get</span><span class="br0">&#40;</span><span class="re5">_Req</span><span class="sy1">,</span> <span class="re5">Path</span><span class="br0">&#41;</span><span class="sy1">-&gt;</span>  <span class="co1">% other static resources</span>
        <span class="re5">Filename</span> <span class="sy3">=</span> <span class="kw5">filename</span>:<span class="re3">join</span><span class="br0">&#40;</span><span class="re5">Path</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="kw1">case</span> <span class="kw5">file</span>:<span class="re3">read_file</span><span class="br0">&#40;</span><span class="re5">Filename</span><span class="br0">&#41;</span> <span class="kw1">of</span>
            <span class="br0">&#123;</span>ok<span class="sy1">,</span> <span class="re5">PageBytes</span><span class="br0">&#125;</span> <span class="sy1">-&gt;</span> <span class="br0">&#123;</span><span class="nu0">200</span><span class="sy1">,</span> <span class="kw3">binary_to_list</span><span class="br0">&#40;</span><span class="re5">PageBytes</span><span class="br0">&#41;</span><span class="br0">&#125;</span><span class="sy1">;</span>
            <span class="br0">&#123;</span>error<span class="sy1">,</span> <span class="re5">Reason</span><span class="br0">&#125;</span> <span class="sy1">-&gt;</span> <span class="br0">&#123;</span><span class="nu0">404</span><span class="sy1">,</span> <span class="re5">Reason</span><span class="br0">&#125;</span>
        <span class="kw1">end</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<h2>Run it!</h2>
<p>We can start up the Spooky server from the Erlang shell as long as we add Spooky and its dependencies to the code path.  Note that what we&#8217;re doing here is starting the Spooky server, and telling it to use our <code>bowling_web</code> module as its plug-in request handler.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    $ erl <span class="sy3">-</span>pa <span class="re6">$S</span>POOKY<span class="sy3">/</span>ebin <span class="sy3">-</span>pa <span class="re6">$S</span>POOKY<span class="sy3">/</span>deps<span class="sy3">/*/</span>ebin
    <span class="sy1">...</span>
    <span class="re5">Eshell</span> <span class="re5">V5</span><span class="sy1">.</span>8<span class="sy1">.</span>4  <span class="br0">&#40;</span>abort with ^G<span class="br0">&#41;</span>
    <span class="nu0">1</span><span class="sy3">&gt;</span> spooky:<span class="re3">start_link</span><span class="br0">&#40;</span>bowling_web<span class="br0">&#41;</span><span class="sy1">.</span>
    <span class="br0">&#123;</span>ok<span class="sy1">,</span><span class="sy3">&lt;</span>0<span class="sy1">.</span>35<span class="sy1">.</span>0<span class="sy3">&gt;</span><span class="br0">&#125;</span>
    <span class="nu0">2</span><span class="sy3">&gt;</span></pre></div></div></div></div></div></div></div>


<p>Of course, I got tired of typing that every time, so I wrote an Escript to do it.  This uses a <code>SPOOKY_DIR</code> environment variable to find all the dependencies.  As an extra bonus, it compiles all our modules for us.  Note that the same process is compiling them and then loading them.  This is Erlang&#8217;s hot code reloading in action, in a low-key way.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    #<span class="sy3">!/</span>usr<span class="sy3">/</span>local<span class="sy3">/</span>bin<span class="sy3">/</span>escript
&nbsp;
    <span class="re3">main</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re5">SpookyDir</span> <span class="sy3">=</span> <span class="kw5">os</span>:<span class="kw3">get</span><span class="re3">env</span><span class="br0">&#40;</span><span class="st0">&quot;SPOOKY_DIR&quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="co1">%% Add spooky and its dependencies to the code path.</span>
        true <span class="sy3">=</span> <span class="kw5">code</span>:<span class="re3">add_path</span><span class="br0">&#40;</span><span class="re5">SpookyDir</span> <span class="sy3">++</span> <span class="st0">&quot;/ebin&quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="re5">Deps</span> <span class="sy3">=</span> <span class="kw5">filelib</span>:<span class="re3">wildcard</span><span class="br0">&#40;</span><span class="re5">SpookyDir</span> <span class="sy3">++</span> <span class="st0">&quot;/deps/*/ebin&quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
        ok <span class="sy3">=</span> <span class="kw5">code</span>:<span class="re3">add_paths</span><span class="br0">&#40;</span><span class="re5">Deps</span><span class="br0">&#41;</span><span class="sy1">,</span>
&nbsp;
        <span class="co1">%% Compile our modules, just to be safe.</span>
        <span class="kw5">c</span>:<span class="re3">c</span><span class="br0">&#40;</span>bowling_game<span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="kw5">c</span>:<span class="re3">c</span><span class="br0">&#40;</span>bowling_service<span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="kw5">c</span>:<span class="re3">c</span><span class="br0">&#40;</span>bowling_web<span class="br0">&#41;</span><span class="sy1">,</span>
&nbsp;
        spooky:<span class="re3">start_link</span><span class="br0">&#40;</span>bowling_web<span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;Started spooky~n&quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
&nbsp;
        <span class="kw5">io</span>:<span class="kw3">get</span>_<span class="re3">line</span><span class="br0">&#40;</span><span class="st0">&quot;Return to exit...  &quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
        spooky:<span class="re3">stop</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>This is a script, and when it gets to its end it shuts down any processes it started, including Spooky.  So while we started up Spooky as before, we then needed a way to keep the script from exiting.  So we called <code>io:get_line/1</code>, which will hang until the user enters something.  At that point it returns and goes on to the <code>spooky:stop/0</code> line, which shuts down gracefully.</p>
<h2>REST interaction</h2>
<p>Now that the server is up and running, we can test it by hitting our REST service directly from a browser.  We can see that it gets the same results as our command-line run did.</p>
<p><img src="https://github.com/bluegraybox/Crafty-Erlang/raw/master/slide_images/bowling_rest_1.png" alt="add/colin/3"/></p>
<p><img src="https://github.com/bluegraybox/Crafty-Erlang/raw/master/slide_images/bowling_rest_2.png" alt="add/colin/4"/></p>
<p><img src="https://github.com/bluegraybox/Crafty-Erlang/raw/master/slide_images/bowling_rest_3.png" alt="add/colin/10"/></p>
<p><img src="https://github.com/bluegraybox/Crafty-Erlang/raw/master/slide_images/bowling_rest_4.png" alt="add/colin/3"/></p>
<h2>Webapp interaction</h2>
<p>Now we get to the web client itself.  Hitting our base URL brings up the main page.</p>
<p><img src="https://github.com/bluegraybox/Crafty-Erlang/raw/master/slide_images/bowling_app_1.png" alt="/"/></p>
<p>We start off by adding a player.  This is entirely client-side.  Our REST service has no separate way of creating or registering players other than adding scores for them.</p>
<p><img src="https://github.com/bluegraybox/Crafty-Erlang/raw/master/slide_images/bowling_app_2.png" alt="add player - client side"/></p>
<p>Now that we have a player, we can start entering scores for them.  Again, we get the same results as with our command-line and REST interfaces.</p>
<p><img src="https://github.com/bluegraybox/Crafty-Erlang/raw/master/slide_images/bowling_app_3.png" alt="add/colin/3"/></p>
<p><img src="https://github.com/bluegraybox/Crafty-Erlang/raw/master/slide_images/bowling_app_4.png" alt="add/colin/3"/></p>
<p><img src="https://github.com/bluegraybox/Crafty-Erlang/raw/master/slide_images/bowling_app_5.png" alt="add/colin/4"/></p>
<p><img src="https://github.com/bluegraybox/Crafty-Erlang/raw/master/slide_images/bowling_app_6.png" alt="add/colin/10"/></p>
<p><img src="https://github.com/bluegraybox/Crafty-Erlang/raw/master/slide_images/bowling_app_7.png" alt="add/colin/3"/></p>
<p>Now, if you poke at this a little bit, you&#8217;ll find it&#8217;s far from perfect.  As is, it won&#8217;t handle invalid data (rolls greater than 10, for example).  The rolls are stored independently in the client and the server (try sending a direct REST request from another browser in the middle of a game).  It might be nice if the server returned the full list of rolls along with the score, so the client didn&#8217;t have to keep any state in its display.  It would be extra nice if it grouped the rolls by frame.  If you want a good little learning project, try fixing any of these.  You could also try implementing this in a different framework, like mochiweb or webmachine.</p>
<h2>Ta-dah!</h2>
<p>So, we&#8217;ve created an elegant little algorithm, and built both a command-line and web interface to it.  You&#8217;ve gotten a little taste of what it&#8217;s like to work with Escript and Spooky.  Hopefully, you&#8217;ve started learning to think in Erlang, and are getting the hang of the recursion and IPC patterns.</p>
<p>There&#8217;s a bunch of extra stuff that I didn&#8217;t have time for in this talk, including a command-line testing tool for the REST service.  You can find that, along with the full source for these examples, unit tests and so on in my <a href="http://github.com/bluegraybox/Crafty-Erlang">GitHub project for this talk</a>.  That also has the S9 markup source for my slides, which you can <a href="http://bluegraybox.github.com/Crafty-Erlang">see on GitHub Pages</a>.  You can follow my continuing adventures, and catch up on previous experiments, ponderings, and rants here on <a href="http://bluegraybox.com/blog">my blog</a>.</p>
<h2>Think small, have fun</h2>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2011/12/06/crafty-erlang/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Elegant Bowling</title>
		<link>http://www.bluegraybox.com/blog/2011/11/25/elegant-bowling/</link>
		<comments>http://www.bluegraybox.com/blog/2011/11/25/elegant-bowling/#comments</comments>
		<pubDate>Fri, 25 Nov 2011 23:56:22 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=191</guid>
		<description><![CDATA[I've had a few mind-blowing moments since I started learning Erlang. One of those was at a hack night where we did the Bowling Game as a pair programming exercise.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve had a few mind-blowing moments since I started learning Erlang.  One of those was at a hack night where we did the Bowling Game as a pair programming exercise.  It&#8217;s a standard, simple programming challenge: calculate the score for a series of rolls in bowling.  It&#8217;s not entirely trivial: Calculating the score for spare and strike frames adds a bit of trickiness, and there are edge cases around the end of the game.</p>
<p>By coincidence, I&#8217;d done it about a year earlier in Python for another hack night.  In an OO language, it&#8217;s pretty obvious to model it as a <a href="https://github.com/bluegraybox/examples/blob/master/bowling/python/Game.py">Game</a> object which contains a list of <a href="https://github.com/bluegraybox/examples/blob/master/bowling/python/Frame.py">Frame</a> objects.  It&#8217;s less clear how to handle the fact that the score for a frame may depend on rolls in other frames.  Either frames have to know about other frames, or rolls have to be added to multiple frames, or the Game class has to handle the spare and strike calculations, or something like that.  All of the options feel a little awkward, so you can get wrapped around the axle there.  But in the end, I had a solution I was pretty happy with.  It weighed in at 53 lines of code.</p>
<p>The final version* in Erlang was 15.  Wow.  I think of Python as a pretty compact language, and the Erlang code is less than a third as long.  And it&#8217;s not some high-density, Perl-style line noise; it&#8217;s clearer &#8211; hardly more than a definition of the rules of the game.</p>
<p><em>(* Thanks to <a href="http://rusty.io/">Rusty</a> for pointing us in the right direction here.)</em></p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">0</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">score</span><span class="br0">&#40;</span><span class="re5">_BonusRolls</span><span class="sy1">,</span> <span class="nu0">11</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Score</span><span class="sy1">;</span>
&nbsp;
<span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="nu0">10</span> | <span class="re5">Rest</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="nu0">10</span> <span class="sy3">+</span> <span class="re3">strike_bonus</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy1">;</span>
&nbsp;
<span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Roll1</span><span class="sy1">,</span> <span class="re5">Roll2</span> | <span class="re5">Rest</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="re5">Roll1</span> <span class="sy3">+</span> <span class="re5">Roll2</span> <span class="sy3">==</span> <span class="nu0">10</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="nu0">10</span> <span class="sy3">+</span> <span class="re3">spare_bonus</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="sy1">;</span>
&nbsp;
<span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Roll1</span><span class="sy1">,</span> <span class="re5">Roll2</span> | <span class="re5">Rest</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="re5">Roll1</span> <span class="sy3">+</span> <span class="re5">Roll2</span><span class="br0">&#41;</span><span class="sy1">;</span>
&nbsp;
<span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Roll1</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">_Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="re5">Roll1</span><span class="sy1">;</span>
<span class="re3">score</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">_Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Score</span><span class="sy1">.</span>
&nbsp;
&nbsp;
<span class="re3">spare_bonus</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="nu0">0</span><span class="sy1">;</span>
<span class="re3">spare_bonus</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Bonus1</span> | <span class="re5">_Rest</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Bonus1</span><span class="sy1">.</span>
&nbsp;
<span class="re3">strike_bonus</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="nu0">0</span><span class="sy1">;</span>
<span class="re3">strike_bonus</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Only</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Only</span><span class="sy1">;</span>
<span class="re3">strike_bonus</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Bonus1</span><span class="sy1">,</span> <span class="re5">Bonus2</span> | <span class="re5">_Rest</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Bonus1</span> <span class="sy3">+</span> <span class="re5">Bonus2</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p><em>(If you&#8217;re completely new to Erlang, the multiple function definitions are essentially implicit if-elseif conditions matched against the values of the parameters.)</em></p>
<p>So what makes the Python code so much longer?  A lot of it is spent querying and updating the state of the objects.  That&#8217;s also where a lot of the design complexity came from, figuring out how each object interacts with the others.  In the Erlang solution, we do an end run around all that by just using simple lists and variables.  The input is a list of numbers; the output is a single number; why use anything more complex in between?</p>
<p>The point of this is not which language is better; it&#8217;s that using Erlang showed me a different way to solve this problem.  I went back and <a href="https://github.com/bluegraybox/examples/blob/master/bowling/python/game_recurse.py">translated the Erlang code into Python</a>.  It&#8217;s straightforward: one function with a big if-elif block.  You can do it as either a recursive function or a while loop.  Either way, it ends up being pretty much the same length as in Erlang.</p>
<p>(As a side note: A nice thing about using recursion is that it simplifies variable scoping.  At each step, you&#8217;re calling a function with an explicit set of parameters.  This makes it clear what state is being passed along.  If you&#8217;re just modifying variables and looping, it would be easy to forget to update a value.)</p>
<p>So why didn&#8217;t I come up with the simpler solution when I wrote this in Python?  It&#8217;s mostly a matter of culture.  As with natural languages, programming languages come with a layer of culture; what the <em>normal</em> way of writing programs is.  Because Python is an OO language, the first question I asked was &#8220;What are the objects?&#8221; What are the concepts in the problem domain, and how do I map them to classes?  While that may turn out to be a necessary intermediate step, it&#8217;s not actually the end goal.  It&#8217;s easy to lose sight of that.  You can jump right in and start coding up classes: constructors, accessors, unit tests and so on.  You can write a fair amount of code without thinking too much about what you&#8217;re trying to accomplish.  That feels like progress, but it may just be a diversion.  In this case, it&#8217;s not necessary and only adds complexity.</p>
<p>In a functional language like Erlang, the first question is &#8220;What are my inputs and outputs?&#8221; What is the end result I&#8217;m trying to get to, and where am I starting from?  It keeps you focused on the data you have and what you&#8217;re trying to accomplish.  Erlang&#8217;s pattern matching brings a lot of power to working with simple data structures.  If you want to create real mutable objects, you can, but Erlang makes you deal with concurrency up front, so it&#8217;s less trivial.  It encourages you to think of the simplest thing that works.</p>
<p>It seems like this should be a transferable skill, but I suspect there&#8217;s a catch.  I could certainly use recursion and simple data structures in my Python code (or Ruby and maybe to a lesser extent Java).  If it cuts out a lot of extraneous object munging and dramatically reduces the line count, that should make it more maintainable.  The trouble is that &#8220;maintainable&#8221; means &#8220;maintainable by other programmers&#8221;.  My code may be more elegant and concise, but if it&#8217;s using programming idioms they aren&#8217;t familiar with, they&#8217;re going to have trouble with it.  I can trust that Erlang programmers are familiar with recursion because Erlang uses it for <em>everything</em>.  That&#8217;s not true of Python.  This is the flip side of culture: There are things that you <em>could</em> say &#8211; that are grammatically correct &#8211; but you wouldn&#8217;t.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2011/11/25/elegant-bowling/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fizzbuzz</title>
		<link>http://www.bluegraybox.com/blog/2011/11/08/fizzbuzz/</link>
		<comments>http://www.bluegraybox.com/blog/2011/11/08/fizzbuzz/#comments</comments>
		<pubDate>Wed, 09 Nov 2011 03:06:16 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=184</guid>
		<description><![CDATA[Fizzbuzz is about the simplest programming challenge imaginable, but it&#8217;s been observed that a surprising number of seemingly experienced programmers choke when told to actually sit down and code it. Of course, telling any programmer this pretty much compels us to sit down and code it just to prove (to ourselves at least) that we [...]]]></description>
			<content:encoded><![CDATA[<p>Fizzbuzz is about the simplest programming challenge imaginable, but <a href="http://imranontech.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/">it&#8217;s been observed</a> that a surprising number of seemingly experienced programmers choke when told to actually sit down and code it. Of course, telling any programmer this <a href="http://www.codinghorror.com/blog/2007/02/fizzbuzz-the-programmers-stairway-to-heaven.html">pretty much compels us</a> to sit down and code it just to prove (to ourselves at least) that we can. Since I&#8217;ve been tinkering in Erlang, I figured I&#8217;d try that. The instructive thing is that even for something this simple, you have to do it differently in Erlang. In fact, it&#8217;s surprising to see <em>how</em> differently you end up doing it in Erlang.</p>
<p>So for reference, here&#8217;s the Python version:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="python"><pre class="de1"><span class="co1">#!/usr/bin/python</span>
&nbsp;
<span class="kw2">max</span> <span class="sy0">=</span> <span class="nu0">100</span>
<span class="kw1">for</span> x <span class="kw1">in</span> <span class="kw2">range</span><span class="br0">&#40;</span><span class="nu0">1</span><span class="sy0">,</span><span class="kw2">max</span>+<span class="nu0">1</span><span class="br0">&#41;</span>:
    <span class="kw1">if</span> <span class="br0">&#40;</span><span class="br0">&#40;</span>x % <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy0">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="kw1">and</span> <span class="br0">&#40;</span><span class="br0">&#40;</span>x % <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy0">==</span> <span class="nu0">0</span><span class="br0">&#41;</span>:
        <span class="kw1">print</span> <span class="st0">&quot;fizzbuzz&quot;</span>
    <span class="kw1">elif</span> <span class="br0">&#40;</span>x % <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy0">==</span> <span class="nu0">0</span>:
        <span class="kw1">print</span> <span class="st0">&quot;fizz&quot;</span>
    <span class="kw1">elif</span> <span class="br0">&#40;</span><span class="br0">&#40;</span>x % <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy0">==</span> <span class="nu0">0</span><span class="br0">&#41;</span>:
        <span class="kw1">print</span> <span class="st0">&quot;buzz&quot;</span>
    <span class="kw1">else</span>:
        <span class="kw1">print</span> x</pre></div></div></div></div></div></div></div>


<p>Here&#8217;s my first draft of the Erlang version</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">#<span class="sy3">!/</span>usr<span class="sy3">/</span>local<span class="sy3">/</span>bin<span class="sy3">/</span>escript
<span class="sy3">-</span><span class="re2">mode</span><span class="br0">&#40;</span>compile<span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">main</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="nu0">1</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="re5">X</span> <span class="sy3">&gt;</span> <span class="nu0">100</span> <span class="sy1">-&gt;</span>
    <span class="me1">ok</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="kw2">and</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;fizzbuzz~n&quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="br0">&#41;</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;fizz~n&quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="br0">&#41;</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;buzz~n&quot;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="br0">&#41;</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;~p~n&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">X</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>So it works, and it uses pattern matching and recursion, but it feels kinda messy. That version is all about the side effects. Let&#8217;s split out the printing, and see what we get.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">#<span class="sy3">!/</span>usr<span class="sy3">/</span>local<span class="sy3">/</span>bin<span class="sy3">/</span>escript
<span class="sy3">-</span><span class="re2">mode</span><span class="br0">&#40;</span>compile<span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">main</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re5">Out</span> <span class="sy3">=</span> <span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="nu0">1</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">print</span><span class="br0">&#40;</span><span class="re5">Out</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="sy1">,</span> <span class="re5">Out</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="re5">X</span> <span class="sy3">&gt;</span> <span class="nu0">100</span> <span class="sy1">-&gt;</span>
    <span class="kw5">lists</span>:<span class="re3">reverse</span><span class="br0">&#40;</span><span class="re5">Out</span><span class="br0">&#41;</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="sy1">,</span> <span class="re5">Out</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="kw2">and</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="br0">&#91;</span>fizzbuzz|Out<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="sy1">,</span> <span class="re5">Out</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span> <span class="sy1">-&gt;</span>
    <span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="br0">&#91;</span>fizz|Out<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="sy1">,</span> <span class="re5">Out</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span> <span class="sy1">-&gt;</span>
    <span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="br0">&#91;</span>buzz|Out<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="sy1">,</span> <span class="re5">Out</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">X</span>|Out<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">print</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="me1">ok</span><span class="sy1">;</span>
<span class="re3">print</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">First</span>|Rest<span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;~p~n&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">First</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">print</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>Ok, that&#8217;s conceptually a bit cleaner, but the code itself actually feels more cluttered. Thinking about it some more, I realize the fizzbuzz function itself isn&#8217;t recursive. Each value can be calculated independently. fizzbuzz(6) is fizz, whether it appears in a sequence or not. We have the fizzbuzz calculation mashed together with iterating over a range. Let&#8217;s rework that so that the list printing function handles the iteration instead.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">#<span class="sy3">!/</span>usr<span class="sy3">/</span>local<span class="sy3">/</span>bin<span class="sy3">/</span>escript
<span class="sy3">-</span><span class="re2">mode</span><span class="br0">&#40;</span>compile<span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">main</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re3">print_loop</span><span class="br0">&#40;</span><span class="nu0">1</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">print_loop</span><span class="br0">&#40;</span><span class="re5">I</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="re5">I</span> <span class="sy3">&gt;</span> <span class="nu0">100</span> <span class="sy1">-&gt;</span>
    <span class="me1">ok</span><span class="sy1">;</span>
<span class="re3">print_loop</span><span class="br0">&#40;</span><span class="re5">I</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;~p~n&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">I</span><span class="br0">&#41;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">print_loop</span><span class="br0">&#40;</span><span class="re5">I</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="kw2">and</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="me1">fizzbuzz</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="me1">fizz</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="me1">buzz</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">X</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>Now the fizzbuzz function itself is very declarative, and the looping is cleaner and simpler. This separation lets us parameterize the function and max value in the print_loop without modifying the fizzbuzz rules. That&#8217;s kinda nice.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">#<span class="sy3">!/</span>usr<span class="sy3">/</span>local<span class="sy3">/</span>bin<span class="sy3">/</span>escript
<span class="sy3">-</span><span class="re2">mode</span><span class="br0">&#40;</span>compile<span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
&nbsp;
<span class="re3">main</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re3">print_loop</span><span class="br0">&#40;</span><span class="kw1">fun</span> fizzbuzz<span class="sy3">/</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">100</span><span class="sy1">,</span> <span class="nu0">1</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">print_loop</span><span class="br0">&#40;</span><span class="re5">_Func</span><span class="sy1">,</span> <span class="re5">Max</span><span class="sy1">,</span> <span class="re5">I</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="re5">I</span> <span class="sy3">&gt;</span> <span class="re5">Max</span> <span class="sy1">-&gt;</span>
    <span class="me1">ok</span><span class="sy1">;</span>
<span class="re3">print_loop</span><span class="br0">&#40;</span><span class="re5">Func</span><span class="sy1">,</span> <span class="re5">Max</span><span class="sy1">,</span> <span class="re5">I</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;~p~n&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">F</span><span class="re3">unc</span><span class="br0">&#40;</span><span class="re5">I</span><span class="br0">&#41;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">print_loop</span><span class="br0">&#40;</span><span class="re5">Func</span><span class="sy1">,</span> <span class="re5">Max</span><span class="sy1">,</span> <span class="re5">I</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="kw2">and</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="me1">fizzbuzz</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="me1">fizz</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="br0">&#40;</span><span class="re5">X</span> <span class="kw2">rem</span> <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy3">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="me1">buzz</span><span class="sy1">;</span>
<span class="re3">fizzbuzz</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">X</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>The end result is about the same number of lines of code as the Python version, so I can&#8217;t say that it&#8217;s more efficient. But it&#8217;s surprisingly <em>different</em>. You can go back and re-write the Python version to have that functional separation, but it doesn&#8217;t feel the same.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="python"><pre class="de1"><span class="co1">#!/usr/bin/python</span>
&nbsp;
<span class="kw1">def</span> fizzbuzz<span class="br0">&#40;</span>x<span class="br0">&#41;</span>:
    <span class="kw1">if</span> <span class="br0">&#40;</span><span class="br0">&#40;</span>x % <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy0">==</span> <span class="nu0">0</span><span class="br0">&#41;</span> <span class="kw1">and</span> <span class="br0">&#40;</span><span class="br0">&#40;</span>x % <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy0">==</span> <span class="nu0">0</span><span class="br0">&#41;</span>:
        <span class="kw1">return</span> <span class="st0">&quot;fizzbuzz&quot;</span>
    <span class="kw1">elif</span> <span class="br0">&#40;</span>x % <span class="nu0">3</span><span class="br0">&#41;</span> <span class="sy0">==</span> <span class="nu0">0</span>:
        <span class="kw1">return</span> <span class="st0">&quot;fizz&quot;</span>
    <span class="kw1">elif</span> <span class="br0">&#40;</span><span class="br0">&#40;</span>x % <span class="nu0">5</span><span class="br0">&#41;</span> <span class="sy0">==</span> <span class="nu0">0</span><span class="br0">&#41;</span>:
        <span class="kw1">return</span> <span class="st0">&quot;buzz&quot;</span>
    <span class="kw1">else</span>:
        <span class="kw1">return</span> x
&nbsp;
<span class="kw2">max</span> <span class="sy0">=</span> <span class="nu0">100</span>
<span class="kw1">for</span> x <span class="kw1">in</span> <span class="kw2">range</span><span class="br0">&#40;</span><span class="nu0">1</span><span class="sy0">,</span><span class="kw2">max</span>+<span class="nu0">1</span><span class="br0">&#41;</span>:
        <span class="kw1">print</span> fizzbuzz<span class="br0">&#40;</span>x<span class="br0">&#41;</span></pre></div></div></div></div></div></div></div>


<p>And would you really? The original Python version looks fine; the second one is actually uglier, with its multiple returns. It&#8217;s not just a matter of what&#8217;s possible in a language, or what&#8217;s more conceptually elegant; it&#8217;s what the language can express cleanly and easily, and what&#8217;s familiar to its developer community.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2011/11/08/fizzbuzz/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Erlang: Your New Favorite Scripting Language?</title>
		<link>http://www.bluegraybox.com/blog/2011/09/18/erlang-your-new-favorite-scripting-language/</link>
		<comments>http://www.bluegraybox.com/blog/2011/09/18/erlang-your-new-favorite-scripting-language/#comments</comments>
		<pubDate>Sun, 18 Sep 2011 21:08:53 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[erlang]]></category>
		<category><![CDATA[talks]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=170</guid>
		<description><![CDATA[This is based on a talk I gave to the Arlington/DC Erlang users&#8217; group. What&#8217;s cool about Erlang? Normally, if you ask &#8220;What&#8217;s cool about Erlang?&#8221; people will talk about scalability. They&#8217;ll talk about performance, about servers that handle thousands of requests a second without breaking a sweat. They&#8217;ll say crazy things like &#8220;Nine 9s [...]]]></description>
			<content:encoded><![CDATA[<p><em>This is based on a talk I gave to the <a href="http://www.meetup.com/erlang/">Arlington/DC Erlang users&#8217; group</a>.</em></p>
<h3>What&#8217;s cool about Erlang?</h3>
<p>Normally, if you ask &#8220;What&#8217;s cool about Erlang?&#8221; people will talk about scalability.  They&#8217;ll talk about performance, about servers that handle thousands of requests a second without breaking a sweat.  They&#8217;ll say crazy things like &#8220;Nine 9s uptime.&#8221; They&#8217;ll talk about how concurrency is baked in to the language, how spawning processes, monitoring them, and sending messages between them is trivial.  They&#8217;ll talk about how you can upgrade your app <em>while it&#8217;s running</em>, with each process loading its new code when it&#8217;s convenient.  They&#8217;ll admit it has some quirks &#8211; weird syntax and awkward constraints &#8211; but that&#8217;s what you have to put up with to get the good stuff.</p>
<p>That is in fact amazingly cool stuff, but what do I do with it?  I don&#8217;t run into a lot of problems that require that massive scale of solution.  I run into a lot of problems that require some quick little scripty thing.  Maybe bigger ones might run to a few hundred lines of code.  If I <em>did</em> have to build something massively scalable, I&#8217;d be leary of doing it in a language I didn&#8217;t know.  There&#8217;s a chicken-and-egg problem here.</p>
<p>I&#8217;d like to take a different look at Erlang, one that might help break that deadlock.  I&#8217;m going to talk about how Erlang is actually a good language for small programs, and how its &#8220;weird&#8221; syntax and language features actually help you write clearer, more concise, and more elegant code.  They take a bit of getting used to, but you&#8217;ll adapt faster than you expect, and you won&#8217;t look at other languages quite the same way again.  Part of what&#8217;s cool about Erlang is what&#8217;s cool about functional programming, but it goes beyond that with its own features that make it even more powerful and expressive.</p>
<h3>Procedural, OO, Functional</h3>
<p>A little background in case you&#8217;re not familiar with functional programming.  There are three basic styles of programming: Procedural, object-oriented, and functional.  (Wikipedia lists about 60, but in my mind, and for the purpose of this discussion, these are the big ones.) Like other human languages, programming languages are not just rules for expressing thoughts; they also embody a culture, a way of looking at and making sense of the world.  Most are not strictly one style, but creoles, mutts to varying degrees, blending influences from the others.</p>
<p>Procedural programming is very narrative.  It explains the world as a sequence of actions.  Do this, do that, then do this other thing; in that case, do this instead.  Functions are like anecdotes, little incidents that the narrative is built up from.  There are things &#8211; data structures &#8211; but they&#8217;re fairly simple.  They&#8217;re passive &#8211; things are done to them.  The narrative may be meandering and incoherent, but there&#8217;s a continuity to it.  C is a procedural language.  Perl is a procedural language with objects bolted on as an afterthought.</p>
<p>This fits pretty well with how people see the world.  We make sense of it through stories.  Even the barest facts need narrative context to be meaningful.</p>
<p>Object-oriented programming focuses on things; things that do things.  This is another way that people explain the world, though in a narrower context.  It looks more at actors and elements in isolation.  We talk about how people behave, or animals; what their capabilities are.  We talk about the utility of things, their features and limits.</p>
<p>OO programming focuses on these actors and elements, what you can do with them and how they interconnect.  It can be powerful and flexible, but it also runs the risk of losing the narrative.  Instead of jumbled strands of procedural spaghetti code, you can end up with ravioli code &#8211; code where it&#8217;s clear what each individual part does, but it&#8217;s hard to piece together the whole.  By the time you&#8217;ve traced your way down a chain of a half-dozen object linkages, you have no idea of what they&#8217;re actually accomplishing.  Java is a mostly OO language.  Python and Ruby are strongly OO, with some functional influence (stronger in Ruby).</p>
<p>Functional languages define a mapping from inputs to outputs.  This is not a normal human way of looking at the world; it&#8217;s very abstract and mathematical.</p>
<p>But all programming is ultimately about taking in some data and producing some sort of output, whether it&#8217;s to a screen, database, file, network, or whatever.  It&#8217;s inherently abstract and mathematical.  A language that forces you to focus on that can be very powerful and expressive.  This is all hard to explain without examples, so we&#8217;ll be getting into those soon.</p>
<p>Doing this requires that you kinda rewire your brain.  The good news is that that&#8217;s much easier than you&#8217;d expect, and a lot more fun.  Especially at first, you&#8217;ll get a lot of &#8220;a-ha!&#8221; moments, with that little burst of neuro-chemical reward for figuring something out.  As with most games, it can be bewildering at first, but there are patterns and strategies you learn that help you make sense of it.</p>
<p>Working with procedural languages, you can do this stream of consciousness thing.  Just start at the first thing you do, and step through it from there.  I think of OO programming as kinda like working with Play-Doh.  I figure out what the main objects are, the big chunks of functionality.  Then I mush those around, occasionally ripping out some bit of functionality from one class and glomming it onto another.  As I work on them, they gradually get smoother and more coherent.  Both of these are very incremental processes.  I can just start writing code and see what comes out of it.</p>
<p>The experience of writing functional code is kinda like doing math.  It requires a lot more up-front thought.  There&#8217;s a lot more staring at a blank screen or scribbling tentative ideas on a whiteboard.  But when you figure it out, you <em>know</em> it; it really clicks.  It&#8217;s an almost physical sensation.</p>
<p>So why would you bother?  Why would you code in an unituitive language?  Why would you take longer to figure out how to do something functionally, when you could just slap it together quickly in an OO or procedural language?  Because what you end up with may be much simpler and clearer.  Sometimes, the procedural solution looks like this:</p>
<pre><code>1 + 2 + 3 + 4 + ... + n
</code></pre>
<p>and the functional solution looks like this:</p>
<pre><code>n(n+1)/2
</code></pre>
<h3>Reading Erlang</h3>
<p>In case you&#8217;re not familiar with Erlang code, I&#8217;ll take a couple minutes to give you the basics &#8211; just what you&#8217;ll need to be able to read the examples I&#8217;m going to throw at you; not enough to really write Erlang from scratch.</p>
<p>Even people who like Erlang will talk about its &#8220;weird&#8221; syntax.  Really, &#8220;weird&#8221; just means &#8220;doesn&#8217;t look like C.&#8221; Almost every mainstream language since C has adopted similar syntax.  Java, the current 800-pound gorilla, deliberately tried to look as familar as possible to the legions of existing C developers.  C# went as far as keeping the name.  Javascript, Perl, Php, Python, and even Ruby are all basically C-like.</p>
<p>So, to start with the basics of Erlang:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="co1">%% This is a comment.</span>
<span class="re5">Variable</span>  <span class="co1">% starts with a capital letter.</span>
<span class="kw4">atom</span>  <span class="co1">% this is a value, not a variable - like :atom in ruby</span>
<span class="br0">&#91;</span><span class="nu0">1</span><span class="sy1">,</span><span class="nu0">2</span><span class="sy1">,</span><span class="nu0">3</span><span class="br0">&#93;</span>  <span class="co1">% list</span>
<span class="br0">&#123;</span><span class="nu0">1</span><span class="sy1">,</span><span class="nu0">2</span><span class="sy1">,</span><span class="nu0">3</span><span class="br0">&#125;</span>  <span class="co1">% tuple</span></pre></div></div></div></div></div></div></div>


<p>You can do multi-assignments with lists like so:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="br0">&#91;</span><span class="re5">X</span><span class="sy1">,</span> <span class="re5">Y</span><span class="sy1">,</span> <span class="re5">Z</span><span class="br0">&#93;</span> <span class="sy3">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">2</span><span class="sy1">,</span> <span class="nu0">3</span><span class="br0">&#93;</span>  <span class="co1">% X=1, Y=2, Z=3</span>
<span class="br0">&#91;</span><span class="re5">First</span><span class="sy1">,</span> <span class="re5">Second</span> | <span class="re5">Rest</span><span class="br0">&#93;</span> <span class="sy3">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">2</span><span class="sy1">,</span> <span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">4</span><span class="br0">&#93;</span>  <span class="co1">% First=1, Second=2, Rest=[3,4]</span>
<span class="br0">&#91;</span><span class="re5">First</span><span class="sy1">,</span> <span class="re5">Second</span> | <span class="re5">Rest</span><span class="br0">&#93;</span> <span class="sy3">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">2</span><span class="br0">&#93;</span>  <span class="co1">% First=1, Second=2, Rest=[]</span></pre></div></div></div></div></div></div></div>


<p>Note that this will cause an error, because 3 &amp; 4 have nowhere to go:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="br0">&#91;</span><span class="re5">First</span><span class="sy1">,</span> <span class="re5">Second</span><span class="br0">&#93;</span> <span class="sy3">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">2</span><span class="sy1">,</span> <span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">4</span><span class="br0">&#93;</span></pre></div></div></div></div></div></div></div>


<p>If you want to ignore them, use an underscore, either by itself or in front of a variable name:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="br0">&#91;</span><span class="re5">First</span><span class="sy1">,</span> <span class="re5">Second</span> | <span class="re5">_</span> <span class="br0">&#93;</span> <span class="sy3">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">2</span><span class="sy1">,</span> <span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">4</span><span class="br0">&#93;</span>  <span class="co1">% </span>
<span class="br0">&#91;</span><span class="re5">First</span><span class="sy1">,</span> <span class="re5">Second</span> | <span class="re5">_Rest</span> <span class="br0">&#93;</span> <span class="sy3">=</span> <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">2</span><span class="sy1">,</span> <span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">4</span><span class="br0">&#93;</span></pre></div></div></div></div></div></div></div>


<p>Function definitions are simple, since neither the return value nor the parameters are typed:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">my_func</span><span class="br0">&#40;</span><span class="re5">Param1</span><span class="sy1">,</span> <span class="re5">Param2</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="co1">%% do stuff</span>
    <span class="re5">X</span> <span class="sy3">=</span> <span class="re3">some_func</span><span class="br0">&#40;</span><span class="re5">Param1</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re5">Y</span> <span class="sy3">=</span> <span class="re3">some_other_func</span><span class="br0">&#40;</span><span class="re5">Param2</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re5">Status</span> <span class="sy3">=</span> ok<span class="sy1">,</span>  <span class="co1">% assign value to variable</span>
    <span class="br0">&#123;</span><span class="re5">Status</span><span class="sy1">,</span> <span class="re5">X</span><span class="sy1">,</span> <span class="re5">Y</span><span class="br0">&#125;</span><span class="sy1">.</span>  <span class="co1">% return a tuple</span></pre></div></div></div></div></div></div></div>


<p>That may look a bit quirky to most programmers, but mathematicians would be happy that this is a valid function definition in Erlang.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">f</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">X</span> <span class="sy3">*</span> <span class="nu0">2</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>You can overload functions, defining different versions of a function with the same name but different numbers of parameters:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">my_func</span><span class="br0">&#40;</span><span class="re5">Param1</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re3">my_func</span><span class="br0">&#40;</span><span class="re5">Param1</span><span class="sy1">,</span> <span class="st0">&quot;default&quot;</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">my_func</span><span class="br0">&#40;</span><span class="re5">Param1</span><span class="sy1">,</span> <span class="re5">Param2</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="co1">%% actually do stuff...</span></pre></div></div></div></div></div></div></div>


<p>Erlang takes overriding a step further, and lets you do it by <em>value</em>.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">my_func</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="sy1">...</span>
&nbsp;
<span class="re3">my_func</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Only</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="sy1">...</span>
&nbsp;
<span class="re3">my_func</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">First</span><span class="sy1">,</span> <span class="re5">Second</span> | <span class="re5">Rest</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="sy1">...</span></pre></div></div></div></div></div></div></div>


<p>It also lets you use &#8220;guards&#8221; &#8211; boolean expressions &#8211; to further break up your function definitions:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">my_func</span><span class="br0">&#40;</span><span class="nu0">0</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="sy1">...</span>
&nbsp;
<span class="re3">my_func</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> where <span class="re5">X</span> <span class="sy3">&gt;</span> <span class="nu0">0</span> <span class="sy1">-&gt;</span> <span class="sy1">...</span>
&nbsp;
<span class="re3">my_func</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> where <span class="re5">X</span> <span class="sy3">&lt;</span> <span class="nu0">0</span> <span class="sy1">-&gt;</span> <span class="sy1">...</span></pre></div></div></div></div></div></div></div>


<p>It may not make much practical difference, but this style of code feels more declarative.  The function definitions feel more distinct and self-contained than a sequence of if-else checks.</p>
<p>Guards also show up in &#8216;if&#8217; expressions.  In Erlang, these are implicitly if-elseif checks.  Here, we&#8217;ll go down the left side conditionals until we find one that matches; then we&#8217;ll return the corresponding value on the right.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="kw1">if</span>
    <span class="re5">X</span> <span class="sy3">&gt;=</span> <span class="nu0">100</span> <span class="sy1">-&gt;</span> <span class="nu0">100</span><span class="sy1">;</span>
    <span class="re5">X</span> <span class="sy3">&gt;=</span> <span class="nu0">0</span>   <span class="sy1">-&gt;</span> <span class="re5">X</span><span class="sy1">;</span>
    true     <span class="sy1">-&gt;</span> <span class="nu0">0</span>
<span class="kw1">end</span></pre></div></div></div></div></div></div></div>


<p>Case statements work similarly.  Here we get the return value of my_func(X) and go down the left side until we find a match; then return the value on the right.  If the left side is an unassigned variable, it counts as a match, and the case value is assigned to it.  This example says, &#8220;if my_func(X) returns &#8216;error&#8217;, return an empty list; otherwise assign the value to List and return that.&#8221;</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="kw1">case</span> <span class="re3">my_func</span><span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="kw1">of</span>
    error <span class="sy1">-&gt;</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="sy1">;</span>
    <span class="re5">List</span> <span class="sy1">-&gt;</span> <span class="re5">List</span>
<span class="kw1">end</span></pre></div></div></div></div></div></div></div>


<p>That may seem a little bizarre, but it makes for very elegant error handling:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re5">Output</span> <span class="sy3">=</span> <span class="kw1">case</span> <span class="kw5">file</span>:<span class="re3">open</span><span class="br0">&#40;</span><span class="re5">Filename</span><span class="sy1">,</span> <span class="br0">&#91;</span>read<span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="kw1">of</span>
    <span class="br0">&#123;</span>ok<span class="sy1">,</span> <span class="re5">Handle</span><span class="br0">&#125;</span> <span class="sy1">-&gt;</span>
        <span class="kw3">process</span>_<span class="re3">file</span><span class="br0">&#40;</span><span class="re5">Handle</span><span class="br0">&#41;</span><span class="sy1">;</span>
    <span class="br0">&#123;</span>error<span class="sy1">,</span> <span class="re5">Reason</span><span class="br0">&#125;</span> <span class="sy1">-&gt;</span>
        <span class="re3">log_error</span><span class="br0">&#40;</span><span class="re5">Reason</span><span class="sy1">,</span> <span class="re5">Filename</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="br0">&#91;</span><span class="br0">&#93;</span>
<span class="kw1">end</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>Essentially, this says that if the return status of file:open() is &#8216;ok&#8217;, then<br />
    Output = process_file(Handle)<br />
If it&#8217;s &#8216;error&#8217;, then log it and set<br />
    Output = []</p>
<p>Now, turning your Erlang code into a command-line script is as simple as this:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">#<span class="sy3">!/</span>usr<span class="sy3">/</span>bin<span class="sy3">/</span>escript
&nbsp;
<span class="re3">main</span><span class="br0">&#40;</span><span class="re5">_Args</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;Hello World!~n&quot;</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>If you want to handle command-line arguments, you can do this:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">#<span class="sy3">!/</span>usr<span class="sy3">/</span>bin<span class="sy3">/</span>escript
&nbsp;
<span class="re3">main</span><span class="br0">&#40;</span><span class="re5">Args</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re3">main</span><span class="br0">&#40;</span><span class="st0">&quot;World&quot;</span><span class="sy1">,</span> <span class="re5">Args</span><span class="br0">&#41;</span><span class="sy1">.</span>  <span class="co1">% invoked first, sets Name=&quot;World&quot;</span>
&nbsp;
<span class="re3">main</span><span class="br0">&#40;</span><span class="re5">_</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="st0">&quot;-h&quot;</span> | <span class="re5">_Args</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;Help! Help!~n&quot;</span><span class="br0">&#41;</span><span class="sy1">;</span>  <span class="co1">% print message, exit.</span>
&nbsp;
<span class="re3">main</span><span class="br0">&#40;</span><span class="re5">_</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="st0">&quot;-n&quot;</span><span class="sy1">,</span> <span class="re5">Name</span> | <span class="re5">Args</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>  <span class="co1">% ignore old name, pop new one off Args.</span>
    <span class="re3">main</span><span class="br0">&#40;</span><span class="re5">Name</span><span class="sy1">,</span> <span class="re5">Args</span><span class="br0">&#41;</span><span class="sy1">;</span>            <span class="co1">% recurse to next arg with new Name.</span>
&nbsp;
<span class="re3">main</span><span class="br0">&#40;</span><span class="re5">Name</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw5">io</span>:<span class="re3">format</span><span class="br0">&#40;</span><span class="st0">&quot;Hello, ~s!~n&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">Name</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">.</span>  <span class="co1">% print message, exit.</span></pre></div></div></div></div></div></div></div>


<p>Note that this will handle any number of &#8220;-n name&#8221; options, and only keep the last one.  It will exit when it gets a &#8220;-h&#8221; arg, or when it runs out of args.  It will exit with an error if it gets any other kind of arg, or if &#8220;-n&#8221; is the last arg.</p>
<h3>Indent Parser</h3>
<p>I first looked at Erlang about three years ago.  It was cool, and I was excited to build an app in it, but what to do?  I didn&#8217;t have any personal projects that made sense as massively distributed, concurrent apps.  So it sat on the shelf.</p>
<p>I came back to Erlang in a roundabout way.  I was going through one of my periodic &#8220;get my act together&#8221; phases.  This time I decided that what I really needed was a project database that I could keep in a flat file in some sort of markup language.  That would allow me to review the whole thing easily, and print it all out in a compact form if need be.  I&#8217;d group projects, sub-projects, and actions just by indents.</p>
<pre><code>project
    action
    sub-project
        action
    action
project
    sub-project
        sub-project
            action
</code></pre>
<p>And the actions would have markup to indicate context, due date, priority, and so on.</p>
<pre><code>work on presentation [computer, quiet] (2011-08-24) !!
</code></pre>
<p>Then I could write a script to parse it and list my next actions by context in the order I should tackle them.</p>
<p>I never got that far.  I got as far as writing a Ruby script to parse the indented text into a logical tree structure, that would turn this</p>
<p><img src="https://github.com/bluegraybox/erlang_intro/raw/master/parser/input.png" alt="Input"></p>
<p>into this</p>
<p><img src="https://github.com/bluegraybox/erlang_intro/raw/master/parser/structure.png" alt="Output"></p>
<p>It had the OO structure you&#8217;d expect: Parser, Lines, Trees, Nodes, Leaves.  It took each input line, and tacked it on to the tree in the next appropriate spot, building it out like so:</p>
<p><img src="https://github.com/bluegraybox/erlang_intro/raw/master/parser/ruby_parser.gif" alt="ruby parsing sequence"></p>
<p>That much went well, and I felt pretty good about it.  I thought I had a nice clean separation of reponsibilities, and some pretty concise code.  But then I read <em>Hackers and Painters</em>.  It&#8217;s a collection of essays by Paul Graham, of HackerNews and Y Combinator fame.  Very smart guy.  You probably won&#8217;t agree with everything he says, but he&#8217;ll make you think.  Throughout the book, he plugs Lisp as the most powerful language in the world and the choice of all True Programmers.  Fine.  I&#8217;ll pick up that gauntlet and give it a shot.</p>
<p>I figured I&#8217;d take my little Ruby script and re-write it in Lisp, just sort of transliterate it.  Pull all the functions out, write them in Lisp; convert the objects to simpler data structures and pass them in as parameters.  That didn&#8217;t go so well.  It&#8217;s hard to explain quite why, but the end result was that the code was messy, convoluted, and incoherent, and still didn&#8217;t build certain structures correctly.  I&#8217;d lose track of where I was in tree and where I was in the input stream.  Trying to fix one case tended to break another.  Most of all, it <em>felt</em> wrong.  It felt like I was trying to jam a square peg into a round hole.  So how could I do this in a more &#8220;Lisp-y&#8221; way?</p>
<h3>Recursion</h3>
<p>Lisp is all about recursion.  You&#8217;d think that anything involving a tree structure would have to be recursive, but not really.  The way I was going about it was actually very linear: taking the input one line at a time and walking up and down the tree until I found where to attach it.  Recursion is really about breaking a problem into self-similar pieces, so you can define the whole in terms of its parts.  Ok, but what does that look like in the real world?</p>
<p>Well, for contrast, here&#8217;s the procedural way of transforming a list of things.  You take an input array, create an output array, and iterate through, mapping each input element to its corresponding output element.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="java"><pre class="de1"><span class="kw3">String</span><span class="br0">&#91;</span><span class="br0">&#93;</span> process<span class="br0">&#40;</span><span class="kw3">String</span><span class="br0">&#91;</span><span class="br0">&#93;</span> input<span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw3">String</span><span class="br0">&#91;</span><span class="br0">&#93;</span> output <span class="sy0">=</span> <span class="kw1">new</span> <span class="kw3">String</span><span class="br0">&#91;</span>input.<span class="me1">length</span><span class="br0">&#93;</span><span class="sy0">;</span>
    <span class="kw1">for</span> <span class="br0">&#40;</span><span class="kw4">int</span> i<span class="sy0">=</span><span class="nu0">0</span><span class="sy0">;</span> i <span class="sy0">&lt;</span> input.<span class="me1">length</span><span class="sy0">;</span> i<span class="sy0">++</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
        output<span class="br0">&#91;</span>i<span class="br0">&#93;</span> <span class="sy0">=</span> do_stuff<span class="br0">&#40;</span>input<span class="br0">&#91;</span>i<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy0">;</span>
    <span class="br0">&#125;</span>
    <span class="kw1">return</span> output<span class="sy0">;</span>
<span class="br0">&#125;</span></pre></div></div></div></div></div></div></div>


<p>The recursive approach is to focus on defining (1) how you transform each part, and (2) how each part relates to the whole.  The idiom here is to take the first thing off the input list, transform it, add it to the output list, and then invoke yourself with the new lists.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="kw3">process</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">First</span>|Rest<span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Output</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re5">NewFirst</span> <span class="sy3">=</span> <span class="re3">do_stuff</span><span class="br0">&#40;</span><span class="re5">First</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="kw3">process</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">NewFirst</span>|Output<span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">;</span></pre></div></div></div></div></div></div></div>


<p>This defines what you do for each element N, and how you get to N+1.  To round it out, you need to define your begin and end points.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1">    <span class="re5">Output</span> <span class="sy3">=</span> <span class="kw3">process</span><span class="br0">&#40;</span><span class="re5">Input</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
    <span class="kw3">process</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Output</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="kw5">lists</span>:<span class="re3">reverse</span><span class="br0">&#40;</span><span class="re5">Output</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>(It&#8217;s convention to add each element to the beginning of the output list, so you need to reverse it when you&#8217;re all done.<br />
It&#8217;s apparently more efficient.)</p>
<p>The key thing here is that this is a common idiom in Erlang.  Procedural and OO languages allow recursion, but you don&#8217;t often have a good reason to use it, so it remains this strange and intimidating concept.  If you do use it, you usually put comments all around it saying &#8220;Recursion happening here! Stand back! Do not touch!&#8221; In Erlang, it&#8217;s how you do <em>everything</em>.  Anything that you&#8217;d use any sort of loop structure for in another language, you do with recursion.  You get used to it pretty fast.</p>
<h3>Lisp</h3>
<p>So, back to the problem at hand: How do I do this parsing thing in a more recursive way?  It ended up being the classic math problem experience.  I beat my head against it for a couple hours, sketching out ideas in code, all of them abject failures.  Eventually I gave up and went to bed.  Lay there staring at the ceiling.  About twenty minutes later, I was just starting to drift off, and it hit me.  It was one of those solutions where you immediately know you&#8217;re right because it&#8217;s so simple and obvious in retrospect, and you feel like an idiot for not having thought of it sooner.</p>
<p>The first line in the input is the first node in the tree.  Every other line either belongs to one of its children, or one of its siblings.  So you can run through the lines until you hit one with the same indent as yours.  That&#8217;ll be your first sibling; everything before it belongs to your children.</p>
<p><img src="https://github.com/bluegraybox/erlang_intro/raw/master/parser/lisp_parser_1.png" alt="lisp step 1"></p>
<p>All you have to do now is recurse and apply the same logic to each block.  Your first child (if any) splits its list into its children and siblings.  Your first sibling (if any) does the same with its list.</p>
<p><img src="https://github.com/bluegraybox/erlang_intro/raw/master/parser/lisp_parser_2.png" alt="lisp step 2"></p>
<p>And so on&#8230;</p>
<p><img src="https://github.com/bluegraybox/erlang_intro/raw/master/parser/lisp_parser_3.png" alt="lisp step 3"></p>
<p>And so on&#8230;</p>
<p><img src="https://github.com/bluegraybox/erlang_intro/raw/master/parser/lisp_parser_4.png" alt="lisp step 4"></p>
<p>And so on&#8230;</p>
<p><img src="https://github.com/bluegraybox/erlang_intro/raw/master/parser/lisp_parser_5.png" alt="lisp step 5"></p>
<p>&#8230;Until you&#8217;re all the way down at the leaf nodes.  Here, the logic is trivial: No lines, no children, no siblings.  And you return back up the tree.</p>
<p>So what does the code look like?  Well, I don&#8217;t have time to teach you how to read Lisp.  Fortunately, at this point it occurred to me, &#8220;Hey, Erlang is a functional language, too.&#8221; Maybe porting from Lisp to Erlang would be fairly straightforward.  As it turned out, not only was the straight conversion easy,<br />
but I was also able to go back and rework bits to take advantage of Erlang&#8217;s pattern matching features to make it even cleaner and simpler.</p>
<h3>Erlang</h3>
<p>Here&#8217;s the core of the Erlang functionality.  We define records &#8211; data structures &#8211; for our input lines and output nodes.  We pop the first line off the list, and split the rest of it into child and sibling lines.  We then recurse on the child lines to get our child nodes, and on the sibling lines to get our sibling nodes.  We create a node with its list of children, add it to the front of its list of siblings, and return that.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="sy3">-</span><span class="re2">record</span><span class="br0">&#40;</span><span class="re1">line</span><span class="sy1">,</span> <span class="br0">&#123;</span>content<span class="sy1">,</span> indent<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy1">.</span>
<span class="sy3">-</span><span class="re2">record</span><span class="br0">&#40;</span><span class="kw3">node</span><span class="sy1">,</span> <span class="br0">&#123;</span>content<span class="sy1">,</span> children<span class="br0">&#125;</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">build_nodes</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">First</span>|Rest<span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="br0">&#123;</span><span class="re5">ChildLines</span><span class="sy1">,</span> <span class="re5">SiblingLines</span><span class="br0">&#125;</span> <span class="sy3">=</span>
        <span class="re3">split_list</span><span class="br0">&#40;</span><span class="re5">First</span><span class="re8">#</span><span class="re7">line</span><span class="sy1">.</span>indent<span class="sy1">,</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Rest</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re5">Children</span> <span class="sy3">=</span> <span class="re3">build_nodes</span><span class="br0">&#40;</span><span class="re5">ChildLines</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re5">Siblings</span> <span class="sy3">=</span> <span class="re3">build_nodes</span><span class="br0">&#40;</span><span class="re5">SiblingLines</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re5">Node</span> <span class="sy3">=</span> #<span class="kw3">node</span><span class="br0">&#123;</span>content<span class="sy3">=</span><span class="re5">First</span><span class="re8">#</span><span class="re7">line</span><span class="sy1">.</span>content<span class="sy1">,</span> children<span class="sy3">=</span><span class="re5">Children</span><span class="br0">&#125;</span><span class="sy1">,</span>
    <span class="br0">&#91;</span><span class="re5">Node</span>|Siblings<span class="br0">&#93;</span><span class="sy1">;</span>
&nbsp;
<span class="re3">build_nodes</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>The split_list function follows much the same pattern as our earlier recursion example.  All the lines start out in the sibling list; the child list is empty.  Instead of transforming each sibling line, it pops it off and adds it to the child list.  When it hits a line that&#8217;s not indented greater than the minimum, it pushes that back onto its siblings, and returns the two lists.  (Again, reversing the children because we&#8217;ve been adding them to the beginning of the list.) If that doesn&#8217;t happen before its sibling list is empty, it&#8217;s all children and no siblings.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">split_list</span><span class="br0">&#40;</span><span class="re5">MinIndent</span><span class="sy1">,</span> <span class="re5">Children</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">First</span>|Rest<span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw1">if</span> 
        <span class="re5">First</span><span class="re8">#</span><span class="re7">line</span><span class="sy1">.</span>indent <span class="sy3">&gt;</span> <span class="re5">MinIndent</span> <span class="sy1">-&gt;</span>
            <span class="re3">split_list</span><span class="br0">&#40;</span><span class="re5">MinIndent</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">First</span>|Children<span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Rest</span><span class="br0">&#41;</span><span class="sy1">;</span>
        true <span class="sy1">-&gt;</span>
            <span class="br0">&#123;</span><span class="kw5">lists</span>:<span class="re3">reverse</span><span class="br0">&#40;</span><span class="re5">Children</span><span class="br0">&#41;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">First</span>|Rest<span class="br0">&#93;</span><span class="br0">&#125;</span>
    <span class="kw1">end</span><span class="sy1">;</span>
&nbsp;
<span class="re3">split_list</span><span class="br0">&#40;</span><span class="re5">_Indent</span><span class="sy1">,</span> <span class="re5">Children</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="br0">&#123;</span><span class="kw5">lists</span>:<span class="re3">reverse</span><span class="br0">&#40;</span><span class="re5">Children</span><span class="br0">&#41;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#125;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>I&#8217;m not sure if that&#8217;s actually fewer lines of code than the equivalent procedural code, but it feels clearer.  The stop condition is unambiguous, as opposed to the usual &#8220;i >= list.length&#8221;.</p>
<h3>Bowling</h3>
<p>I stumbled across another good example in the Bowling Game.  The challenge is just to write a program to score a bowling game.  This is a classic beginner coding exercise.  It&#8217;s very self-contained, but it has just enough complexity and ambiguity to be interesting.</p>
<p>When you&#8217;re programming in OO languages, there&#8217;s a pretty obvious class structure.  You have Games and Frames and Rolls, and you calculate a score.  What makes this interesting is that spares and strikes cause rolls from future frames to be added to the score for that frame.  This gives you a bit of metaphor shear.  Rolls belong to one frame, but may be counted double or even triple.  Do you put that logic in the Frame class, requiring frames to know about their following frames?  Or do you put it in the Game, as the keeper of inter-frame knowledge?</p>
<p>I had written this in Python as part of a pair programming exercise about a year ago.  I was pretty happy with the results.  The code itself was fifty-some lines.  There was a clean separation of responsibilities.  The Frame class had all sorts of useful methods for querying its state.  The Game class hid all that and provided a clean interface for adding rolls and getting the score.</p>
<p>Then for an Erlang meetup, we did the same exercise.  This was the result:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re3">frame</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">0</span><span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<span class="re3">frame</span><span class="br0">&#40;</span><span class="re5">_BonusRolls</span><span class="sy1">,</span> <span class="nu0">11</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">Score</span><span class="sy1">;</span>
&nbsp;
<span class="re3">frame</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="nu0">10</span>|Rest<span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="br0">&#91;</span><span class="re5">Bonus1</span><span class="sy1">,</span> <span class="re5">Bonus2</span>|_<span class="br0">&#93;</span> <span class="sy3">=</span> <span class="re5">Rest</span><span class="sy1">,</span>
    <span class="re3">frame</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="nu0">10</span> <span class="sy3">+</span> <span class="re5">Bonus1</span> <span class="sy3">+</span> <span class="re5">Bonus2</span><span class="br0">&#41;</span><span class="sy1">;</span>
&nbsp;
<span class="re3">frame</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">First</span><span class="sy1">,</span><span class="re5">Second</span>|Rest<span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="kw1">when</span> <span class="br0">&#40;</span><span class="re5">First</span><span class="sy3">+</span><span class="re5">Second</span><span class="sy3">==</span><span class="nu0">10</span><span class="br0">&#41;</span><span class="sy1">-&gt;</span>
    <span class="br0">&#91;</span><span class="re5">Bonus1</span>|_<span class="br0">&#93;</span> <span class="sy3">=</span> <span class="re5">Rest</span><span class="sy1">,</span>
    <span class="re3">frame</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="nu0">10</span> <span class="sy3">+</span> <span class="re5">Bonus1</span><span class="br0">&#41;</span><span class="sy1">;</span>
&nbsp;
<span class="re3">frame</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">First</span><span class="sy1">,</span><span class="re5">Second</span>|Rest<span class="br0">&#93;</span><span class="sy1">,</span> <span class="re5">Frame</span><span class="sy1">,</span> <span class="re5">Score</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re3">frame</span><span class="br0">&#40;</span><span class="re5">Rest</span><span class="sy1">,</span> <span class="re5">Frame</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span> <span class="re5">Score</span> <span class="sy3">+</span> <span class="re5">First</span> <span class="sy3">+</span> <span class="re5">Second</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>That&#8217;s ten lines of code, a 5x improvement over Python.  And (again, once you get used to Erlang&#8217;s syntax) it&#8217;s amazingly clear.  frame() takes a list of remaining rolls, a frame number, and a total score.  The different definitions of frame() handle the end-of-game, strike, spare, and normal conditions.  Each consumes rolls, boosts the score, and recurses to the next frame.</p>
<p>So what about unit tests?  Here you go:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">test</span><span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re3">test</span><span class="br0">&#40;</span><span class="nu0">0</span><span class="sy1">,</span>   <span class="br0">&#91;</span><span class="nu0">0</span><span class="sy1">,</span><span class="nu0">0</span><span class="sy1">,</span> <span class="nu0">0</span><span class="sy1">,</span><span class="nu0">0</span><span class="sy1">,</span> <span class="nu0">0</span><span class="sy1">,</span><span class="nu0">0</span><span class="sy1">,</span> <span class="nu0">0</span><span class="sy1">,</span><span class="nu0">0</span><span class="sy1">,</span> <span class="nu0">0</span><span class="sy1">,</span><span class="nu0">0</span><span class="sy1">,</span> <span class="nu0">0</span><span class="sy1">,</span><span class="nu0">0</span><span class="sy1">,</span> <span class="nu0">0</span><span class="sy1">,</span><span class="nu0">0</span><span class="sy1">,</span> <span class="nu0">0</span><span class="sy1">,</span><span class="nu0">0</span><span class="sy1">,</span> <span class="nu0">0</span><span class="sy1">,</span><span class="nu0">0</span><span class="sy1">,</span> <span class="nu0">0</span><span class="sy1">,</span><span class="nu0">0</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">test</span><span class="br0">&#40;</span><span class="nu0">20</span><span class="sy1">,</span>  <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">test</span><span class="br0">&#40;</span><span class="nu0">150</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="nu0">5</span><span class="sy1">,</span><span class="nu0">5</span><span class="sy1">,</span> <span class="nu0">5</span><span class="sy1">,</span><span class="nu0">5</span><span class="sy1">,</span> <span class="nu0">5</span><span class="sy1">,</span><span class="nu0">5</span><span class="sy1">,</span> <span class="nu0">5</span><span class="sy1">,</span><span class="nu0">5</span><span class="sy1">,</span> <span class="nu0">5</span><span class="sy1">,</span><span class="nu0">5</span><span class="sy1">,</span> <span class="nu0">5</span><span class="sy1">,</span><span class="nu0">5</span><span class="sy1">,</span> <span class="nu0">5</span><span class="sy1">,</span><span class="nu0">5</span><span class="sy1">,</span> <span class="nu0">5</span><span class="sy1">,</span><span class="nu0">5</span><span class="sy1">,</span> <span class="nu0">5</span><span class="sy1">,</span><span class="nu0">5</span><span class="sy1">,</span> <span class="nu0">5</span><span class="sy1">,</span><span class="nu0">5</span><span class="sy1">,</span> <span class="nu0">5</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">test</span><span class="br0">&#40;</span><span class="nu0">47</span><span class="sy1">,</span>  <span class="br0">&#91;</span><span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">1</span><span class="sy1">,</span><span class="nu0">1</span><span class="sy1">,</span> <span class="nu0">10</span><span class="sy1">,</span> <span class="nu0">10</span> <span class="sy1">,</span><span class="nu0">9</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="re3">test</span><span class="br0">&#40;</span><span class="nu0">173</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="nu0">7</span><span class="sy1">,</span><span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">7</span><span class="sy1">,</span><span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">7</span><span class="sy1">,</span><span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">7</span><span class="sy1">,</span><span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">7</span><span class="sy1">,</span><span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">7</span><span class="sy1">,</span><span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">7</span><span class="sy1">,</span><span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">7</span><span class="sy1">,</span><span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">7</span><span class="sy1">,</span><span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">7</span><span class="sy1">,</span><span class="nu0">3</span><span class="sy1">,</span> <span class="nu0">10</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">,</span>
&nbsp;
<span class="re3">test</span><span class="br0">&#40;</span><span class="re5">Expected</span><span class="sy1">,</span> <span class="re5">Rolls</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw1">case</span> <span class="re3">score</span><span class="br0">&#40;</span><span class="re5">Rolls</span><span class="br0">&#41;</span> <span class="kw1">of</span>
        <span class="re5">Expected</span> <span class="sy1">-&gt;</span> <span class="kw5">io</span>:<span class="re3">fwrite</span><span class="br0">&#40;</span><span class="st0">&quot;Pass~n&quot;</span><span class="br0">&#41;</span><span class="sy1">;</span>
        <span class="re5">Scored</span> <span class="sy1">-&gt;</span> <span class="kw5">io</span>:<span class="re3">fwrite</span><span class="br0">&#40;</span><span class="st0">&quot;Fail: expected=~p, scored=~p~n&quot;</span><span class="sy1">,</span>
            <span class="br0">&#91;</span><span class="re5">Expected</span><span class="sy1">,</span> <span class="re5">Scored</span><span class="br0">&#93;</span><span class="br0">&#41;</span>
    <span class="kw1">end</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>That&#8217;s it: a list of test cases with expected result and input rolls; and a simple method for evaluating them.  There are unit test frameworks for Erlang, but why bother when it&#8217;s as simple as this?</p>
<h3>The Funhouse Mirror</h3>
<p>Looking back at the Python code, I realize that it spends lot of time on peripheral issues: What is the nature of a Frame?  How does it relate to the Frames around it?  Is it responsible for validating its inputs, or does the Game do that?  (Usually both, which makes for some redundancy.) Does it bear responsibility for calculating its own value, or does that also fall to the Game class?  What&#8217;s the &#8220;right&#8221; way to divide up functionality that involves two or more classes?  It gets very metaphysical.</p>
<p>And in the end, these questions have no direct bearing on the task of calculating the score.  They&#8217;re all about the model, which is just an intermediate stage between input and output.  You also tend to end up with a lot of &#8220;what if?&#8221; code: functions that could be useful, but aren&#8217;t actually used.  You get boilerplate accessor methods.  After working with Erlang for a bit, OO code seems to spend a lot of time talking about the problem without actually solving it.  You look at all these interlocking parts and think, &#8220;Well! It certainly is very busy, but what is it actually doing?&#8221; Erlang takes more up-front thought, but is it really a good sign that you can write a lot of OO model code without really understanding what you&#8217;re trying to accomplish?</p>
<p>So I say, Embrace the weirdness.  Give Erlang a shot.  Spend a few hours &#8211; it shouldn&#8217;t take long.  The syntax and idioms start to feel natural in a surprisingly short time.  Even if you never get to use it for work, it&#8217;ll change the way you think about programming.</p>
<p>Remember that you can start small, that you can write Erlang programs that aren&#8217;t distributed or concurrent.  You can write little shell scripts or file parsers or cgi scripts.  And you can be secure in the knowledge that you could scale if you had to, without having to significantly re-work your code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2011/09/18/erlang-your-new-favorite-scripting-language/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Bash Metaprogramming</title>
		<link>http://www.bluegraybox.com/blog/2011/08/05/bash-metaprogramming/</link>
		<comments>http://www.bluegraybox.com/blog/2011/08/05/bash-metaprogramming/#comments</comments>
		<pubDate>Sat, 06 Aug 2011 03:43:25 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[shell]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=162</guid>
		<description><![CDATA[My current gig is doing Java enterprise integration work. You&#8217;d think that that would involve writing a lot of Java code. Not so much. It&#8217;s mostly dicking around with XML config files to wire together a bunch of different tools and frameworks. I&#8217;ve actually written more lines of Bash script than Java code. In fact, [...]]]></description>
			<content:encoded><![CDATA[<p>My current gig is doing Java enterprise integration work. You&#8217;d think that that would involve writing a lot of Java code. Not so much. It&#8217;s mostly dicking around with XML config files to wire together a bunch of different tools and frameworks. I&#8217;ve actually written more lines of Bash script than Java code. In fact, I&#8217;ve spent a fair amount of time working on scripts, and they&#8217;ve more than repaid the effort.</p>
<p>I&#8217;m dealing with data that gets passed through layers and layers of components, shuttling to various web services and back. There&#8217;s all this dynamic XML configuration and auto-generated Java code. When something gets garbled in translation, it&#8217;s great to have a four-line script to send a bare-bones HTTP POST to a web service and see what comes back.</p>
<p>Deploying a new version of our code is this tedious and unforgiving process of ftping the code down from the staging server, unpacking it to a deployment directory, shutting down the web server, backing up the old version, copying the new version into place, and restarting the web server. It&#8217;s actually more complicated than that, but I forget all the details &#8211; because I don&#8217;t have to remember them. It&#8217;s all scripted. I just run my script and hit return a bunch.</p>
<p>Computers have great memory and terrible judgement. My scripts remember all the nitpicky details of what I have to do, but they stop and ask me whenever a decision has to be made. We work well together.</p>
<p>I&#8217;ve never really thought of myself as a &#8220;Bash programmer&#8221;. Scripting is just an adjunct to &#8220;doing stuff on Linux machines.&#8221; But I&#8217;ve been doing enough of it lately that I decided to actually treat Bash as a programming language: Learn more about what you can do with it, and try to create re-usable code instead of single-use scripts. It turns out it has a ton of features that I&#8217;ve never used. Most surprisingly, it even allows some limited metaprogramming. For example:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="bash"><pre class="de1">$ <span class="re2">name</span>=<span class="st0">&quot;Colin MacDonald&quot;</span>
$ <span class="re2">city</span>=<span class="st0">&quot;Arlington&quot;</span>
$ <span class="re2">state</span>=<span class="st0">&quot;VA&quot;</span>
$ <span class="kw3">echo</span> <span class="re1">$name</span>
Colin MacDonald
$ <span class="re2">vars</span>=<span class="st0">&quot;name city state&quot;</span>
$ <span class="kw1">for</span> x <span class="kw1">in</span> <span class="re1">$vars</span> ; <span class="kw1">do</span> <span class="kw3">echo</span> <span class="st0">&quot;<span class="es2">$x</span>=<span class="es3">${!x}</span>&quot;</span> ; <span class="kw1">done</span>
<span class="re2">name</span>=Colin MacDonald
<span class="re2">city</span>=Arlington
<span class="re2">state</span>=VA</pre></div></div></div></div></div></div></div>


<p>In the <code>for</code> loop, when <code>x</code> is &#8220;city&#8221;, <code>${!x}</code> is <code>$city</code>. Ok, clever, but what do you use it for? Well, it lets me save configuration settings to a file with a generic function that goes something like:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="bash"><pre class="de1"><span class="kw1">function</span> save_config <span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw1">for</span> x <span class="kw1">in</span> <span class="re1">$vars</span> ; <span class="kw1">do</span>
        <span class="kw3">echo</span> <span class="st0">&quot;<span class="es2">$x</span>=<span class="es1">\&quot;</span><span class="es3">${!x}</span><span class="es1">\&quot;</span>&quot;</span> <span class="sy0">&gt;&gt;</span> <span class="re1">$config_file</span>
    <span class="kw1">done</span>
<span class="br0">&#125;</span></pre></div></div></div></div></div></div></div>


<p>And gets called like so:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="bash"><pre class="de1">save_config <span class="st0">&quot;name city state&quot;</span></pre></div></div></div></div></div></div></div>


<p>I&#8217;ve been able to extend this sort of meta-variable handling to parsing command-line parameters and prompting the user for input, so I now have a reusable library for managing script configuration in a fairly clean way. Now my script can just have:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="bash"><pre class="de1">load_config
process_options <span class="st0">&quot;[d]=debug&quot;</span> <span class="st0">&quot;[n]=name [c]=city [s]=state&quot;</span> <span class="st0">&quot;$@&quot;</span>
confirm_config <span class="st0">&quot;[name]=<span class="es1">\&quot;</span>Name:<span class="es1">\&quot;</span> [city]=<span class="es1">\&quot;</span>City:<span class="es1">\&quot;</span> [state]=<span class="es1">\&quot;</span>State:<span class="es1">\&quot;</span>&quot;</span>
save_config <span class="st0">&quot;name city state&quot;</span></pre></div></div></div></div></div></div></div>


<p>When you run it, it sets the variables based on the command-line params, then prompts you to confirm the settings and add any missing ones.</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="bash"><pre class="de1">$ .<span class="sy0">/</span>my_script.sh  <span class="re5">-n</span> <span class="st0">&quot;John Smith&quot;</span>
Name: <span class="br0">&#91;</span>John Smith<span class="br0">&#93;</span> 
City: <span class="br0">&#91;</span><span class="br0">&#93;</span> Arlington
city changed to <span class="st_h">'Arlington'</span>
State: <span class="br0">&#91;</span><span class="br0">&#93;</span> VA
state changed to <span class="st_h">'VA'</span></pre></div></div></div></div></div></div></div>


<p>Those settings will be saved in the config file</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="bash"><pre class="de1">$ <span class="kw2">cat</span> .my_script.cfg 
<span class="re2">name</span>=<span class="st0">&quot;John Smith&quot;</span>
<span class="re2">city</span>=<span class="st0">&quot;Arlington&quot;</span>
<span class="re2">state</span>=<span class="st0">&quot;VA&quot;</span></pre></div></div></div></div></div></div></div>


<p>And the next time you run your script, you get</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="bash"><pre class="de1">$ .<span class="sy0">/</span>my_script.sh
Name: <span class="br0">&#91;</span>John Smith<span class="br0">&#93;</span> 
City: <span class="br0">&#91;</span>Arlington<span class="br0">&#93;</span> 
State: <span class="br0">&#91;</span>VA<span class="br0">&#93;</span></pre></div></div></div></div></div></div></div>


<p>In my world, these will be things like URLs and SOAP message definitions &#8211; things that will be different on each machine, and which I really only want to type in once. So, handy.</p>
<p>If you want to grab <a href="https://github.com/bluegraybox/examples/blob/master/bash/lib_config.sh">this library</a> and a <a href="https://github.com/bluegraybox/examples/blob/master/bash/template.sh">template of how to use it</a>, they&#8217;re up on <a href="https://github.com/">GitHub</a>. If you want to learn more about metaprogramming tricks in Bash, pop the hood and dig around in there. The syntax is a bit strange and can be very finicky, so there&#8217;s some hard-won knowledge baked into the library.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2011/08/05/bash-metaprogramming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Foreign Language Lessons, part 3</title>
		<link>http://www.bluegraybox.com/blog/2011/07/14/foreign-language-lessons-part-3/</link>
		<comments>http://www.bluegraybox.com/blog/2011/07/14/foreign-language-lessons-part-3/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 04:20:33 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=146</guid>
		<description><![CDATA[So, continuing on with the fun from last time, I went back to the my Lisp program and translated it into Erlang. Unlike the complete re-think I had to pull off in going from Ruby to Lisp, this was very straightforward. Here&#8217;s the meat of the Erlang code: And the equivalent Lisp: Erlang has obvious [...]]]></description>
			<content:encoded><![CDATA[<p>So, continuing on with the fun from <a href="http://www.bluegraybox.com/blog/2011/07/12/foreign-language-lessons-part-2/">last time</a>, I went back to the my <a href="http://www.bluegraybox.com/blog/2011/07/02/foreign-language-lessons/">Lisp program</a> and translated it into Erlang. Unlike the complete re-think I had to pull off in going from Ruby to Lisp, this was very straightforward.</p>
<p>Here&#8217;s the meat of <a href="https://github.com/bluegraybox/examples/blob/last-sequential/indent-parser/parse_indents.erl">the Erlang code</a>:</p>
<div id="gist-1083971" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="p">-</span><span class="ni">record</span><span class="p">(</span><span class="nl">line</span><span class="p">,</span> <span class="p">{</span><span class="n">content</span><span class="p">,</span> <span class="n">indent</span><span class="p">}).</span></div><div class='line' id='LC2'><span class="p">-</span><span class="ni">record</span><span class="p">(</span><span class="nl">node</span><span class="p">,</span> <span class="p">{</span><span class="n">content</span><span class="p">,</span> <span class="n">children</span><span class="p">}).</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'><span class="nf">parse_text_line</span><span class="p">(</span><span class="nv">Text</span><span class="p">)</span> <span class="o">-&gt;</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c">%% converts &quot;    text&quot; to (:content &quot;text&quot; :indent 4)</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nv">Content</span> <span class="o">=</span> <span class="nn">string</span><span class="p">:</span><span class="n">strip</span><span class="p">(</span><span class="nn">string</span><span class="p">:</span><span class="n">strip</span><span class="p">(</span><span class="nv">Text</span><span class="p">,</span> <span class="n">left</span><span class="p">),</span> <span class="n">left</span><span class="p">,</span> <span class="sc">$\t</span><span class="p">),</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nv">Indent</span> <span class="o">=</span> <span class="nb">length</span><span class="p">(</span><span class="nv">Text</span><span class="p">)</span> <span class="o">-</span> <span class="nb">length</span><span class="p">(</span><span class="nv">Content</span><span class="p">),</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nl">#line</span><span class="p">{</span><span class="n">content</span><span class="o">=</span><span class="nn">string</span><span class="p">:</span><span class="n">strip</span><span class="p">(</span><span class="nv">Content</span><span class="p">,</span> <span class="n">right</span><span class="p">,</span> <span class="sc">$\n</span><span class="p">),</span> <span class="n">indent</span><span class="o">=</span><span class="nv">Indent</span><span class="p">}.</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'><span class="c">%% Split a list of lines in two, breaking on the first line whose indent is =&lt; the minimum.</span></div><div class='line' id='LC11'><span class="nf">split_list</span><span class="p">(_</span><span class="nv">MinIndent</span><span class="p">,</span> <span class="nv">List1</span><span class="p">,</span> <span class="p">[])</span> <span class="o">-&gt;</span> <span class="p">[</span><span class="nn">lists</span><span class="p">:</span><span class="n">reverse</span><span class="p">(</span><span class="nv">List1</span><span class="p">),</span> <span class="p">[]];</span></div><div class='line' id='LC12'><span class="nf">split_list</span><span class="p">(</span><span class="nv">MinIndent</span><span class="p">,</span> <span class="nv">List1</span><span class="p">,</span> <span class="p">[</span><span class="nv">First</span><span class="p">|</span><span class="nv">Rest</span><span class="p">])</span> <span class="k">when</span> <span class="nv">First</span><span class="nl">#line.indent</span> <span class="o">=&lt;</span> <span class="nv">MinIndent</span> <span class="o">-&gt;</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">[</span><span class="nn">lists</span><span class="p">:</span><span class="n">reverse</span><span class="p">(</span><span class="nv">List1</span><span class="p">),</span> <span class="p">[</span><span class="nv">First</span><span class="p">|</span><span class="nv">Rest</span><span class="p">]];</span></div><div class='line' id='LC14'><span class="nf">split_list</span><span class="p">(</span><span class="nv">MinIndent</span><span class="p">,</span> <span class="nv">List1</span><span class="p">,</span> <span class="p">[</span><span class="nv">First</span><span class="p">|</span><span class="nv">Rest</span><span class="p">])</span> <span class="o">-&gt;</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">split_list</span><span class="p">(</span><span class="nv">MinIndent</span><span class="p">,</span> <span class="p">[</span><span class="nv">First</span><span class="p">|</span><span class="nv">List1</span><span class="p">],</span> <span class="nv">Rest</span><span class="p">).</span></div><div class='line' id='LC16'><br/></div><div class='line' id='LC17'><span class="c">%% Parse a list of &#39;line&#39; record into a tree structure, based on indent</span></div><div class='line' id='LC18'><span class="nf">build_nodes</span><span class="p">([])</span> <span class="o">-&gt;</span> <span class="p">[];</span></div><div class='line' id='LC19'><span class="nf">build_nodes</span><span class="p">([</span><span class="nv">First</span><span class="p">|</span><span class="nv">Rest</span><span class="p">])</span> <span class="o">-&gt;</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">[</span><span class="nv">ChildLines</span><span class="p">,</span> <span class="nv">SiblingLines</span><span class="p">]</span> <span class="o">=</span> <span class="n">split_list</span><span class="p">(</span><span class="nv">First</span><span class="nl">#line.indent</span><span class="p">,</span> <span class="p">[],</span> <span class="nv">Rest</span><span class="p">),</span></div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nv">Children</span> <span class="o">=</span> <span class="n">build_nodes</span><span class="p">(</span><span class="nv">ChildLines</span><span class="p">),</span></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nv">Siblings</span> <span class="o">=</span> <span class="n">build_nodes</span><span class="p">(</span><span class="nv">SiblingLines</span><span class="p">),</span></div><div class='line' id='LC23'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nv">Node</span> <span class="o">=</span> <span class="nl">#node</span><span class="p">{</span><span class="n">content</span><span class="o">=</span><span class="nv">First</span><span class="nl">#line.content</span><span class="p">,</span> <span class="n">children</span><span class="o">=</span><span class="nv">Children</span><span class="p">},</span></div><div class='line' id='LC24'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">[</span><span class="nv">Node</span><span class="p">|</span><span class="nv">Siblings</span><span class="p">].</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1083971/7ecca424eb67f2eb1bd17bc1f715e2dfd443bd36/parse_indents.erl" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1083971#file_parse_indents.erl" style="float:right;margin-right:10px;color:#666">parse_indents.erl</a>
            <a href="https://gist.github.com/1083971">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>And the equivalent <a href="https://github.com/bluegraybox/examples/blob/master/indent-parser/parse-indents.lisp">Lisp</a>:</p>
<div id="gist-1083966" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="p">(</span><span class="nb">defun</span> <span class="nv">parse-text-line</span> <span class="p">(</span><span class="nv">line</span><span class="p">)</span></div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="c1">;; converts &quot;    text&quot; to (:content &quot;text&quot; :indent 4)</span></div><div class='line' id='LC3'>&nbsp;&nbsp;<span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nv">content</span> <span class="p">(</span><span class="nb">string-left-trim</span> <span class="o">&#39;</span><span class="p">(</span><span class="sc">#\Space</span> <span class="sc">#\Tab</span><span class="p">)</span> <span class="nv">line</span><span class="p">)))</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="nb">list</span> <span class="ss">:content</span> <span class="nv">content</span> <span class="ss">:indent</span> <span class="p">(</span><span class="nb">-</span> <span class="p">(</span><span class="nb">length</span> <span class="nv">line</span><span class="p">)</span> <span class="p">(</span><span class="nb">length</span> <span class="nv">content</span><span class="p">)))))</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'><span class="p">(</span><span class="nb">defun</span> <span class="nv">split-list</span> <span class="p">(</span><span class="nv">criterion</span> <span class="nv">data-list</span><span class="p">)</span></div><div class='line' id='LC7'>&nbsp;&nbsp;<span class="c1">;; break a list into two lists; the second begins with the first element that matches the criterion.</span></div><div class='line' id='LC8'>&nbsp;&nbsp;<span class="p">(</span><span class="k">if</span> <span class="nv">data-list</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="k">if</span> <span class="p">(</span><span class="nb">funcall</span> <span class="nv">criterion</span> <span class="p">(</span><span class="nb">first</span> <span class="nv">data-list</span><span class="p">))</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="nb">list</span> <span class="p">()</span> <span class="nv">data-list</span><span class="p">)</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nv">me</span> <span class="p">(</span><span class="nb">pop</span> <span class="nv">data-list</span><span class="p">)))</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nv">chunks</span> <span class="p">(</span><span class="nv">split-list</span> <span class="nv">criterion</span> <span class="nv">data-list</span><span class="p">)))</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="nb">push</span> <span class="nv">me</span> <span class="p">(</span><span class="nb">first</span> <span class="nv">chunks</span><span class="p">))</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nv">chunks</span><span class="p">)))</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="nb">list</span> <span class="p">()</span> <span class="p">())))</span></div><div class='line' id='LC16'><br/></div><div class='line' id='LC17'><span class="p">(</span><span class="nb">defun</span> <span class="nv">build-nodes</span> <span class="p">(</span><span class="nv">lines</span><span class="p">)</span></div><div class='line' id='LC18'>&nbsp;&nbsp;<span class="p">(</span><span class="k">if</span> <span class="nv">lines</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="k">let*</span> <span class="p">((</span><span class="nv">me</span> <span class="p">(</span><span class="nb">pop</span> <span class="nv">lines</span><span class="p">))</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">;; split off our children from the rest of the lines.</span></div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">;; the first line with an indent &lt;= ours is a sibling, not a child</span></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="nv">chunks</span> <span class="p">(</span><span class="nv">split-list</span> <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nv">x</span><span class="p">)</span> <span class="p">(</span><span class="nb">&lt;=</span> <span class="p">(</span><span class="nb">getf</span> <span class="nv">x</span> <span class="ss">:indent</span><span class="p">)</span> <span class="p">(</span><span class="nb">getf</span> <span class="nv">me</span> <span class="ss">:indent</span><span class="p">)))</span> <span class="nv">lines</span><span class="p">)))</span></div><div class='line' id='LC23'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nv">children</span> <span class="p">(</span><span class="nv">build-nodes</span> <span class="p">(</span><span class="nb">pop</span> <span class="nv">chunks</span><span class="p">)))</span></div><div class='line' id='LC24'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="nv">siblings</span> <span class="p">(</span><span class="nv">build-nodes</span> <span class="p">(</span><span class="nb">pop</span> <span class="nv">chunks</span><span class="p">))))</span></div><div class='line' id='LC25'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nv">node</span> <span class="p">(</span><span class="nb">list</span> <span class="ss">:content</span> <span class="p">(</span><span class="nb">getf</span> <span class="nv">me</span> <span class="ss">:content</span><span class="p">))))</span></div><div class='line' id='LC26'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="k">if</span> <span class="nv">children</span> <span class="p">(</span><span class="nb">setf</span> <span class="p">(</span><span class="nb">getf</span> <span class="nv">node</span> <span class="ss">:children</span><span class="p">)</span> <span class="nv">children</span><span class="p">))</span></div><div class='line' id='LC27'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">;; (format t &quot;~a~%&quot; (getf node :content))</span></div><div class='line' id='LC28'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">(</span><span class="nb">push</span> <span class="nv">node</span> <span class="nv">siblings</span><span class="p">))))</span></div><div class='line' id='LC29'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="no">nil</span><span class="p">))</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1083966/a0e0adbe179bd04d820a40fc4456d333b96054a9/parse-indents.lisp" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1083966#file_parse_indents.lisp" style="float:right;margin-right:10px;color:#666">parse-indents.lisp</a>
            <a href="https://gist.github.com/1083966">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Erlang has obvious Lisp roots, so most of the concepts translated 1-for-1. (I didn&#8217;t have any macros in my Lisp code, which might have made that hairier.) Most of it was changing dashes to underscores and moving parentheses around, but Erlang has some new features of interest.</p>
<h3>Pattern Matching</h3>
<p>Most of the Erlang functions take advantage of its pattern matching. This is a more extreme form of the method overloading that Java developers are familiar with. Erlang does allow varying numbers of parameters, as in</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">show_indented</span><span class="br0">&#40;</span><span class="re5">Nodes</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re3">show_indented</span><span class="br0">&#40;</span><span class="re5">Nodes</span><span class="sy1">,</span> <span class="nu0">0</span><span class="br0">&#41;</span><span class="sy1">.</span>
<span class="re3">show_indented</span><span class="br0">&#40;</span><span class="re5">Nodes</span><span class="sy1">,</span> <span class="re5">Indent</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="sy1">...</span></pre></div></div></div></div></div></div></div>


<p>where the one-parameter version just calls the two-parameter version with a default indent. But more interestingly, it lets you define functions by the parameter <em>values</em>, as we see here:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">build_nodes</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="br0">&#91;</span><span class="br0">&#93;</span><span class="sy1">;</span>
<span class="re3">build_nodes</span><span class="br0">&#40;</span><span class="re5">Lines</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="sy1">...</span></pre></div></div></div></div></div></div></div>


<p>The first build_nodes function matches when it&#8217;s passed an empty array. If any other value is passed, it fails to match the first version and tries the second. The second matches any parameter, and assigns its value to the Lines variable. The really wacky case of this is in the definition of</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="re3">main</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="br0">&#91;</span>$\:|FuncName<span class="br0">&#93;</span>|Filenames<span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="sy1">...</span>
<span class="re3">main</span><span class="br0">&#40;</span><span class="re5">Filenames</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="sy1">...</span></pre></div></div></div></div></div></div></div>


<p>The first one only matches a list whose first element is a string beginning with a &#8216;:&#8217; (&#8220;:my_function&#8221;), and handily assigns the rest of the string to the FuncName variable (FuncName = &#8220;my_function&#8221;) and all the other arguments to Filenames. No match, and it just assigns the whole argument list to Filenames. You could implement that functionality in any other language, but this expression is very concise and clear, very declarative.</p>
<p>The case clause works in a similar way:</p>


<div class="wp-geshi-highlight-wrap5"><div class="wp-geshi-highlight-wrap4"><div class="wp-geshi-highlight-wrap3"><div class="wp-geshi-highlight-wrap2"><div class="wp-geshi-highlight-wrap"><div class="wp-geshi-highlight"><div class="erlang"><pre class="de1"><span class="kw1">case</span> <span class="re5">Node</span><span class="re8">#</span><span class="kw3">node</span><span class="sy1">.</span>children <span class="kw1">of</span>
        <span class="br0">&#91;</span><span class="br0">&#93;</span> <span class="sy1">-&gt;</span> <span class="kw5">io</span>:<span class="re3">fwrite</span><span class="br0">&#40;</span><span class="st0">&quot;~s~n&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">NodePath</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">;</span>
        <span class="re5">Children</span> <span class="sy1">-&gt;</span> <span class="re3">show_path</span><span class="br0">&#40;</span><span class="re5">Children</span><span class="sy1">,</span> <span class="re5">NodePath</span><span class="br0">&#41;</span>
    <span class="kw1">end</span></pre></div></div></div></div></div></div></div>


<p>This says, &#8220;If node&#8217;s children are an empty list, write out the node path; otherwise, assign them to Children, and pass that to show_path() along with NodePath.</p>
<p>On the whole, as odd as Erlang&#8217;s syntax is, I find it friendlier than Lisp&#8217;s. The pattern matching is weird at first, but very elegant and powerful once you wrap your head around it. I&#8217;d be interested to know the reaction of someone new to programming. I suspect they&#8217;d be less thrown by the syntactic quirkiness &#8211; the arrows and the comma vs. semicolon vs. period for line endings.</p>
<h3>Spawn!</h3>
<p>But all this is not why I&#8217;m learning Erlang. If it were just a stylistic improvement over Lisp, that wouldn&#8217;t justify its existence. We&#8217;re here for crazy parallel processing hijinks. So ok, here, let me re-write this so that it spawns a new process for every node.  When the node is done building its children and siblings, it sends a message with all its data to its parent node, and so on up and down the tree. Ready? Here we go&#8230;</p>
<div id="gist-1083968" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="nf">build_nodes</span><span class="p">(</span><span class="nv">Parent</span><span class="p">,</span> <span class="nv">Group</span><span class="p">,</span> <span class="p">[])</span> <span class="o">-&gt;</span> <span class="nv">Parent</span> <span class="o">!</span> <span class="p">{</span><span class="nv">Group</span><span class="p">,</span> <span class="p">[]};</span></div><div class='line' id='LC2'><span class="nf">build_nodes</span><span class="p">(</span><span class="nv">Parent</span><span class="p">,</span> <span class="nv">Group</span><span class="p">,</span> <span class="nv">Lines</span><span class="p">)</span> <span class="o">-&gt;</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">[</span><span class="nv">First</span><span class="p">|</span><span class="nv">Rest</span><span class="p">]</span> <span class="o">=</span> <span class="nv">Lines</span><span class="p">,</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c">%% split off our children from the rest of the Lines.</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="c">%% the first line with an indent =&lt; ours is a sibling, not a child</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nv">Criterion</span> <span class="o">=</span> <span class="k">fun</span><span class="p">(</span><span class="nv">X</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nv">X</span><span class="nl">#line.indent</span> <span class="o">=&lt;</span> <span class="nv">First</span><span class="nl">#line.indent</span> <span class="k">end</span><span class="p">,</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">[</span><span class="nv">ChildLines</span><span class="p">,</span> <span class="nv">SiblingLines</span><span class="p">]</span> <span class="o">=</span> <span class="n">split_list</span><span class="p">(</span><span class="nv">Criterion</span><span class="p">,</span> <span class="nv">Rest</span><span class="p">),</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nb">spawn</span><span class="p">(</span><span class="o">?</span><span class="nv">MODULE</span><span class="p">,</span> <span class="n">build_nodes</span><span class="p">,</span> <span class="p">[</span><span class="n">self</span><span class="p">(),</span> <span class="n">children</span><span class="p">,</span> <span class="nv">ChildLines</span><span class="p">]),</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nb">spawn</span><span class="p">(</span><span class="o">?</span><span class="nv">MODULE</span><span class="p">,</span> <span class="n">build_nodes</span><span class="p">,</span> <span class="p">[</span><span class="n">self</span><span class="p">(),</span> <span class="n">siblings</span><span class="p">,</span> <span class="nv">SiblingLines</span><span class="p">]),</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">receive</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span><span class="n">children</span><span class="p">,</span> <span class="nv">Children</span><span class="p">}</span> <span class="o">-&gt;</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nv">Node</span> <span class="o">=</span> <span class="nl">#node</span><span class="p">{</span><span class="n">content</span><span class="o">=</span><span class="nv">First</span><span class="nl">#line.content</span><span class="p">,</span> <span class="n">children</span><span class="o">=</span><span class="nv">Children</span><span class="p">}</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">end</span><span class="p">,</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">receive</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="p">{</span><span class="n">siblings</span><span class="p">,</span> <span class="nv">Siblings</span><span class="p">}</span> <span class="o">-&gt;</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nn">io</span><span class="p">:</span><span class="n">fwrite</span><span class="p">(</span> <span class="s">&quot;[</span><span class="si">~s</span><span class="s">] </span><span class="si">~p~n</span><span class="s">&quot;</span><span class="p">,</span> <span class="p">[</span><span class="nv">Node</span><span class="nl">#node.content</span><span class="p">,</span> <span class="n">self</span><span class="p">()]),</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="nv">Parent</span> <span class="o">!</span> <span class="p">{</span><span class="nv">Group</span><span class="p">,</span> <span class="p">[</span><span class="nv">Node</span><span class="p">|</span><span class="nv">Siblings</span><span class="p">]}</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">end</span><span class="p">.</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1083968/0bfd5c003f1c914e3e519d830cf7b4448743068e/parse_indents.erl" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1083968#file_parse_indents.erl" style="float:right;margin-right:10px;color:#666">parse_indents.erl</a>
            <a href="https://gist.github.com/1083968">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p><a href="https://github.com/bluegraybox/examples/blob/first-concurrent/indent-parser/parse_indents.erl">Here&#8217;s the full thing</a>, but that&#8217;s about it. Instead of calling build_nodes() directly, we spawn them off and wait for the results. Instead of just returning our list of nodes, we send it to our Parent. (&#8220;Group&#8221; is just to keep children and siblings separate.) If you <a href="https://github.com/bluegraybox/examples/commit/a9492999a2230bbd8670bb90886e11a25fb44dc1#indent-parser/parse_indents.erl">look at the diff</a>, you&#8217;ll see a couple more minor things, but that&#8217;s all there is to the functional change.</p>
<p>So Erlang is surprisingly useful as a general-purpose scripting language. Probably not the first tool I&#8217;d reach for, but it doesn&#8217;t suck. And all of its limitations and eccentricities pay off when you start spawing processes. They straightjacket you into designing something that&#8217;s easily parallelized. I&#8217;m imagining trying to do a similar conversion in Java, where I&#8217;d be building a shared data structure and having to manage synchronization, thread completion, ordering results, and all that. Bleah.</p>
<p><em>(I have to point out that this is actually a bad example &#8211; this is not the kind of processing you want to parallelize. It schleps around a fair amount of data, and does very little processing. You really want that the other way around.)</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2011/07/14/foreign-language-lessons-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Foreign Language Lessons, part 2</title>
		<link>http://www.bluegraybox.com/blog/2011/07/12/foreign-language-lessons-part-2/</link>
		<comments>http://www.bluegraybox.com/blog/2011/07/12/foreign-language-lessons-part-2/#comments</comments>
		<pubDate>Tue, 12 Jul 2011 06:20:27 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=136</guid>
		<description><![CDATA[So, last time when I was talking about Lisp, I said that even if I didn&#8217;t end up using it, I hoped I might learn things from it that I could apply to other languages. I kinda had one in mind when I said it, and that one was Erlang. What? Erlang was developed back [...]]]></description>
			<content:encoded><![CDATA[<p>So, last time when I was talking about Lisp, I said that even if I didn&#8217;t end up using it, I hoped I might learn things from it that I could apply to other languages.  I kinda had one in mind when I said it, and that one was Erlang.</p>
<p>What?</p>
<p>Erlang was developed back in the 80s for programming telephone switching equipment.  That sounds pretty bizarrely specialized, right?  The problem they had was pretty much unique back then.  They had all these machines that had to talk to each other.  The individual messages, the requests they had to process, were relatively simple, but the system as a whole had to deal with an absolutely ludicrous volume of them and be perfectly reliable.  You probably make hundreds, if not thousands, of phone calls a year.  If even two or three of them got dropped, you&#8217;d say your phone system is pretty crappy. &#8220;It keeps dropping calls.&#8221; And if the whole system went down for like an hour, they&#8217;d never hear the end of it.</p>
<p>These days, a lot of people have this problem.  Not just phone companies, but pretty much anyone who runs a popular web site or instant messaging service.  A lot of enterprise software now relies on a &#8220;message bus&#8221; to handle communications between various chunks of code on different servers.  Anything having to do with credit card processing or financial markets also needs that cocktail of high volume and high availability.</p>
<p>So what&#8217;s so special about Erlang?</p>
<p>Erlang was built from the ground up with this sort of thing in mind, not just as a concern but as its <em>raison d&#8217;etre</em>.  There are really basic things that Erlang doesn&#8217;t let you do because they cause problems at scale in a massively multi-processing environment.  Like, it doesn&#8217;t let you modify data structures.  Once you&#8217;ve created them, you can copy them over and change them on the way, but you can&#8217;t change the original.  Why? Because that forces you to communicate the change explicitly, and nobody has to worry about data getting yanked out from under them.</p>
<p>That&#8217;s the programming equivalent of rugby players taping their ears to their heads.  The fact that people feel the need to do that tells you something about the seriousness of the situation.</p>
<p>On the other hand, Erlang has features that make it easier to write these sorts of massively concurrent and robust programs.  Spinning off a new process is trivial, a single command, as is sending messages to it and even registering it as a service so that other processes can talk to it.  Doing that on a remote machine isn&#8217;t much more than adding its name or IP to the command.  I&#8217;ve done that sort of thing in Java, but holy crap it&#8217;s a lot of hassle.</p>
<p>The fact that this is a simple and routine part of Erlang programming also tells you something about the nature of the situation.</p>
<p>The <em>crazy</em> thing that Erlang lets you do (again, easily) that I haven&#8217;t seen in any other language is that it lets you update code while it&#8217;s running.  This is not to be confused with the half-assed thing Java application servers do: If they&#8217;re running in &#8220;development mode&#8221; (<em>so</em> not recommended for production use), they can recompile updated JSPs; or they can shut down your whole app and restart it, leaking memory like a sieve the whole while.  In Erlang, all these separate processes can individually reload their code whenever it suits them.  You don&#8217;t have to shut down the server.  You don&#8217;t have to coordinate all the processes in some way.  You just set it up so that the next time a process does its thing, it does it with the new version of the code.  Here&#8217;s what it looks like:</p>
<div id="gist-1074932" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="p">-</span><span class="ni">module</span><span class="p">(</span><span class="n">countdown</span><span class="p">).</span></div><div class='line' id='LC2'><span class="p">-</span><span class="ni">export</span><span class="p">([</span><span class="n">init</span><span class="o">/</span><span class="mi">0</span><span class="p">,</span> <span class="n">reload</span><span class="o">/</span><span class="mi">0</span><span class="p">]).</span></div><div class='line' id='LC3'><span class="p">-</span><span class="ni">export</span><span class="p">([</span><span class="n">tick</span><span class="o">/</span><span class="mi">1</span><span class="p">]).</span>  <span class="c">% so we can spawn this properly.</span></div><div class='line' id='LC4'><br/></div><div class='line' id='LC5'><span class="c">%% spawn a countdown process with a default start time of 10 seconds.</span></div><div class='line' id='LC6'><span class="nf">init</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="n">init</span><span class="p">(</span><span class="mi">10</span><span class="p">).</span></div><div class='line' id='LC7'><span class="nf">init</span><span class="p">(</span><span class="nv">Time</span><span class="p">)</span> <span class="o">-&gt;</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nb">register</span><span class="p">(</span><span class="n">ticker</span><span class="p">,</span> <span class="nb">spawn</span><span class="p">(</span><span class="o">?</span><span class="nv">MODULE</span><span class="p">,</span> <span class="n">tick</span><span class="p">,</span> <span class="p">[</span><span class="nv">Time</span><span class="p">])).</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'><span class="nf">tick</span><span class="p">(</span><span class="nv">Time</span><span class="p">)</span> <span class="k">when</span> <span class="nv">Time</span> <span class="o">&gt;=</span> <span class="mi">0</span> <span class="o">-&gt;</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nn">io</span><span class="p">:</span><span class="n">format</span><span class="p">(</span><span class="s">&quot;Tick </span><span class="si">~p~n</span><span class="s">&quot;</span><span class="p">,</span> <span class="p">[</span><span class="nv">Time</span><span class="p">]),</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nn">timer</span><span class="p">:</span><span class="n">sleep</span><span class="p">(</span><span class="mi">999</span><span class="p">),</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">receive</span> <span class="n">reload</span> <span class="o">-&gt;</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">?</span><span class="nv">MODULE</span><span class="p">:</span><span class="n">tick</span><span class="p">(</span><span class="nv">Time</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">after</span> <span class="mi">1</span> <span class="o">-&gt;</span> <span class="n">tick</span><span class="p">(</span><span class="nv">Time</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">end</span><span class="p">;</span></div><div class='line' id='LC17'><span class="nf">tick</span><span class="p">(_</span><span class="nv">StartTime</span><span class="p">)</span> <span class="o">-&gt;</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="nn">io</span><span class="p">:</span><span class="n">format</span><span class="p">(</span><span class="s">&quot;Boom.</span><span class="si">~n</span><span class="s">&quot;</span><span class="p">,</span> <span class="p">[]),</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">done</span><span class="p">.</span></div><div class='line' id='LC20'><br/></div><div class='line' id='LC21'><span class="nf">reload</span><span class="p">()</span> <span class="o">-&gt;</span></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">ticker</span> <span class="o">!</span> <span class="n">reload</span><span class="p">.</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1074932/6577d99e435da75217d56004da4ccc171e72a815/countdown.erl" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1074932#file_countdown.erl" style="float:right;margin-right:10px;color:#666">countdown.erl</a>
            <a href="https://gist.github.com/1074932">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>(Calling &#8220;?MODULE:tick()&#8221; causes the code to reload; plain &#8220;tick()&#8221; doesn&#8217;t. <a href="https://gist.github.com/1074932">Full example with alternate version and commentary.</a>)</p>
<p>The syntax probably looks kinda foreign, but simple enough that you can puzzle it out.  It just creates a countdown timer called &#8220;ticker&#8221;, but it comes with a reload command that tells it to update itself.  In the middle of counting down, you could swap in a new version that prints something different, or counts slower, or starts counting up.  It&#8217;s a trivial example, but that&#8217;s the point: it&#8217;s <em>trivial</em>.  Doing this in any other language would be somewhere between mind-bendingly complicated and flat-out impossible.  It certainly wouldn&#8217;t be something you&#8217;d do to make your program <em>more</em> reliable.  But Erlang has this whole infrastructure for not only updating your application while it&#8217;s running, but rolling back to the old version if you find you&#8217;ve screwed something up.</p>
<p>So Erlang is technologically cool, and useful in an increasingly broad range of applications.  But part of the appeal for me is also that it&#8217;s kinda weird.  As with Lisp, the programming toolkit is not like most other languages, and it forces me to think about problems in a very different way.  That makes it more interesting as a hobby, and it may also make it more valuable as a professional skill.  There&#8217;s a lot of demand for Java, but there&#8217;s also a lot of competition.  Erlang is more of a gamble.  It may not catch on, but if it does, all that weirdness is going to thin the competition.</p>
<p>Until then, it also means that the Erlang community is mostly made up of people who actually love programming.  They&#8217;re not just trying to get a job.  They&#8217;re smart and passionate about what they do.  They&#8217;re fun to hang out with and they seem to like beer.  So worst case, I&#8217;ll have fun learning it.</p>
<p>(Most of Paul Graham&#8217;s older <a href="http://www.paulgraham.com/articles.html">essays</a> about why you should use Lisp also apply to Erlang.)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2011/07/12/foreign-language-lessons-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

