<?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 &#187; software</title>
	<atom:link href="http://www.bluegraybox.com/blog/category/software/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bluegraybox.com/blog</link>
	<description>so much to do, so little time...</description>
	<lastBuildDate>Tue, 27 Dec 2011 00:55:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<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[software]]></category>
		<category><![CDATA[erlang]]></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[software]]></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[software]]></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[software]]></category>
		<category><![CDATA[erlang]]></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[software]]></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[software]]></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[software]]></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>
		<item>
		<title>Foreign Language Lessons</title>
		<link>http://www.bluegraybox.com/blog/2011/07/02/foreign-language-lessons/</link>
		<comments>http://www.bluegraybox.com/blog/2011/07/02/foreign-language-lessons/#comments</comments>
		<pubDate>Sat, 02 Jul 2011 19:44:39 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[software]]></category>
		<category><![CDATA[lisp]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=132</guid>
		<description><![CDATA[I've been tinkering around with Lisp in my spare time lately. My hope was that it would force me to think differently, and it did.]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been tinkering around with <a href="http://en.wikipedia.org/wiki/Lisp_(programming_language)">Lisp</a> in my spare time lately. I recently finally got around to reading <a href="http://www.paulgraham.com/articles.html">Paul Graham&#8217;s</a> <a href="http://www.amazon.com/Hackers-Painters-Big-Ideas-Computer/dp/1449389554"><em>Hackers and Painters</em></a>. He talks a lot about how Lisp was his business&#8217;s competitive advantage (he made his bankroll on what became <a href="http://smallbusiness.yahoo.com/ecommerce/">Yahoo! Stores</a> and now runs <a href="http://news.ycombinator.com/">Hacker News</a> and <a href="http://ycombinator.com/">Y Combinator</a>), and how it&#8217;s both the mark and maker of really <em>good</em> programmers. I&#8217;ve always written it off as being an &#8220;academic&#8221; language, but he convinced me to give it a try. I have no expectation of actually using it professionally, but I hoped that I might learn something that would be applicable in other languages.</p>
<p>Lisp is the Latin of programming languages. It&#8217;s been around forever (since 1958, which is the paleolithic era for programming). It never really caught on, outside of niche applications and user groups, but it&#8217;s never quite died out, and it seems to be enjoying a resurgence. It&#8217;s also inspired other languages, like Ruby and Erlang, that I&#8217;ve gotten interested in, and people who know it say that even those just have watered-down, training-wheel versions of features found in Lisp.</p>
<p>I had a good little sample problem to try it out on. I&#8217;d been sketching out a to-do list tool, something that would let me keep track of projects, nested sub-projects, and tasks. The key was that I wanted to keep the data in plain text, in some readable format, but also be able to munge it &#8211; filter and sort it and such; some sort of simple wiki-style <a href="http://en.wikipedia.org/wiki/Markdown">markup language</a>. The first part of this was the structure: I&#8217;d have a project, with its sub-projects indented below it, and their sub-projects and tasks indented further. The parser would build up a tree data structure. So you&#8217;d have plain text input that looks like this:<br />
<img src="https://github.com/bluegraybox/examples/raw/master/indent-parser/input.png" /><br />
and you&#8217;d want to end up with a data structure like this:<br />
<img src="https://github.com/bluegraybox/examples/raw/master/indent-parser/structure.png" /></p>
<p>Now, I&#8217;d already done this in Ruby. I&#8217;d designed a set of classes to represent the stages of the parsed data. I start out with a list of strings, then I break each string into a simple object that just knows &#8220;indent&#8221; and &#8220;content&#8221;. It then adds that to the tree structure as a node that knows what its parent node is. As more nodes get added, they become its children. Eventually, I could extend those classes to understand particular bits of project-related markup, like priorities or dependencies. But for now, just the tree structure.</p>
<p>Already, there&#8217;s a bit of <a href="http://en.wikipedia.org/wiki/Recursion">recursion</a> here: I have a &#8220;current&#8221; node, the most recently added one. If the next node is indented further, I add it to the current node&#8217;s children. Otherwise, I tell the current node&#8217;s parent to try to add it. This way, you could pop up several levels before you find a parent to add the new node to. In this example, I try to add node &#8220;e&#8221; to &#8220;d&#8221;, then &#8220;c&#8221;, before finally adding it to &#8220;a&#8221;. Despite that, it&#8217;s still a pretty linear process. Each line is added in order, and you&#8217;re just moving up and down the tree, stitching each into place.</p>
<p>So for my first stab at doing this in Lisp, I just sort of transliterated it. I took the logic and structure of my Ruby code, and tried to just turn it into Lisp syntax. That didn&#8217;t go so well. It&#8217;s a bit hard to explain how it went wrong, other than to say that it came out like the programming version of <a href="http://www.engrish.com/">Engrish</a>. It didn&#8217;t work right, it was hard to follow what was going on in the code, and trying to fix it just made it uglier.</p>
<p>Normally, when I&#8217;m writing code it&#8217;s kinda like sculpting with clay or Play-Doh. I start out with a rough idea of what I want and gradually refine it, mushing chunks of logic around, whittling away bits I don&#8217;t need. I can see it taking shape. My understanding of what&#8217;s going on, the scope and nature of the problem I&#8217;m solving, gets clearer and clearer. This code was just getting messier. It felt more and more like a duct tape and bailing wire job. Even more than other programmers, Lisp people go on about the elegance and clarity of their code. So I gave up for the evening and went to bed pondering how to make it &#8220;Lispier&#8221;, maybe really work that recursion thing.</p>
<p>In the classification of programming languages, Lisp is a <a href="http://en.wikipedia.org/wiki/Functional_programming">&#8220;functional&#8221;</a> language, as opposed to an <a href="http://en.wikipedia.org/wiki/Object-oriented_programming">object-oriented</a> or <a href="http://en.wikipedia.org/wiki/Procedural_programming">procedural</a> language. The distinctions are a bit blurry, but they&#8217;re about how the language encourages you to organize your code and suggests the terms you use to describe the problem you&#8217;re dealing with. Like I said, vague, but programming is fundamentally an act of communication, so the mental constructs you bring to it are important.</p>
<p>Programming languages all have nouns and verbs: Data and things you do with the data. Procedural languages focus on the verbs, the procedures. You&#8217;re stepping through a process; it&#8217;s linear. Procedures are broken down into sub-procedures, but it&#8217;s still all about what you&#8217;re doing as you step through the process. You have data structures, but you&#8217;re kinda just trundling them along through the procedures like a shopping cart.</p>
<p>Object-oriented languages focus on the data, how it&#8217;s organized. The verbs are &#8220;methods&#8221; tied to the data, what you can do with it. Methods may do things with other objects, but they&#8217;re defined in terms of the thing doing it.</p>
<p>Functional languages are a little harder to explain. Rather than the steps of a process, they focus on the start and end points, what you put in and what comes out; results, not actions. That isn&#8217;t really how people think. We tell stories; we make sense of the world through narratives. But while it&#8217;s not entirely natural, the functional way of thinking can be useful because it forces you to focus on what you&#8217;re trying to accomplish.</p>
<p>The other part of &#8220;Lispy&#8221; code is its focus on handling lists of data recursively. You define a function that does something with the first element of the list, then applies itself to the rest of the list. Rather than</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="lisp"><pre class="de1">new_list <span class="sy0">=</span> <span class="br0">&#91;</span><span class="br0">&#93;</span>
for thing in <span class="kw1">list</span><span class="sy0">:</span>
    <span class="me1">new_thing</span> <span class="sy0">=</span> do_stuff<span class="br0">&#40;</span>thing<span class="br0">&#41;</span>
    new_list<span class="sy0">.</span>add<span class="br0">&#40;</span>new thing<span class="br0">&#41;</span></pre></div></div></div></div></div></div></div>


<p>You do something more 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="lisp"><pre class="de1"><span class="br0">&#40;</span><span class="kw1">defun</span> process-<span class="kw1">list</span> <span class="br0">&#40;</span><span class="kw1">list</span><span class="br0">&#41;</span>
  <span class="br0">&#40;</span><span class="kw1">list</span> <span class="br0">&#40;</span>do-stuff <span class="br0">&#40;</span>first <span class="kw1">list</span><span class="br0">&#41;</span><span class="br0">&#41;</span>
        <span class="br0">&#40;</span>process-<span class="kw1">list</span> <span class="br0">&#40;</span>rest <span class="kw1">list</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="br0">&#41;</span><span class="br0">&#41;</span></pre></div></div></div></div></div></div></div>


<p>process-list is a function that calls do-stuff on the first thing in a list, then calls itself on the rest of the list, and gloms the results together to make a new list.  Weird way to do things, huh?</p>
<p>Anyway, in my case, I&#8217;ve got a node and a list of lines that are all either children or siblings of that node. Once you break the list into those two chunks, you just create a child and a sibling node, and hand them their lines to process. Your output is a list of the siblings, with you in the front. Your child hands you back a list of its siblings, your children, with itself in the front. Your sibling gives you it siblings (which are also your siblings) with itself in the front. By the time they get back to you, all of your siblings and children already have their siblings and children.</p>
<p>That&#8217;s a very clean, mathematical way of thinking about it, but it&#8217;s seriously non-linear. The Ruby code built its structure in order, &#8220;a&#8221; through &#8220;l&#8221;. The Lisp code built it in the following order: d e c b i h k j g l f a. It processes the children from the deepest up, and the siblings from the last to the first. Not intuitive.</p>
<p>The experience of programming Lisp ended up being a lot more like doing math than sculpting Play-Doh. I had to step away from the keyboard and just think about it for a while. But when I figured it out, everything just <em>snapped</em> into place. It wasn&#8217;t the gradual refining and polishing of an idea; it was like solving a puzzle. When I hit on the solution, I <em>knew</em> I had it. I felt it in my bones.</p>
<p>So it was a good learning experience. My hope was that Lisp would force me to think differently, and it did. The Lisp program I came up with is fundamentally unlike the Ruby version. (You can see the Ruby code <a href="https://github.com/bluegraybox/examples/blob/master/indent-parser/indent_parser.rb">here</a> and the Lisp code <a href="https://github.com/bluegraybox/examples/blob/master/indent-parser/parse-indents.lisp">here</a>.) I think I&#8217;ve kinda wrapped my head around this functional programming approach. That, more than Lisp syntax, is the potentially useful bit.</p>
<p>The thing about functional programs is that they&#8217;re much easier to break into seprate processing chunks, whether you&#8217;re running them on some Google-grade cluster or compute cloud, or just on a multi-core chip. There&#8217;s a lot more demand for that kinda thing these days. The Ruby version of my code has this central tree structure that it adds onto line by line. There isn&#8217;t any way to farm that work out to a bunch of independent processes. In the Lisp version, at each node you&#8217;re splitting the work into two batches, children and siblings. You could distribute it naturally across as many processors as you have nodes. Each just has to get its set of lines to process, and the tree comes together in this non-linear way as they return their results.</p>
<p>I&#8217;ve always been all about code as a communication between programmers, rather than just a way of telling the machine what to do. Lisp doesn&#8217;t do so well on this count. It&#8217;s certainly not as friendly to the novice programmer. One of the things I love about Python is that pretty much anyone who knows how to program can read it &#8211; it looks like pseudocode. That&#8217;s <em>so</em> not true of Lisp. The syntax, with all those parentheses, isn&#8217;t like any other languages. It makes no sense at first, and takes a good bit of getting used to. (To be fair, it was there first.) But the harder thing is shifting to a new set of ideas and customs. Early on (and occasionally still) I would try to do something that should be simple and obvious, but in Lisp they just don&#8217;t do things that way. Like any foreign language, it&#8217;s much harder to write than to read, and the idioms are harder to learn than the grammar.</p>
<p>But again, like any foreign culture, once you spend some time there, you get used to it and it starts to feel comfortable, even normal. Recursion goes from being alien and academic to highly practical. All the crazy parentheses actually feel like a more logical and coherent way of grouping functions. And when you come home to Ruby or Java or whatever, you bring a little bit of all that with you.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2011/07/02/foreign-language-lessons/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Business Process Automation</title>
		<link>http://www.bluegraybox.com/blog/2011/01/24/business-process-automation/</link>
		<comments>http://www.bluegraybox.com/blog/2011/01/24/business-process-automation/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 15:00:18 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=115</guid>
		<description><![CDATA[If you’re not familiar with the term, it probably sounds like some marketing bullshit, but it’s actually a good shorthand description of one of the ways that software can be insanely useful. To break it down: “Business process” is a blanket term for all the things that people have do at work to get something [...]]]></description>
			<content:encoded><![CDATA[<p>If you’re not familiar with the term, it probably sounds like some marketing bullshit, but it’s actually a good shorthand description of one of the ways that software can be insanely useful. To break it down: “Business process” is a blanket term for all the things that people have do at work to get something done. You’ll have a business process for setting up new customer accounts, fulfilling an order for widgets, or whatever. The “Automation” part is about writing software to make this more efficient. So “Business Process Automation” covers any software that makes people’s jobs easier.</p>
<p>That doesn’t mean replacing people with machines. It’s about letting the computer handle the tedious, repetitive crap, and freeing people up to work on the more interesting stuff. In almost any business process, there will be some amount of straightforward bookkeeping that a computer can handle; but there will also be a need for judgement and common sense, and the ability to deal with ambiguous or unforeseen situations, which computers are fundamentally incapable of.</p>
<p>The simplest, most common example of this is spreadsheet software. A computer can’t tell you what numbers and formulas to put in, or what the results mean&mdash;what’s important, what action to take&mdash;but it can save you the hassle of re-doing the math every time something changes. It’s a power tool, like a band saw or a nail gun.</p>
<p>The first time this was really driven home for me was years ago, when I was working at a little web development shop. I was chatting with a friend of mine who was a designer there, and she was griping that she’d gotten stuck with this crappy assignment. One of our clients had these tables of financial data on their site that had to be updated every month. They sent the new data to us in a PDF document. Her task was to copy the data from the PDF into HTML. So she opened up the PDF in one window, and the HTML source in another, and copied it one entry at a time: click, drag, ctrl-c, click, ctrl-v; for row after row, table after table. She’d just finished the first batch of this, and it had taken her nearly two full days. Absolutely mind-numbing, and she was going to have to do this every month.</p>
<p>She told me all this, and I said, “You did what? No, that’s crazy; don’t do that again. Give me a little while.” I went off and found a utility to dump out the PDF as text, then wrote a Perl script to parse the data out and stuff it into an HTML template. It took me maybe a day and a half. Now, each month, she just had to run the script and spend maybe fifteen minutes proof-reading the pages it spat out.</p>
<p>This is a tiny example, but it demonstrates the alchemy you can work with software. I got to do this fun little side-project; I freed up nearly 10% of her time, so she could do more valuable work for the company; and I made her job way less sucky. Everybody wins.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2011/01/24/business-process-automation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Business Software</title>
		<link>http://www.bluegraybox.com/blog/2011/01/20/business-software/</link>
		<comments>http://www.bluegraybox.com/blog/2011/01/20/business-software/#comments</comments>
		<pubDate>Thu, 20 Jan 2011 18:50:27 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=112</guid>
		<description><![CDATA[I&#8217;m a programmer. I write business software. Programmers hate writing business software. It&#8217;s not cool, and it&#8217;s hard. Programmers won&#8217;t come out and say that it&#8217;s hard; they&#8217;ll use terms like &#8220;messy&#8221; or &#8220;uninteresting&#8221;. It&#8217;s not hard for technical reasons; it&#8217;s hard for human reasons. And we, on the whole, are not good with humans. [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m a programmer.  I write business software.  Programmers hate writing business software.  It&#8217;s not cool, and it&#8217;s hard.  Programmers won&#8217;t come out and say that it&#8217;s hard; they&#8217;ll use terms like &#8220;messy&#8221; or &#8220;uninteresting&#8221;.  It&#8217;s not hard for technical reasons; it&#8217;s hard for human reasons.  And we, on the whole, are not good with humans.  I&#8217;m not great with them, but I&#8217;m increasingly of the opinion that they&#8217;re more interesting than machines.</p>
<p>Let me give you a definition of Business Software that&#8217;ll shed a bit of light on the situation:  Business Software is software that isn&#8217;t used by programmers.  It&#8217;s used by non-technical people, suits.  It&#8217;s not useful to us.  We don&#8217;t care about it.  Programmers use programming tools and play video games; end of story.  In fact, if the suits think it&#8217;s great, that&#8217;s a sign that it sucks.</p>
<p>Since we don&#8217;t use business software, we don&#8217;t know what it should do, whether it&#8217;s working right, or how to make it better.  There isn&#8217;t a good, objective definition of what it&#8217;s supposed to do; it&#8217;s &#8220;whatever the user wants.&#8221;  Sometimes, it&#8217;s based on bizarre business, organizational, historical, or legal requirements.  There&#8217;s no way to reason it out.  If you try, you&#8217;ll often find out that your perfectly logical conclusion is in fact disastrously wrong.  So we have to ask the users how the software needs to work.  That means sitting in meetings.  With suits.</p>
<p>Since the users aren&#8217;t technical, they can&#8217;t just tell you what they want.  They probably don&#8217;t know, themselves.  They don&#8217;t know what the limits of the technology are.  They have no idea what&#8217;s feasible.  They ask all sorts of really dumb questions, and expect the impossible.  They&#8217;re not good at visualizing how they&#8217;ll actually use the software.  They&#8217;re usually wrong about what they think they want.  And they will change their minds.  So you have to bridge that gap, and you don&#8217;t get to just meet them halfway.  They might be able to learn a few basic technical things, but you need to learn a lot about their business.  So now you have to be the one asking a lot of dumb questions.</p>
<p>So just figuring out what your program needs to do is the really hard bit.  You&#8217;d think that after suffering through all of that, you&#8217;d at least get to do something really cool, but no &#8211; the technical solution often turns out to be fairly straightforward, usually something involving a web server and a database.  I think that&#8217;s why there&#8217;s such frantic innovation in tools and frameworks for building web applications:  There are all these programmers out there trying to make the technical work interesting.</p>
<p>In fact, to write successful business software, you have to make it deliberately uncool.  You don&#8217;t use development builds of cutting edge tools and elaborate frameworks; you use simple, stable tools that lots of other people know how to use.  In business software, you&#8217;re really trying to program yourself out of a job, to make yourself replaceable.  You&#8217;re trying to take all of this business knowledge, and embody it in code.  I&#8217;ve heard programmers brag that the guys who came after them weren&#8217;t smart enough to maintain their code.  That&#8217;s completely backwards.  If you&#8217;re really good, anyone should be able to pick up your code and understand what it&#8217;s doing and why.  Code is communication, the expression of an idea.  Your code should make all of the complex business logic clear and precise.  If you&#8217;ve done really well, you can even walk non-technical people through it and give them a better understanding of their own business.  If other programmers can&#8217;t work with it, you either didn&#8217;t really understand it, or you didn&#8217;t communicate it clearly.</p>
<p>&#8220;Legacy code&#8221; is a term of distain.  It&#8217;s shorthand for &#8220;crusty old software written in some boring language on an obsolete platform.&#8221;  In practical terms, it&#8217;s anything more than about 6 months old.  Real legacy code can even be decades old, written back in the days of Big Iron.  It&#8217;s been tweaked and stretched and hacked up ever since.  It has years of business logic layered on like shellac.  To work with it, you have to waste valuable brain space learning about how people did things before we Figured It Out.  If you&#8217;re really skilled and really lucky, your reward will be that your business software becomes legacy code.  It&#8217;ll become critical to the business and they&#8217;ll use it for years to come.  The fullness of time will expose all of the mistakes and misjudgements that you made.  You will learn humility, and it will make you a better programmer.  It&#8217;s a tough love kinda thing.</p>
<p>So why do I write business software?  Because I like people.  I like trying to figure them out.  I like trying to get my head inside their world.  All of that stupid, illogical business logic?  Most of it really does make sense once you learn the context and history of it.  I like that it&#8217;s unintuitive; I like that little jolt of surprise I get when I learn that the world is more complex than I&#8217;d thought.  I also like being useful.  Just on the level of pure self-preservation, I figure I&#8217;m better off being useful rather than just clever.  But I also like the feedback.  I get all kinds of warm fuzzies from writing a bit of code that makes someone else&#8217;s life a little easier.  I&#8217;ve come to the conclusion that I was put on this earth to program the Suck out of people&#8217;s jobs.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2011/01/20/business-software/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

