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

<channel>
	<title>bluegrayblog</title>
	<atom:link href="http://www.bluegraybox.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bluegraybox.com/blog</link>
	<description>so much to do, so little time...</description>
	<lastBuildDate>Sun, 19 May 2013 17:27:25 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>World&#8217;s Dumbest TCP Service</title>
		<link>http://www.bluegraybox.com/blog/2013/05/04/worlds-dumbest-tcp-service/</link>
		<comments>http://www.bluegraybox.com/blog/2013/05/04/worlds-dumbest-tcp-service/#comments</comments>
		<pubDate>Sat, 04 May 2013 17:00:40 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=318</guid>
		<description><![CDATA[I feel like a bash scripting Dr. Frankenstein. Last week, I wrote about the world&#8217;s dumbest instant messaging tool. This week I&#8217;ve moved on to the world&#8217;s dumbest TCP server. In my quest for a deep understanding of networking, it&#8217;s a bit of a detour, a roadside America attraction. I&#8217;m not so much learning new [...]]]></description>
				<content:encoded><![CDATA[<p>I feel like a bash scripting Dr. Frankenstein. Last week, I wrote about the world&#8217;s dumbest instant messaging tool. This week I&#8217;ve moved on to the world&#8217;s dumbest TCP server. In my quest for a deep understanding of networking, it&#8217;s a bit of a detour, a roadside America attraction. I&#8217;m not so much learning new stuff here as figuring out how to explain what I know. And having fun pushing the limits of bash in the process.</p>
<p>Part of this is just the challenge of the absurd: Could I make this particular bear dance? But the serious point is two-fold: to make the idea of network services more accessible, and to show that bash is more powerful than you might think. People don&#8217;t think of bash as a programming language: A bash script usually starts life as a bunch of commands you executed one at a time on the command line, then copied into a file so you didn&#8217;t have to re-type them. That&#8217;s not real programming, is it? But bash also has variables, data structures, functions, and even process forking. That&#8217;s enough to get a fair amount done.</p>
<p>Network servers have the opposite problem. They&#8217;re big bits of infrastructure that Other People write. And infrastructure-grade servers &#8211; like the Apache web server &#8211; <em>are</em> complicated. Apache has to implement the full HTTP protocol, not just the small subset of it that most people use. It&#8217;s got all this logic for authenticating users, negotiating content types, redirecting to pages that have moved, and so on. On top of all that, it&#8217;s got developer-decades worth of edge case handling, performance optimizations, and feature creep.</p>
<p>But the core of what it does is straightforward: It listens on a socket, you connect to it and send it a message in a particular format, it does some processing on that, and it sends you a message in response. That&#8217;s fundamentally what all network servers do. The ones we&#8217;re familiar with &#8211; web, mail, and chat servers &#8211; have rich and complex message protocols, but a quick skim through the <code>/etc/services</code> file turns up sedimentary layers of oddly specific services, like ntp and biff. They do small, specific, useful things.</p>
<p>So the what&#8217;s the simplest server I can write that does something even minimally useful? And can I write it in bash?</p>
<p>I figured netcat is a good place to start. Last week, we used it to send messages back and forth between two people. All we want to do now is replace one of those people with a very small shell script. <code>netcat -l <em>port</em></code> starts up a server that listens on a port and dumps anything it gets to standard output (stdout). It also sends anything it gets on standard input (stdin) back to the client. We just need to redirect netcat&#8217;s stdout to a program, and then redirect that program&#8217;s output to netcat&#8217;s stdin. Doing either of those alone would be trivial; doing both is tricky.</p>
<p>Figuring that out took a fair amount of digging through the bash man page, and experimenting to get the syntax right, but in the end it was a trivial amount of code. Let&#8217;s take it as read for now that we&#8217;ve got a program called <code>wtf_server</code>, which reads from stdin and writes to stdout. What we&#8217;re going to do is use bash&#8217;s built-in <code>coproc</code> command, which will start it up as a background process, and set up new file handles for its stdin and stdout.</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">coproc WTF <span class="br0">&#123;</span> wtf_server; <span class="br0">&#125;</span></pre></div></div></div></div></div></div></div>


<p>The <code>WTF</code> tells coproc to create an array named <code>WTF</code> and save the file handles in it. <code>${WTF[0]}</code> will be wtf_server&#8217;s stdout, <code>${WTF[1]}</code> will be its stdin. So now we can start up the netcat server with its stdout and stdin jumper-cabled to wtf_server as desired.</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">port</span>=<span class="nu0">2345</span>
nc <span class="re5">-l</span> <span class="re1">$port</span> <span class="sy0">&lt;&amp;</span><span class="co1">${WTF[0]}</span> <span class="sy0">&gt;&amp;</span><span class="co1">${WTF[1]}</span></pre></div></div></div></div></div></div></div>


<p>Really, that&#8217;s the hard bit. Now we just need a program to read stdin and write stdout. In fact, we don&#8217;t even need a real program; our wtf_server is actually just a bash function. In its simplest incarnation, it just echoes back what was sent to 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="bash"><pre class="de1"><span class="kw1">function</span> wtf_server <span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw1">while</span> <span class="kw2">true</span> ; <span class="kw1">do</span>
        <span class="kw2">read</span> msg
        <span class="kw3">echo</span> <span class="st0">&quot;You said: '<span class="es2">$msg</span>'&quot;</span>
    <span class="kw1">done</span>
<span class="br0">&#125;</span></pre></div></div></div></div></div></div></div>


<p>With the coproc and netcat server running, you can switch to another terminal, open a client connection with netcat, and have an exchange 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="text"><pre class="de1">$ nc localhost 2345
hello world!
You said: 'hello world!'</pre></div></div></div></div></div></div></div>


<p>Ok, so that&#8217;s the proof of concept. We&#8217;re definitely falling short of the &#8220;minimally useful&#8221; criteria, but we can replace our echo with any bash commands we want. The only constraint is what it&#8217;s <em>safe</em> to do &#8211; this is still a toy service, anonymous and going over an unencrypted connection. Don&#8217;t run the input as shell commands, fer chrissakes. Within those limits, there&#8217;s still plenty of useful things we can do: reporting on system info or serving up static content. Here&#8217;s a sketch with a few ideas:</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> wtf_server <span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw1">while</span> <span class="kw2">true</span> ; <span class="kw1">do</span>
        <span class="kw2">read</span> msg
        <span class="kw1">case</span> <span class="re1">$msg</span> <span class="kw1">in</span>
            i <span class="sy0">|</span> index <span class="br0">&#41;</span>
                <span class="kw2">ls</span> <span class="re1">$docs</span> <span class="sy0">;;</span>
            get\ <span class="sy0">*</span> <span class="br0">&#41;</span>
                <span class="re2">f</span>=<span class="co1">${msg#get }</span>
                <span class="kw2">cat</span> <span class="re1">$docs</span><span class="sy0">/</span><span class="re1">$f</span> <span class="sy0">;;</span>
            t <span class="sy0">|</span> <span class="kw1">time</span> <span class="br0">&#41;</span>
                <span class="kw2">date</span> <span class="sy0">;;</span>
            u <span class="sy0">|</span> <span class="kw2">uptime</span> <span class="br0">&#41;</span>
                <span class="kw2">uptime</span> <span class="sy0">;;</span>
            <span class="sy0">*</span> <span class="br0">&#41;</span>
                <span class="kw3">echo</span> <span class="st0">&quot;Commands: t, time; u, uptime; i, index; get &lt;file&gt;&quot;</span>
                <span class="kw3">echo</span> <span class="st0">&quot;    ctrl-c to exit&quot;</span>
        <span class="kw1">esac</span>
        <span class="kw3">echo</span> <span class="re5">-n</span> <span class="st0">&quot;&gt; &quot;</span>
    <span class="kw1">done</span>
<span class="br0">&#125;</span></pre></div></div></div></div></div></div></div>


<p>This gives us a limited interactive shell. Each case statement handles a different request format. We can get the machine&#8217;s current time and uptime stats. It also has a docs directory; we can list the files in it and cat them out individually. A session 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="text"><pre class="de1">$ nc localhost 2345
&nbsp;
Commands: t, time; u, uptime; i, index; get &lt;file&gt;
    ctrl-c to exit
&gt; t
Sat May  4 11:52:52 EDT 2013
&gt; u
 11:52:53 up 42 days,  5:48, 26 users,  load average: 0.67, 0.37, 0.35
&gt; i
about.txt
status.txt
&gt; get status.txt
Up late on a Friday, hacking bash scripts.
&gt; ^C
$</pre></div></div></div></div></div></div></div>


<p><em>(After connecting, I just hit return to send a blank line, and the server responded with the help text and the &#8216;>&#8217; prompt. Every server response ends with a prompt.)</em></p>
<p>That&#8217;s it. No real protocol, certainly nothing formal like HTTP, just a set of ad-hoc request handlers, made up as we went along. The beauty of this is that it doesn&#8217;t depend on anything else. It&#8217;s not running behind Apache or anything. There&#8217;s no development environment to set up, no gems to install; just one standard unix utility &#8211; netcat &#8211; and bash handles all the rest.</p>
<hr />
<p>Here&#8217;s the full <code>wtf_server.sh</code> script that starts this up.</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="co0">#!/bin/bash</span>
&nbsp;
<span class="co0"># Weird little TCP server</span>
<span class="co0"># Tells time and uptime; can list and dump files in an &quot;docs&quot; subdir</span>
&nbsp;
<span class="co0"># Takes a port parameter, just so you know which one you're running on.</span>
<span class="kw3">test</span> <span class="re5">-n</span> <span class="st0">&quot;$1&quot;</span> <span class="sy0">||</span> <span class="br0">&#123;</span> <span class="kw3">echo</span> <span class="st0">&quot;$0 &lt;port&gt;&quot;</span>; <span class="kw3">exit</span> <span class="nu0">1</span>; <span class="br0">&#125;</span>
<span class="re2">port</span>=<span class="re4">$1</span>
<span class="re2">dir</span>=<span class="sy0">`</span><span class="kw2">dirname</span> <span class="re4">$0</span><span class="sy0">`</span>
<span class="re2">docs</span>=<span class="re1">$dir</span><span class="sy0">/</span>docs
&nbsp;
<span class="kw1">function</span> wtf_server <span class="br0">&#40;</span><span class="br0">&#41;</span> <span class="br0">&#123;</span>
    <span class="kw1">while</span> <span class="kw2">true</span> ; <span class="kw1">do</span>
        <span class="kw2">read</span> msg
        <span class="kw1">case</span> <span class="re1">$msg</span> <span class="kw1">in</span>
            i <span class="sy0">|</span> index <span class="br0">&#41;</span>
                <span class="kw2">ls</span> <span class="re1">$docs</span> <span class="sy0">;;</span>
            get\ <span class="sy0">*</span> <span class="br0">&#41;</span>
                <span class="re2">f</span>=<span class="co1">${msg#get }</span>
                <span class="kw2">cat</span> <span class="re1">$docs</span><span class="sy0">/</span><span class="re1">$f</span> <span class="sy0">;;</span>
            t <span class="sy0">|</span> <span class="kw1">time</span> <span class="br0">&#41;</span>
                <span class="kw2">date</span> <span class="sy0">;;</span>
            u <span class="sy0">|</span> <span class="kw2">uptime</span> <span class="br0">&#41;</span>
                <span class="kw2">uptime</span> <span class="sy0">;;</span>
            <span class="sy0">*</span> <span class="br0">&#41;</span>
                <span class="kw3">echo</span> <span class="st0">&quot;Commands: t, time; u, uptime; i, index; get &lt;file&gt;&quot;</span>
                <span class="kw3">echo</span> <span class="st0">&quot;    ctrl-c to exit&quot;</span>
        <span class="kw1">esac</span>
        <span class="kw3">echo</span> <span class="re5">-n</span> <span class="st0">&quot;&gt; &quot;</span>
    <span class="kw1">done</span>
<span class="br0">&#125;</span>
&nbsp;
<span class="co0"># Start wtf_server as a background coprocess named WTF</span>
<span class="co0"># Its stdin filehandle is ${WTF[1]}, and its stdout is ${WTF[0]}</span>
coproc WTF <span class="br0">&#123;</span> wtf_server; <span class="br0">&#125;</span>
&nbsp;
<span class="co0"># Start a netcat server, with its stdin redirected from WTF's stdout,</span>
<span class="co0"># and its stdout redirected to WTF's stdin</span>
nc <span class="re5">-l</span> <span class="re1">$port</span> <span class="re5">-k</span> <span class="sy0">&lt;&amp;</span><span class="co1">${WTF[0]}</span> <span class="sy0">&gt;&amp;</span><span class="co1">${WTF[1]}</span></pre></div></div></div></div></div></div></div>


]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2013/05/04/worlds-dumbest-tcp-service/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unpacking Packets</title>
		<link>http://www.bluegraybox.com/blog/2013/04/27/unpacking-packets/</link>
		<comments>http://www.bluegraybox.com/blog/2013/04/27/unpacking-packets/#comments</comments>
		<pubDate>Sat, 27 Apr 2013 13:41:20 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=306</guid>
		<description><![CDATA[So, I sort of understand this whole TCP thing: You open a connection, you send packets, you close the connection. TCP provides a reliable delivery protocol layered on top of the unreliable IP protocol. So your data gets wrapped in a TCP segment, which gets wrapped in an IP datagram. But what does that actually [...]]]></description>
				<content:encoded><![CDATA[<p>So, I <a href="http://www.bluegraybox.com/blog/2005/04/22/under-the-hood/" title="Under the Hood" target="_blank">sort of understand</a> this whole TCP thing: You open a connection, you send packets, you close the connection. TCP provides a reliable delivery protocol layered on top of the unreliable IP protocol. So your data gets wrapped in a TCP segment, which gets wrapped in an IP datagram.</p>
<p>But what does that actually look like?</p>
<p>Web requests, email, and all of that add another layer of protocol overhead on top of TCP, so let&#8217;s start out with something really simple: the world&#8217;s dumbest instant messaging service. We&#8217;re going to use netcat, the Swiss army knife of TCP/IP utilities. All we&#8217;re going to do is have one netcat process (the server) listen on a TCP port, and have another netcat process (the client) open a connection to it. Both will send any messages typed on the command line, and print any messages they get. We start up the server 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="text"><pre class="de1">$ nc -l 43981</pre></div></div></div></div></div></div></div>


<p>That&#8217;s just telling netcat to start up and listen on port 43981. Why 43981? We&#8217;ll get to that in a bit.</p>
<p>Then we switch to another terminal, and start up the client 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="text"><pre class="de1">$ nc localhost 43981</pre></div></div></div></div></div></div></div>


<p>Here, we need to tell it which server to connect to, and give it the same port number. Then we type stuff into the client:</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="text"><pre class="de1">$ nc localhost 43981
hello world!
how's it going?</pre></div></div></div></div></div></div></div>


<p>Each time we hit return, the line shows up in the server:</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="text"><pre class="de1">$ nc -l 43981
hello world!
how's it going?</pre></div></div></div></div></div></div></div>


<p>A key thing about TCP is that it&#8217;s a two-way connection. Part of what the client does when it opens the connection is tell the server how to send messages back to it. So here we can also type something into the server:</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="text"><pre class="de1">$ nc -l 43981
hello world!
how's it going?
pretty good!</pre></div></div></div></div></div></div></div>


<p>And it will show up in the client:</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="text"><pre class="de1">$ nc localhost 43981
hello world!
how's it going?
pretty good!</pre></div></div></div></div></div></div></div>


<p>When we get bored, we <code>ctrl-c</code> to quit either the server or the client, and the other shuts down automatically.</p>
<h2>Pop the Hood</h2>
<p>Ok, so that&#8217;s it. Messages going across a TCP connection a line at a time. Totally bare-bones. So what&#8217;s going on under the hood? To answer that, we&#8217;re going to re-run this little exercise, and this time we&#8217;re going to use tcpdump to listen in on the conversation. As the name implies, tcpdump listens in on TCP traffic and dumps it out to the screen. So, open a third terminal and fire up tcpdump:</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="text"><pre class="de1">$ sudo tcpdump -i lo -X port 43981
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on lo, link-type EN10MB (Ethernet), capture size 65535 bytes</pre></div></div></div></div></div></div></div>


<p>&#8220;-i lo&#8221; tells it to listen on the loopback interface, since our machine is just sending messages to itself, and &#8220;-X&#8221; will dump out the TCP segments in a couple of useful formats. &#8220;port 43981&#8243; tells it to only report traffic to and from our netcat server port.</p>
<p>We don&#8217;t see anything when we start up our netcat server, but as soon as we start up the client, we get this in the tcpdump terminal:</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="text"><pre class="de1">12:50:53.227362 IP localhost.59356 &gt; localhost.43981: Flags [S], seq 586457076, win 32792, options [mss 16396,sackOK,TS val 48581958 ecr 0,nop,wscale 7], length 0
	0x0000:  4500 003c d2b2 4000 4006 6a07 7f00 0001  E..&lt;..@.@.j.....
	0x0010:  7f00 0001 e7dc abcd 22f4 9ff4 0000 0000  ........&quot;.......
	0x0020:  a002 8018 fe30 0000 0204 400c 0402 080a  .....0....@.....
	0x0030:  02e5 4d46 0000 0000 0103 0307            ..MF........
12:50:53.227404 IP localhost.43981 &gt; localhost.59356: Flags [S.], seq 2685804629, ack 586457077, win 32768, options [mss 16396,sackOK,TS val 48581958 ecr 48581958,nop,wscale 7], length 0
	0x0000:  4500 003c 0000 4000 4006 3cba 7f00 0001  E..&lt;..@.@.&lt;.....
	0x0010:  7f00 0001 abcd e7dc a016 2055 22f4 9ff5  ...........U&quot;...
	0x0020:  a012 8000 fe30 0000 0204 400c 0402 080a  .....0....@.....
	0x0030:  02e5 4d46 02e5 4d46 0103 0307            ..MF..MF....
12:50:53.227439 IP localhost.59356 &gt; localhost.43981: Flags [.], ack 1, win 257, options [nop,nop,TS val 48581958 ecr 48581958], length 0
	0x0000:  4500 0034 d2b3 4000 4006 6a0e 7f00 0001  E..4..@.@.j.....
	0x0010:  7f00 0001 e7dc abcd 22f4 9ff5 a016 2056  ........&quot;......V
	0x0020:  8010 0101 fe28 0000 0101 080a 02e5 4d46  .....(........MF
	0x0030:  02e5 4d46                                ..MF</pre></div></div></div></div></div></div></div>


<p>What we see here is the client and server negotiating a TCP connection in what&#8217;s known as a three-way handshake. Our client sends a packet saying that it wants to start a connection, the server sends back an acknowledgement, and the client responds with a confirmation. For each of these we get a summary line describing the packet and then a dump of the actual contents &#8211; verbatim, byte-by-byte. The &#8220;0&#215;0000&#8243; and such on the left are the byte index in hexadecimal for the start of each row; so zero, 10 (16 in decimal), 20 (32), 30 (48). The big chunk in the center is the data in hex characters. Each hex character is 4 bits (half a byte, and thus referred to as a &#8220;nibble&#8221; &#8211; ah, nerd humor), so each set of 4 is two bytes. The block on the right is the same data, rendered as ASCII characters (with all the non-printing characters shown as periods). Since what we&#8217;re dealing with here is all binary data, that&#8217;s not useful yet.</p>
<p>So what <em>is</em> all this crap?</p>
<h2>IP Header</h2>
<p>Well, like I said, we&#8217;ve got <a href="https://en.wikipedia.org/wiki/Transmission_Control_Protocol#TCP_segment_structure" title="Wikipedia - TCP Header" target="_blank">TCP</a> <strong>segments</strong> wrapped in <a href="https://en.wikipedia.org/wiki/IPv4#Header" title="Wikipedia - IPv4" target="_blank">IP</a> <strong>datagrams</strong>, so the IP data is going to be what we see first. As always, Wikipedia is an awesome resource, and its page on IPv4 lays out the datagram structure for us bit-by-bit. (You may want to open that up in another tab for reference while you&#8217;re reading this.) Let&#8217;s look at our dump of the first packet:</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="text"><pre class="de1">	0x0000:  4500 003c d2b2 4000 4006 6a07 7f00 0001  E..&lt;..@.@.j.....
	0x0010:  7f00 0001 e7dc abcd 22f4 9ff4 0000 0000  ........&quot;.......
	0x0020:  a002 8018 fe30 0000 0204 400c 0402 080a  .....0....@.....
	0x0030:  02e5 4d46 0000 0000 0103 0307            ..MF........</pre></div></div></div></div></div></div></div>


<p>The first thing we see is the &#8220;4&#8243; telling us that this is an IPv4 datagram (not IPv6). Then a &#8220;5&#8243; for the header length. That&#8217;s in 32-bit words, so each of those will be two blocks of hex characters. So we already know that the IP header part of this packet is just:</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="text"><pre class="de1">	0x0000:  4500 003c d2b2 4000 4006 6a07 7f00 0001  E..&lt;..@.@.j.....
	0x0010:  7f00 0001                                ....</pre></div></div></div></div></div></div></div>


<p>The next byte is the DSCP and ECN fields. They&#8217;re all zeros, so we can ignore them here, but essentially they tell routers how important or urgent this packet is. In principle, all packets are the same, but in practice we might want some packets &#8211; like for Voice Over IP &#8211; to have a higher priority if there&#8217;s a lot of traffic. This one byte opens a rabbit hole of technical and policy issues.</p>
<p>The next two bytes &#8211; 003c or 60 in decimal &#8211; tell us the total length of the packet. Sure enough, the packet ends after 12 bytes of the &#8220;0&#215;0030&#8243; row. Two bytes here means that the total length of the packet can&#8217;t be more than 65535 bytes (2^16 &#8211; 1).</p>
<p>Each packet incurs a certain amount of overhead in transmission and processing, so it makes sense to put as much data in each packet as possible. But while the IPv4 protocol sets a maximum of 65535 bytes, it doesn&#8217;t require that every router support that. Remember that the protocol was developed back when 64K bytes was more than most machines had, and even now, that&#8217;s a lot for one message on a router that&#8217;s handling large volumes of traffic.</p>
<p>So our next four bytes &#8211; d2b2 4000 &#8211; deal with fragmentation. When a router has to forward a datagram that&#8217;s bigger than the next router can deal with, it will break it into fragments. The first thing we need is an Identification field so the server knows which fragments go together. The starting index is arbitrary &#8211; d2b2 for this one &#8211; but you&#8217;ll see that it&#8217;s incremented normally for later packets. Why not just start with 0001 or 0000? I suspect there&#8217;s another rabbit hole there, and I&#8217;d guess it has to do with managing multiple connections between the same client and server.</p>
<p>The other two bytes are divided up a little oddly: 3 bits for flags and 13 bits for the Fragment Offset &#8211; its index number. That means that the flags are the 8, 4, and 2 bits of the first nibble. It&#8217;s 4, so that&#8217;s the Don&#8217;t Fragment bit. Even if we were fragmented, this is the first packet, so the Fragment Offset is zero.</p>
<p>Next is TTL &#8211; Time To Live. When I bring up this page in a browser on my laptop, it sends packets skipping across the network to my hosting provider in California. They&#8217;ll pass through a few routers at my ISP and several more at internet backbone providers across the country before they get to the hosting server. There isn&#8217;t a pre-ordained route that they&#8217;ll follow. Each router looks at each packet and tries to figure out where to send it to get it closer to its destination. This is what makes the internet robust: If one of those connections goes down, the router will figure out the next best way to get the message through. (And yes, the mechanics of how that works are more than other whole essay.)</p>
<p>The downside of this is that if one or more routers are mis-configured, they could send the packets back to a previous router, and they&#8217;d end up going in loops. To keep packets from circling endlessly, they have a limited lifespan, measured in &#8220;hops&#8221;. Each router along the way decrements the TTL field. If the packet hasn&#8217;t got where it&#8217;s going by the time it gets to zero, the router knows something&#8217;s gone wrong, and drops it. Our packet starts off with a TTL byte of 40, so it&#8217;s got 64 hops to live.</p>
<p>It may not look like it, but we&#8217;re almost down to the end of the IP header here. The next byte tells us the IP Protocol number for the contents of this IP datagram. <a href="https://en.wikipedia.org/wiki/List_of_IP_protocol_numbers" title="Wikipedia - IP Protocol Numbers" target="_blank">06 means it&#8217;s TCP</a>.</p>
<p>The next two bytes &#8211; 6a07 &#8211; are the header checksum. It&#8217;s a number calculated from all the bytes in the header. It&#8217;s a way to check that the header wasn&#8217;t garbled in transit. When a router gets a packet, it calculates a checksum based on the header it received; if any bits got randomly flipped, the checksums won&#8217;t match. (This doesn&#8217;t protect against intentional tampering because someone could also update the checksum.)</p>
<p>The last two fields are the source and destination IP addresses. Again, this is a two-way connection we&#8217;re setting up here, so the client needs to tell the server where to send packets back to. Since we&#8217;re just talking to ourselves over the loopback interface, they&#8217;re both 127.0.0.1 &#8211; 7f00 0001 in hex.</p>
<h2>TCP Header</h2>
<p>Ok, that&#8217;s the IP header. Now on to the TCP header. Let&#8217;s strip the IP header out of our packet and see what&#8217;s left.</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="text"><pre class="de1">	0x0000:
	0x0010:            e7dc abcd 22f4 9ff4 0000 0000      ....&quot;.......
	0x0020:  a002 8018 fe30 0000 0204 400c 0402 080a  .....0....@.....
	0x0030:  02e5 4d46 0000 0000 0103 0307            ..MF........</pre></div></div></div></div></div></div></div>


<p>The first two fields &#8211; two bytes each &#8211; are the source and destination port numbers: e7dc and abcd. That&#8217;s why I picked the weird port to run this on: 43981 in hex is abcd, so it&#8217;s easy to spot in the output. e7dc is 59356, which isn&#8217;t significant &#8211; it&#8217;s just what was automatically chosen when the client opened the connection. Perhaps the most significant thing about the ports is that they&#8217;re not part of the IP header. Ports are a TCP-level concept; the IP layer only cares about getting the packets to the right machine.</p>
<p>The next four bytes &#8211; 22f4 9ff4 &#8211; are the Sequence Number (586,457,076). As with the Fragment Offset in the IP layer, this is to keep track of what order the segments belong in and which have been received. The big difference is that here it&#8217;s the index of the starting byte in the segment, so it will increase from segment to segment by the number of bytes in the TCP data. It also starts at an arbitrary value, and loops around to zero when it hits the maximum Sequence Number (4 Gigabytes). More on this later.</p>
<p>The next number is the Acknowledgement Number. It&#8217;s essentially the Sequence Number for the data received. It&#8217;s zero for now, so we&#8217;ll talk about it later when it&#8217;s got something to say for itself.</p>
<p>The next nibble is the Data Offset, which is the TCP header length in 32-bit words. It&#8217;s &#8220;a&#8221; (10), for a total of 40 bytes, which matches what we can see.</p>
<p>The rest of the a002 block are unused bits (reserved for future use) and flags. They&#8217;re all zero except the 2 bit, which is the SYN flag (for synchronize), which means that this segment is the start of a connection.</p>
<p>The next two bytes &#8211; 8018 (32792 in decimal) &#8211; are the Window Size. This is the sender putting a cap on how much data can be sent back to it, in case it has limited resources. I don&#8217;t know the reason for that exact number, but there&#8217;s a surprise here: We&#8217;ll see in a minute that there&#8217;s an optional field that multiplies this value.</p>
<p>Next is the TCP checksum. Unlike the IP checksum, this one is summed across both the TCP header and data. Why doesn&#8217;t the IP checksum just do both? I&#8217;m not sure, but I&#8217;d guess there&#8217;s both a design principle and a practical reason. TCP shouldn&#8217;t really depend on IP for that. Even though they were designed to work together, they have separate responsibilities. In theory, you could run TCP on top of other protocols than IP, though I don&#8217;t know of anyone doing that. So if TCP has to calculate its own checksum, there&#8217;s no point making IP do it as well. The practical concern is that the TCP data can be huge compared to the 40 bytes of IP header, and the IP checksum has to be checked at every hop; the TCP checksum is only checked when it reaches its destination.</p>
<p>The last standard field is the Urgent Pointer. The URG flag wasn&#8217;t set, so this is 0000. As to when that flag is set and how the urgent pointer is used when it is, that&#8217;s probably yet another rabbit hole.</p>
<p>Beyond that, we have a number of optional fields. They&#8217;re odd in that they&#8217;re not in a specific order, they&#8217;re different sizes, and they may have multiple sub-fields. The first byte of each tells us what type of field it is. I&#8217;ll run through them quickly, putting pipes between the sub-fields so you can see how they&#8217;re broken up.</p>
<ul>
<li>02|04|400c: Maximum segment size = 400c (16,396 bytes). This is used by the TCP layer to limit the segment size and save it from getting fragmented at the IP layer.</li>
<li>04|02: Selective acknowledgement permitted. Allows the receiver to request re-transmission of only missing segments, rather than the whole message. More on this later.</li>
<li>08|0a|01fd b1be|0000 0000: Timestamp=01fd b1be (33403326), previous timestamp=0000 0000. Used to help determine the order of the TCP segments when the amount of data being sent is more than the maximum Sequence Number.</li>
<li>01: no operation &#8211; padding to align options on word boundaries for performance.</li>
<li>03|03|07: window scale = 7; multiplies Window Size by 2^7, bringing it to 4,197,376 bytes</li>
</ul>
<p>We can check our homework here by looking at the packet summary. (Come on, it wouldn&#8217;t have been any fun if we did that first!)</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="text"><pre class="de1">12:50:53.227362 IP localhost.59356 &gt; localhost.43981: Flags [S], seq 586457076, win 32792, options [mss 16396,sackOK,TS val 48581958 ecr 0,nop,wscale 7], length 0</pre></div></div></div></div></div></div></div>


<p>Now that we know what we&#8217;re looking at, it&#8217;s pretty easy to read: time; host.port for source and destination; SYN flag; Sequence Number; window size; options with max segment, selective ack, timestamp, no-op, and window scale; and data length of zero.</p>
<p>Awesome, done! That&#8217;s the first packet.</p>
<h2>The Rest of the Handshake</h2>
<p>Now that we have the structure down, we just need to look at what&#8217;s different about the rest of the packets, and we can get most of what we need from the summary lines.</p>
<p>So, packet two is the response from our server.</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="text"><pre class="de1">12:50:53.227404 IP localhost.43981 &gt; localhost.59356: Flags [S.], seq 2685804629, ack 586457077, win 32768, options [mss 16396,sackOK,TS val 48581958 ecr 48581958,nop,wscale 7], length 0
	0x0000:  4500 003c 0000 4000 4006 3cba 7f00 0001  E..&lt;..@.@.&lt;.....
	0x0010:  7f00 0001 abcd e7dc a016 2055 22f4 9ff5  ...........U&quot;...
	0x0020:  a012 8000 fe30 0000 0204 400c 0402 080a  .....0....@.....
	0x0030:  02e5 4d46 02e5 4d46 0103 0307            ..MF..MF....</pre></div></div></div></div></div></div></div>


<p>What&#8217;s different? The IP identification is 0000, which strikes me as odd. Don&#8217;t know what&#8217;s going on there. And the checksum is different because of that. If we were connecting two different machines, we&#8217;d have seen the source and destination addresses switch. In the TCP header, the ports switched, which is the tip-off that this packet is going from the server to the client. We have a new Sequence Number, since the client and server keep separate counts of the data bytes they send. We now have an Acknowledgement Number, which is the client&#8217;s Sequence Number from the last packet, plus one. Both the SYN and ACK flags are set, marking this as the server acknowledgement. There&#8217;s a slightly different Window Size, but with the same scaling factor. The previous timestamp is set. And of course a different TCP checksum because of all that.</p>
<p>The third packet is the client&#8217;s confirmation of the connection. The server knows that the client asked for a connection, and the server knows that it sent an acknowledgement, but it needs to know that the client got the acknowledgment.</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="text"><pre class="de1">12:50:53.227439 IP localhost.59356 &gt; localhost.43981: Flags [.], ack 1, win 257, options [nop,nop,TS val 48581958 ecr 48581958], length 0
	0x0000:  4500 0034 d2b3 4000 4006 6a0e 7f00 0001  E..4..@.@.j.....
	0x0010:  7f00 0001 e7dc abcd 22f4 9ff5 a016 2056  ........&quot;......V
	0x0020:  8010 0101 fe28 0000 0101 080a 02e5 4d46  .....(........MF
	0x0030:  02e5 4d46                                ..MF</pre></div></div></div></div></div></div></div>


<p>The IP identity has been incremented, which changes the checksum. The TCP Sequence Number has been incremented and matches Acknowledgement Number from the previous server packet. Likewise, the Acknowledgement Number is now the Sequence Number from the server packet, incremented. We have fewer options &#8211; just the timestamps and a couple of no-ops &#8211; so the Header Size is only 8. Only the ACK flag is set, which says that the connection is solid now. The Window Size is 257, with no scaling factor in the options. I don&#8217;t think this is actually used now that the connection is established, so I don&#8217;t know why it&#8217;s not zero. Something else to research.</p>
<p>Anyway, hey, TCP connection established! So this is the first thing we&#8217;d see whether we&#8217;re sending email, hitting a web page, or whatever.</p>
<h2>Getting Down to Work</h2>
<p>After that, we send a message from the client to the server, and get a response back. This time, we&#8217;re actually sending data!</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="text"><pre class="de1">12:51:04.418321 IP localhost.59356 &gt; localhost.43981: Flags [P.], seq 1:14, ack 1, win 257, options [nop,nop,TS val 48584755 ecr 48581958], length 13
	0x0000:  4500 0041 d2b4 4000 4006 6a00 7f00 0001  E..A..@.@.j.....
	0x0010:  7f00 0001 e7dc abcd 22f4 9ff5 a016 2056  ........&quot;......V
	0x0020:  8018 0101 fe35 0000 0101 080a 02e5 5833  .....5........X3
	0x0030:  02e5 4d46 6865 6c6c 6f20 776f 726c 6421  ..MFhello.world!
	0x0040:  0a                                       .
12:51:04.418446 IP localhost.43981 &gt; localhost.59356: Flags [.], ack 14, win 256, options [nop,nop,TS val 48584755 ecr 48584755], length 0
	0x0000:  4500 0034 6d10 4000 4006 cfb1 7f00 0001  E..4m.@.@.......
	0x0010:  7f00 0001 abcd e7dc a016 2056 22f4 a002  ...........V&quot;...
	0x0020:  8010 0100 fe28 0000 0101 080a 02e5 5833  .....(........X3
	0x0030:  02e5 5833                                ..X3</pre></div></div></div></div></div></div></div>


<p>Here&#8217;s where the ASCII output finally becomes useful. You can spot the &#8220;hello world!&#8221; content right away, which makes it a lot easier to keep track of which packets are which as we&#8217;re digging through this.</p>
<p>In the first packet, the Total Length is bigger by 13 (&#8220;hello world!&#8221; plus the return character). The client set the PSH flag, to indicate that there&#8217;s data to push to the application (netcat). The Acknowledgement and Sequence numbers are the same as last time because no data was sent; but then in the server&#8217;s response, its Acknowledgement Number is 13 (no coincidence) more than the client&#8217;s Sequence Number.</p>
<p>Ok, so now that the Acknowledgement number is starting to move for real, let&#8217;s talk about what all the futzing around with it and the Sequence Number is about. This is really the core of TCP, what makes it special. This is how it guarantees that the data gets through even when IP delivery fails and packets get dropped. To do that, the client needs to keep track of each chunk of data it sends out, and it needs to get a response from the server saying that piece has been received. It&#8217;s like registered mail but better, because the response tells the client not only that the server got a packet, but how much data it got and where it is in the client&#8217;s data set. (The Acknowledgement Number is actually the number of the next byte the server expects to get from the client).</p>
<p>TCP isn&#8217;t normally a one-for-one exchange like this. Often, the client would send out a whole mess of packets at once. Rather than acknowledging each individually, which would generate a whole lot of traffic, the server just sends back the Acknowledgement Number for the highest packet received, assuming it gets them all. If it doesn&#8217;t, if there are packets missing, it could send an acknowledgement for the highest contiguous packet it gets, and have the client re-send everything later. But it could be smarter than that, and this is where the Selective Acknowledgement option comes in. That lets the server acknowledge several discontinuous blocks (as start and end bytes), so the client only has to re-send the missing pieces.</p>
<p>Also remember that this is a two-way conversation. When the server is sending an acknowledgement to the client, it&#8217;s also sending its own Sequence Number, so the client can keep track of what it&#8217;s received from the server. In this case,  all the content is in the outbound message, and what&#8217;s coming back is an empty acknowledgement. But in an HTTP request, we&#8217;d see content in the outbound message &#8211; request headers, the type of request (GET, POST, etc.), the path to the web page we&#8217;re requesting, and any form data &#8211; and the response would have the HTML content of the web page.</p>
<h2>Shutting Down</h2>
<p>The one thing left to show you is what happens when we close the connection. If you hit <code>ctrl-c</code> in either terminal, you&#8217;ll see both the client and server exit immediately, but you&#8217;ll also see a bunch of traffic in tcpdump.</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="text"><pre class="de1">12:51:38.214610 IP localhost.59356 &gt; localhost.43981: Flags [F.], seq 30, ack 14, win 257, options [nop,nop,TS val 48593204 ecr 48590359], length 0
	0x0000:  4500 0034 d2b7 4000 4006 6a0a 7f00 0001  E..4..@.@.j.....
	0x0010:  7f00 0001 e7dc abcd 22f4 a012 a016 2063  ........&quot;......c
	0x0020:  8011 0101 fe28 0000 0101 080a 02e5 7934  .....(........y4
	0x0030:  02e5 6e17                                ..n.
12:51:38.215934 IP localhost.43981 &gt; localhost.59356: Flags [F.], seq 14, ack 31, win 256, options [nop,nop,TS val 48593205 ecr 48593204], length 0
	0x0000:  4500 0034 6d13 4000 4006 cfae 7f00 0001  E..4m.@.@.......
	0x0010:  7f00 0001 abcd e7dc a016 2063 22f4 a013  ...........c&quot;...
	0x0020:  8011 0100 fe28 0000 0101 080a 02e5 7935  .....(........y5
	0x0030:  02e5 7934                                ..y4
12:51:38.215994 IP localhost.59356 &gt; localhost.43981: Flags [.], ack 15, win 257, options [nop,nop,TS val 48593205 ecr 48593205], length 0
	0x0000:  4500 0034 d2b8 4000 4006 6a09 7f00 0001  E..4..@.@.j.....
	0x0010:  7f00 0001 e7dc abcd 22f4 a013 a016 2064  ........&quot;......d
	0x0020:  8010 0101 fe28 0000 0101 080a 02e5 7935  .....(........y5
	0x0030:  02e5 7935                                ..y5</pre></div></div></div></div></div></div></div>


<p>We&#8217;ve sent a couple more messages back and forth (&#8220;how&#8217;s it going?&#8221;, &#8220;pretty good!&#8221;), so the Sequence and Acknowledgement numbers have jumped ahead a bit, as have the timestamps.</p>
<p>The real action here is in the TCP flags, the 2nd byte in the 0&#215;0020 row. The ACK bit is still set, but now the FIN bit is too. That&#8217;s the client telling the server to close the connection. The server sends back a response with the FIN bit set, and the client sends a simple acknowledgement. It&#8217;s the same send-acknowledge-confirm exchange that we saw in the opening handshake.</p>
<h2>Wrapping Up, Moving On</h2>
<p>Ok, so that&#8217;s been a lot of to absorb, but what I hope you&#8217;ve gotten out of this is that all these internet protocol details are interestingly complex, but totally comprehensible. You&#8217;ve got the tools to look under the hood, and with a bit of patience you can figure out what all the parts are doing.</p>
<p>If you haven&#8217;t actually run through this little netcat/tcpdump exercise on your own terminal, give it a try. You don&#8217;t need to pick through it byte-by-byte like I have. Just take a couple minutes to watch the packets go back and forth, and skim the summary lines. That gave me a sort of visceral sense of what&#8217;s going on.</p>
<p>If you do want to dig into this more, try pointing tcpdump at a real service. Set up a minimal web page on your local web server, point tcpdump at port 80, and hit the page with your browser. I just tried that myself, and I think it&#8217;s going to keep me busy for a while.</p>
<p><em>Thanks to <a href="http://www.troodon-software.com/">Frank Hunleth</a> for corrections to the original version of this post.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2013/04/27/unpacking-packets/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>New Line of Inquiry</title>
		<link>http://www.bluegraybox.com/blog/2013/04/21/new-line-of-inquiry/</link>
		<comments>http://www.bluegraybox.com/blog/2013/04/21/new-line-of-inquiry/#comments</comments>
		<pubDate>Sun, 21 Apr 2013 10:25:13 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[personal]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=300</guid>
		<description><![CDATA[I&#8217;m starting on a new line of inquiry here. I&#8217;ve been doing web applications and unix systems programming for about 15 years now. Computer and network security has always been an aspect of what I do, but it&#8217;s never been my focus. I&#8217;m thinking it&#8217;s time to change that. I&#8217;m looking for a challenge, something [...]]]></description>
				<content:encoded><![CDATA[<p>I&#8217;m starting on a new line of inquiry here.</p>
<p>I&#8217;ve been doing web applications and unix systems programming for about 15 years now. Computer and network security has      always been an aspect of what I do, but it&#8217;s never been my focus. I&#8217;m thinking it&#8217;s time to change that. I&#8217;m looking for a   challenge, something that will keep me busy and learning for the rest of my life. Security is an unending struggle on an     ever-changing field. I want to be doing something useful, and security is becoming more and more of an issue in daily life.</p>
<p>I&#8217;ve always been a generalist, and security seems to be a field where that&#8217;s valuable. It&#8217;s not about using one tool to do a specific job; it&#8217;s about understanding systems at multiple levels, how things interact and how they fail. It&#8217;s about how     people interact with technology. It&#8217;s creative: there&#8217;s a lot of design that goes into making software both secure and       usable.</p>
<p>I have a lot to learn; like I said, this has never been my focus. I need to understand unix systems and networking protocols at a much deeper level than I have before. I&#8217;ve said for years that you don&#8217;t learn anything from a working system. It&#8217;s     when something fails that you have to go in under the hood and learn how it actually works. A corollary to that is that you  need to really understand a system to figure out how it can break, or how it can be broken intentionally.</p>
<p>&#8220;Under the hood&#8221; means that I need to dust off my C programming chops and set aside the layers of abstraction that I&#8217;m used  to. There&#8217;s also a lot of lore and literature specific to computer security that I need to absorb. There are tools for both  attack and defense that I need to play with.</p>
<p>The best way to learn something is to try to explain it, so that&#8217;s what I&#8217;m going to do here. Let me know if it makes sense, if it&#8217;s useful. Let me know where there are gaps or unanswered questions, or where I&#8217;m just plain wrong.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2013/04/21/new-line-of-inquiry/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Amateur Erlang</title>
		<link>http://www.bluegraybox.com/blog/2013/02/18/amateur-erlang/</link>
		<comments>http://www.bluegraybox.com/blog/2013/02/18/amateur-erlang/#comments</comments>
		<pubDate>Mon, 18 Feb 2013 19:43:34 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[erlang]]></category>

		<guid isPermaLink="false">http://www.bluegraybox.com/blog/?p=289</guid>
		<description><![CDATA[This is based on the talk I gave at ErlangDC. I don&#8217;t actually make my living programming Erlang, so I&#8217;m still a beginner in a lot of ways. I&#8217;ve been tinkering with it for the last year and a half or so, and in short, it&#8217;s been awesome. I&#8217;ve had a lot of fun; I&#8217;ve [...]]]></description>
				<content:encoded><![CDATA[<p><em>This is based on the talk I gave at <a href="http://erlangdc.com/2013/talks/colin_macdonald/">ErlangDC</a></em>.</p>
<p>I don&#8217;t actually make my living programming Erlang, so I&#8217;m still a beginner in a lot of ways.  I&#8217;ve been tinkering with it for the last year and a half or so, and in short, it&#8217;s been awesome. I&#8217;ve had a lot of fun; I&#8217;ve learned a ton, and what I&#8217;ve learned has been more broadly useful than I might have expected; and overall it&#8217;s definitely made me a better programmer.</p>
<p>So I&#8217;m going to talk about that experience: what you learn when you learn Erlang; some of the &#8220;ah-ha!&#8221; moments I&#8217;ve had &#8211; things that will give you a running start at the Erlang learning curve; and how to get some practical experience with Erlang before you dive into writing distributed, high-availability systems.</p>
<h2>Foreign Travel</h2>
<p>Learning a new programming language is like going to a foreign country. It&#8217;s not just the language, it&#8217;s the culture that goes with it. They do things differently over there. If you just drop in for a day trip, it&#8217;s going to be all weird and awkward; but if you stick around a bit, you start getting used to it; and when you go home, you find that there are things you miss and things that you&#8217;ve brought home with you.</p>
<p>There&#8217;s also a sort of meta-learning, because then when you go to a different country, it&#8217;s not as jarring; you adapt more quickly. I found that once I&#8217;d gotten used to Erlang&#8217;s syntax, other languages &#8211; Coffeescript and Scala &#8211; didn&#8217;t look so weird. At work the other day, someone was doing a demo of iPhone development, and some of my co-workers were really thrown by Objective-C&#8217;s syntax. I was just like, &#8220;Oh yeah, now that you mention it, it does have an odd mix of Lisp-style bracket grouping and C-style dot notation. Whatever. It&#8217;s code.&#8221;</p>
<p>Working with Erlang also teaches you a fundamentally different way of solving problems, especially if, like me, you&#8217;re coming from an object-oriented (OO) background like Java or Python. It has functional language features like recursion and closures. It focuses on simple data structures, and gives you powerful tools for working with them. And it&#8217;s all about concurrency. Those all add up to something more than the sum of their parts. They&#8217;re also things that translate to other languages: You&#8217;ll see Erlang-style concurrency in Scala, and functional programming is showing up all over the place these days.</p>
<h3>Bowling</h3>
<p>A good example of this is the bowling game program. I&#8217;ve <a href="http://www.bluegraybox.com/blog/2011/11/25/elegant-bowling/">written about this before</a>, so let me just recap it quickly. It&#8217;s a standard programming challenge: Calculate the score for a game in bowling. It&#8217;s fairly straightforward, but there are a bunch of tricky edge cases. The first time I did it was in Python as a pair programming exercise, and at the end I was pretty happy with the results. It came out to 53 lines of code. Then about a year later, we did the same thing at one of the Erlang meetups, and the solution that one of the experienced Erlang programmers turned in was about ten lines of code. Ten lines of clean, elegant code, not like a Perl one-liner. That blew my mind.</p>
<p>I went back and looked at the Python code and realized how much of it was OO modeling that doesn&#8217;t actually help solve the problem. In fact, it creates a bunch of its own problems. Obviously, you need a Game class and a Frame class, and the Game keeps a list of Frames. Then you very quickly get into all these metaphysical questions around whether a Frame should just be a dumb data holder, or whether it should be a fully self-actualized and empowered being, capable of accessing other frames to calculate its score and detect bad data. Putting all the smarts in the Game may be the easiest thing, but that brings up historical echoes of failed Soviet central planning, and just doesn&#8217;t feel very OO. And once you&#8217;ve got these classes, you start speculating about possible features: What if you want to be able to query the Game for a list of all the rolls &#8211; does that change how you store that info? In short, you can get really wrapped around the axle with all these design issues.</p>
<p>The Erlang solution sidesteps that whole mess. It just maps input to output. The input is a list of numbers, the output is a single number. That sounds like some kind of fold function. With pattern matching, you write that as one function with four clauses: End of game, strike frame, spare frame, normal 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="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="co1">%% Game complete.</span>
<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="co1">%% Strike.</span>
<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="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="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="co1">%% Spare.</span>
<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="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="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="co1">%% Normal.</span>
<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>
&nbsp;
 <span class="co1">%% spare &amp; strike bonus calculations.</span>
<span class="re3">spare_bonus</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="re5">First</span><span class="sy1">.</span>
<span class="re3">strike_bonus</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="br0">&#41;</span> <span class="sy1">-&gt;</span> <span class="re5">First</span> <span class="sy3">+</span> <span class="re5">Second</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<h3>Bringing it Home</h3>
<p>The thing is, once I&#8217;d seen the solution in Erlang, I was able to go back and implement it in Python; it came out to roughly the same number of lines of code, and was about as readable. That transfers, that way of solving problems. Instead of thinking, &#8220;What are the classes I need to model this problem domain?&#8221; start with, &#8220;What are my inputs and outputs? What&#8217;s the end result I want, and what am I starting from? Can I do that with simple data structures?&#8221;</p>
<p>So now when I write Python code, I use list comprehensions a lot more; <code>for</code> loops feel kinda sketchy &#8211; clumsy and error-prone. Modifying a variable instead of creating a new one sets off this tiny warning bell. I use annotations and lambda functions more often, and wish I had tail recursion and pattern matching. I do more with lists and dictionaries; defining classes for everything feels like boilerplate.</p>
<p>In the last year, I&#8217;ve also done a bunch of rich browser client Javascript programming with jQuery and Backbone.js. That&#8217;s a very functional style of programming. It&#8217;s all widget callbacks and event handling &#8211; lots of closures. (I don&#8217;t know who originally said it, but Javascript has been described as &#8220;Lisp with C syntax&#8221;.) Actually, I was coding in Coffeescript and debugging in Javascript. Coffeescript is essentially a very concise and strongly functional macro language for generating Javascript. So it was a really good thing to have the experience with Erlang going into that.</p>
<h3>Community</h3>
<p>The other thing about foreign travel is the people you meet. I&#8217;d like to make a little plug for the Erlang community. It&#8217;s still small enough to be awesome. Just lurk on the <a href="http://erlang.org/mailman/listinfo/erlang-questions">erlang-questions mailing list</a>, and you can learn a ton. There are some really sharp people on it, and the discussions are a fascinating mix of academic and practical. You see threads that wander from theoretical computer science to implementation details to performance issues.</p>
<h2>Ah-ha! Moments</h2>
<p>Like I said, Erlang has a different way of doing things. It&#8217;s not that it&#8217;s all that more complicated than other languages, but it&#8217;s definitely different. So I&#8217;m going to talk about some of the ah-ha! moments &#8211; the conceptual breakthroughs &#8211; that made learning it easier.</p>
<h3>Syntax</h3>
<p>I&#8217;ll start with the syntax, which is probably the least important difference, but it&#8217;s the first thing that people tend to get hung up on. They look at Erlang code, and they&#8217;re all like, &#8220;Where are the semicolons? What are all these commas doing here? Where are the curly braces?&#8221; It all seems bizarre and arbitrary. It&#8217;s not. It&#8217;s just not like C.</p>
<p>What helped me get used to Erlang&#8217;s syntax was realizing that what it looks like is English. Erlang functions are like sentences: You have commas between lists of things, semicolons between clauses, and a period at the end. Header statements like <code>-module</code> and <code>-define</code> all express a complete thought, so they end with a period. A function definition is one big multi-line sentence. Each line within it ends with a comma, function clauses end with a semicolon, and there&#8217;s a period at the end. <code>case</code> and <code>if</code> blocks are like mini function definitions: They separate their conditions with semicolons and end with <code>end</code>. <code>end</code> *is* the puctuation; you don&#8217;t put another semicolon before it. After <code>end</code>, you put whatever punctuation would normally go there.</p>
<p>You also have to realize that all the things you think of as control structures &#8211; <code>case</code>, <code>if</code>, <code>receive</code>, etc. &#8211; are functions.</p>
<p>Here&#8217;s a cheat sheet:</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>my_module<span class="br0">&#41;</span><span class="sy1">.</span>
&nbsp;
<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="re5">Value</span> <span class="sy3">=</span> <span class="kw3">get</span>_<span class="re3">default_value</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy1">,</span>          <span class="co1">% comma</span>
    <span class="re5">Response</span> <span class="sy3">=</span> <span class="kw1">case</span> <span class="re3">other_func</span><span class="br0">&#40;</span><span class="re5">Value</span><span class="br0">&#41;</span> <span class="kw1">of</span>
        ok <span class="sy1">-&gt;</span> <span class="st0">&quot;We're good!&quot;</span><span class="sy1">;</span>              <span class="co1">% semicolon</span>
        <span class="re5">_</span> <span class="sy1">-&gt;</span> <span class="st0">&quot;Oh noes!&quot;</span>                   <span class="co1">% nothing!</span>
    <span class="kw1">end</span><span class="sy1">,</span>                                  <span class="co1">% comma</span>
    <span class="br0">&#123;</span><span class="re5">Response</span><span class="sy1">,</span> <span class="re5">Value</span><span class="br0">&#125;</span><span class="sy1">;</span>                    <span class="co1">% semicolon</span>
<span class="re3">my_func</span><span class="br0">&#40;</span><span class="br0">&#91;</span><span class="re5">Value</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="br0">&#123;</span><span class="st0">&quot;We're good!&quot;</span><span class="sy1">,</span> <span class="re5">Value</span><span class="br0">&#125;</span><span class="sy1">;</span>               <span class="co1">% semicolon</span>
<span class="re3">my_func</span><span class="br0">&#40;</span><span class="re5">Values</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="re5">IncDbl</span> <span class="sy3">=</span> <span class="kw1">fun</span> <span class="br0">&#40;</span><span class="re5">X</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
        <span class="re5">Inc</span> <span class="sy3">=</span> <span class="re5">X</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span>                      <span class="co1">% comma</span>
        <span class="re5">Inc</span> <span class="sy3">*</span> <span class="nu0">2</span>                           <span class="co1">% nothing!</span>
    <span class="kw1">end</span><span class="sy1">,</span>                                  <span class="co1">% comma</span>
    <span class="re5">Value</span> <span class="sy3">=</span> <span class="kw5">lists</span>:<span class="re3">map</span><span class="br0">&#40;</span><span class="re5">IncDbl</span><span class="sy1">,</span> <span class="re5">Values</span><span class="br0">&#41;</span><span class="sy1">,</span>    <span class="co1">% comma</span>
    <span class="br0">&#123;</span><span class="st0">&quot;We're good!&quot;</span><span class="sy1">,</span> <span class="re5">Value</span><span class="br0">&#125;</span><span class="sy1">.</span>               <span class="co1">% period</span></pre></div></div></div></div></div></div></div>


<p>Even with that, it&#8217;s still pretty idiosyncratic. You&#8217;ll find yourself making a bunch of syntax mistakes at first, and that&#8217;ll be frustrating. Let me just say that you&#8217;ll get used to it faster than you expect. After a couple weekends hacking on Erlang code, it&#8217;ll start to look normal.</p>
<h3>Recursion</h3>
<p>Recursion is not something you use 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 modify 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 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, and it stops being scary.</p>
<p>This is also where Erlang&#8217;s weirdnesses start working together. 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 more 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 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. When the input is an empty list, just return the 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">%% 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 &#8211; it&#8217;s an efficiency thing.)</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>
<p>As a coda to this, it&#8217;s worth mentioning that this is essentially what Erlang&#8217;s <code>lists:map/2</code> function does, so you could replace all the forgoing with 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="erlang"><pre class="de1"><span class="kw5">lists</span>:<span class="re3">map</span><span class="br0">&#40;</span><span class="kw1">fun</span> my_module:<span class="me2">munge</span><span class="sy3">/</span><span class="nu0">1</span><span class="sy1">,</span> <span class="re5">Input</span><span class="br0">&#41;</span></pre></div></div></div></div></div></div></div>


<p>The <code>lists</code> module has a number of other functions for doing simple list munging like this.</p>
<h3>More OO than OO</h3>
<p>The next thing is Erlang process spawning and inter-process communication. Again, this is one of those things that in normal languages is rarely used and fraught with peril. In Java, multithreaded applications involve a lot of painstaking synchronization, and you still often get bit by either concurrent modification errors or performance issues from overly aggressive locking. In Erlang of course, you do it all the time. Understanding why requires a bit of background.</p>
<p>The original concept of object oriented programming was that objects would be autonomous actors rather than just data structures. They would interact with each other by sending messages back and forth. You see artifacts of this like Ruby&#8217;s <code>send</code> method. (Rather than invoking a method directly, you call <code>send</code> on the object with the method name as the first argument.) In practice, objects in OO languages are little more than data structures with function definitions bolted on. They&#8217;re not active agents; they&#8217;re passive, waiting around for a thread of execution to come through and do something to them.</p>
<p>In a sense, Erlang is more truly object oriented than OO languages, but you come to it by a roundabout way. Since even complex data structures are immutable, updating your data always creates a new reference to it. If you pass any data structure to a function, as soon as it modifies it, it&#8217;s dealing with a different data structure. So the only way to have something like global, mutable data is to have that reference owned by a single process and managed 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="re3">loop</span><span class="br0">&#40;</span><span class="re5">State</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw1">receive</span> <span class="re5">Message</span> <span class="sy1">-&gt;</span>
        <span class="re5">NewState</span> <span class="sy3">=</span> <span class="re3">handle_message</span><span class="br0">&#40;</span><span class="re5">Message</span><span class="sy1">,</span> <span class="re5">State</span><span class="br0">&#41;</span><span class="sy1">,</span>
        <span class="re3">loop</span><span class="br0">&#40;</span><span class="re5">NewState</span><span class="br0">&#41;</span>
    <span class="kw1">end</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>(You wouldn&#8217;t literally have code like this, but it&#8217;s conceptually what you&#8217;re doing.) <code>State</code> is any data structure, from an integer to a nested tuple/list/dictionary structure. You&#8217;d spawn this loop function as a new process with its initial state data. From then on it would receive messages from other processes, update its state, maybe send a respose, and then recurse with the new state. The key here is that it&#8217;s a local variable to this function; there&#8217;s no way for any other process to mess with it directly. If you spawn another process with this function, it will have a separate copy of the <code>State</code>, and any updates it makes will be completely independent of this. The simplest example I can think of would be an auto-incrementing id generator:</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">Id</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw1">receive</span>
        <span class="br0">&#123;</span><span class="re5">Pid</span><span class="sy1">,</span> next<span class="br0">&#125;</span> <span class="sy1">-&gt;</span>
            <span class="re5">NewId</span> <span class="sy3">=</span> <span class="re5">Id</span> <span class="sy3">+</span> <span class="nu0">1</span><span class="sy1">,</span>
            <span class="re5">Pid</span> <span class="sy3">!</span> <span class="re5">NewId</span><span class="sy1">,</span>
            <span class="re3">loop</span><span class="br0">&#40;</span><span class="re5">NewId</span><span class="br0">&#41;</span>
    <span class="kw1">end</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<p>You could start it up and get new ids 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="re5">Pid</span> <span class="sy3">=</span> <span class="kw3">spawn</span><span class="br0">&#40;</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="nu0">0</span><span class="br0">&#41;</span> <span class="kw1">end</span><span class="br0">&#41;</span><span class="sy1">,</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> next<span class="br0">&#125;</span><span class="sy1">,</span>
<span class="re5">Id</span> <span class="sy3">=</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>


<p>So anything that would be an object in an OO language is a process in Erlang. I hadn&#8217;t realized quite how true that was until I was messing around in the Erlang shell, and opened a file. <code>file:open/2</code> says it returns <code>{ok, IoDevice}</code> on success. Let&#8217;s take a look at 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="nu0">1</span><span class="sy3">&gt;</span> <span class="kw5">file</span>:<span class="re3">open</span><span class="br0">&#40;</span><span class="st0">&quot;test.txt&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span>write<span class="br0">&#93;</span><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></pre></div></div></div></div></div></div></div>


<p>Hey, wait! That&#8217;s a process id. See?</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">2</span><span class="sy3">&gt;</span> <span class="kw3">self</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy1">.</span>
<span class="sy3">&lt;</span>0<span class="sy1">.</span>32<span class="sy1">.</span>0<span class="sy3">&gt;</span></pre></div></div></div></div></div></div></div>


<p>So when you open a file, you don&#8217;t actually access it directly; you&#8217;re spawning off a process to manage access to it.</p>
<p>As with recursion and the <code>lists</code> module, Erlang has modules like <code>gen_server</code> and <code>gen_event</code> which gieve you a more formal and standard way to do this sort of thing. They add a lot of process management on top of this basic communication, so I won&#8217;t get into the details here, but check it out.</p>
<h2>Getting Practice</h2>
<p>Ok, so once you&#8217;ve gotten past the language concepts, how can you actually get some practice with it? Something a little more low-key than massively distributed high-availability systems?</p>
<h3>Scripting</h3>
<p>Probably the easiest way to start, if you just want to get comfortable with the language, is shell scripting. <code>escript</code> lets you use Erlang as a scripting language.</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="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<span class="es0">\t</span>~p~n&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">Args</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 pretty cool. You have the ease of scripting, with full access to Erlang&#8217;s libaries. Furthermore, you can set a node name or sname in your script, and then it can connect to other Erlang nodes. (The special <code>%%!</code> comment says to pass the rest of the line through as parameters to <code>erl</code>, the Erlang emulator.)</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="co1">%%! -sname my_script</span></pre></div></div></div></div></div></div></div>


<p>For example, here&#8217;s a simple way to grab a web page:</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="re5">Url</span><span class="br0">&#93;</span><span class="br0">&#41;</span> <span class="sy1">-&gt;</span>
    <span class="kw5">inets</span>:<span class="re3">start</span><span class="br0">&#40;</span><span class="br0">&#41;</span><span class="sy1">,</span>
    <span class="br0">&#123;</span>ok<span class="sy1">,</span> <span class="br0">&#123;</span><span class="br0">&#123;</span><span class="re5">_Proto</span><span class="sy1">,</span> <span class="re5">Code</span><span class="sy1">,</span> <span class="re5">_Desc</span><span class="br0">&#125;</span><span class="sy1">,</span> <span class="re5">_Hdr</span><span class="sy1">,</span> <span class="re5">Content</span><span class="br0">&#125;</span><span class="br0">&#125;</span> <span class="sy3">=</span> http<span class="kw5">c</span>:<span class="re3">request</span><span class="br0">&#40;</span><span class="re5">Url</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;Response (~p):~n~s~n&quot;</span><span class="sy1">,</span> <span class="br0">&#91;</span><span class="re5">Code</span><span class="sy1">,</span> <span class="re5">Content</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 actually pretty handy because you can fetch data from web services that way. I started with this and built out a really simple automated testing tool for a web service I was writing, in about 20 lines of code. You can do all sorts of useful little things like this. They&#8217;re a good way to get used to Erlang&#8217;s idioms, and you can gradually build in more complexity as you go.</p>
<h3>Testing Tools</h3>
<p>In fact, testing tools are another way to get in some real experience with Erlang. You could do something simple to test web service functionality, or something more complicated and concurrent for load testing.</p>
<p>You could also mock out back-end web services for testing. I was doing some browser-side Javascript development last summer, and didn&#8217;t have access to the server I&#8217;d be talking to. (It was running on an embedded device.) So I faked it up in Erlang with <a href="https://github.com/flashingpumpkin/spooky">Spooky</a> , which is a simple Sinatra-style framework. It went something 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="sy3">-</span><span class="re2">module</span><span class="br0">&#40;</span>my_web_service<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>
&nbsp;
<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="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>
&nbsp;
<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="re5">Req</span>:<span class="re3">ok</span><span class="br0">&#40;</span><span class="st0">&quot;Default response&quot;</span><span class="br0">&#41;</span><span class="sy1">;</span>
<span class="co1">%% http://localhost:8000/path/to/resource</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;path&quot;</span><span class="sy1">,</span> <span class="st0">&quot;to&quot;</span><span class="sy1">,</span> <span class="st0">&quot;resource&quot;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">-&gt;</span>
    <span class="re5">Req</span>:<span class="re3">ok</span><span class="br0">&#40;</span><span class="st0">&quot;Canned response for resource&quot;</span><span class="br0">&#41;</span><span class="sy1">;</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;path&quot;</span><span class="sy1">,</span> <span class="st0">&quot;to&quot;</span><span class="sy1">,</span> <span class="st0">&quot;other-resource&quot;</span><span class="br0">&#93;</span><span class="br0">&#41;</span><span class="sy1">-&gt;</span>
    <span class="re5">Req</span>:<span class="re3">ok</span><span class="br0">&#40;</span><span class="st0">&quot;Canned response for other resource&quot;</span><span class="br0">&#41;</span><span class="sy1">.</span></pre></div></div></div></div></div></div></div>


<h3>Web Apps</h3>
<p>If you&#8217;re coming from a web background, that&#8217;s another good place to start tinkering with Erlang. Instead of trying to think up an Erlang project, just do your next personal web app in Erlang. Erlang has a range of web application frameworks, so you can decide how much of the heavy lifting you want to do. As you saw, Spooky lets you simple stuff easily, but it&#8217;s fairly low-level.</p>
<p><a href="http://www.chicagoboss.org/">ChicagoBoss</a> is a richer, Django-like framework. It has an ORM, URL dispatching, and page templates (with Django syntax, no less). Wait, _Object_-Relational Mapper? What&#8217;s that doing in a functional language? Yeah, ok, really they&#8217;re proplists with a parameterized module and a bunch of auto-generated helper functions wrapped around them. They&#8217;re still immutable; don&#8217;t freak out. More experienced developers may argue about whether that&#8217;s the right way to do things, but it certainly makes ChicagoBoss more beginner-friendly.  It also gives you some enticing extras like a built-in message queue and email server. The ChicagoBoss tutorial is really concise and well-written, so I&#8217;ll leave it at that.</p>
<p>If you want to get into the nuts and bolts of proper HTTP request handling, take a look at <a href="https://github.com/basho/webmachine/wiki">WebMachine</a>. Most web frameworks leave out or gloss over a lot of the richness of the HTTP protocol. WebMachine not only gives you a lot of control over every step of the request handling, but actually forces you to think through it. It&#8217;s not the most intuitive for beginners, but it&#8217;s an education.</p>
<p>Those are the ones I&#8217;ve played with a bit, but there are lots more.</p>
<h3>Contributing</h3>
<p>One of the things I&#8217;ve run across with these, as with most open-source tools, is that there are &#8220;opportunities to contribute.&#8221; We&#8217;d love it if all of our software tools worked perfectly all the time, but the next best thing is if the source is on GitHub. Working with Spooky, I tripped over an odd little edge case. It turned out to be a simple fix &#8211; half a dozen lines of code. I forked it, fixed it, and put in a pull request. Had a similar experience with the ChicagoBoss templating code. They were both tiny contributions, but you still get a warm fuzzy feeling doing that. Throw in a few extra unit tests if you really want to make the owners happy.</p>
<p>Even if you&#8217;re unlucky, and the code works perfectly, almost every piece of software out there could benefit from better documentation. Take advantage of your newbie status; write a tutorial. The people who wrote the software know it inside and out; it helps to have beginners writing for beginners. I can vouch that a great way to learn something is to try to explain it to someone else.</p>
<h3>Adventure Awaits!</h3>
<p>What I hope I&#8217;ve left you with is a sense that Erlang is worth learning in its own right, that it&#8217;ll teach you new things about programming that you can apply in any language; that while it&#8217;ll be strange at first, it&#8217;s totally learnable; and that there are any number of low-intensity ways to get started using it. Most importantly, though, I want to leave you with the sense that this is fun. Learning a new language, new problem-solving tools, new ways of expressing ideas, that&#8217;s all fun. You&#8217;ve got an adventure ahead of you.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2013/02/18/amateur-erlang/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Remedial Javascript</title>
		<link>http://www.bluegraybox.com/blog/2012/05/10/remedial-javascript/</link>
		<comments>http://www.bluegraybox.com/blog/2012/05/10/remedial-javascript/#comments</comments>
		<pubDate>Thu, 10 May 2012 12:52:45 +0000</pubDate>
		<dc:creator>colin</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[javascript]]></category>

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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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

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

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

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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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

http://localhost:8000/add/Player/Roll

</pre>
<p>So for example:</p>
<pre>

http://localhost:8000/add/colin/4

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


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


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


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


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


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


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


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


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


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


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


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


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

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


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


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

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


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


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


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


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


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


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


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


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


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


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


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


<p>And would you really? The original Python version looks fine; the second one is actually uglier, with its multiple returns. It&#8217;s not just a matter of what&#8217;s possible in a language, or what&#8217;s more conceptually elegant; it&#8217;s what the language can express cleanly and easily, and what&#8217;s familiar to its developer community.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bluegraybox.com/blog/2011/11/08/fizzbuzz/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
