<?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/"
	>

<channel>
	<title>Stifflog</title>
	<atom:link href="http://www.stifflog.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.stifflog.com</link>
	<description>Just another WordPress weblog</description>
	<pubDate>Thu, 26 Aug 2010 19:14:50 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Thinking in APIs</title>
		<link>http://www.stifflog.com/2010/08/26/thinking-in-apis/</link>
		<comments>http://www.stifflog.com/2010/08/26/thinking-in-apis/#comments</comments>
		<pubDate>Thu, 26 Aug 2010 18:36:52 +0000</pubDate>
		<dc:creator>stiff</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.stifflog.com/?p=89</guid>
		<description><![CDATA[Recently I had a little piece of general functionality to implement at work, in a web application I develop - we wanted to be able to trigger various events on the client side (for example pop-up a lightbox-style window), the catch being that the events were to be triggered on the server side, not directly [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I had a little piece of general functionality to implement at work, in a web application I develop - we wanted to be able to trigger various events on the client side (for example pop-up a lightbox-style window), the catch being that the events were to be triggered on the server side, not directly in response to a client request. It is nothing too fancy to implement, a little queue in the database for the actions to trigger + setting up long-pooling in the clients browser suffices as the first attempt. However, I experimented with 2 or 3 designs for this to make it more convenient to use and in the process I realized something I think may be worth sharing.</p>
<p>Consider a typical small software project - a few programmers working together on a single project for a prolonged period of time. Requests for new features are coming in from a customer every few weeks. Some of the requests are probably similar in some ways, so people will want to build reusable modules for the most common tasks. Immediately, perhaps the single biggest problem of software development comes into play - <strong>communication</strong>.<span id="more-89"></span></p>
<p>As a typical software project grows, an implicit &#8220;design&#8221; emerges from every programmer building tiny APIs only with his/her own use in mind, giving raise to problems:</p>
<ul>
<li>Many different APIs will get created for doing the same things. If you do not explicitly agree to have a library for a particular common task, everybody will create their own little &#8220;libraries&#8221;.</li>
<li>There will be many components sharing parts of the functionality, but each having its own code for achieving it. This code could instead form a shared API and decrease the overall amount of work it would take to build those components. If you don&#8217;t explicitly try to design APIs together with normal project development, you will miss many occasions for code reuse.</li>
</ul>
<p>The longer the project is developed, the worse the effects of the above are. In the end, the system takes more time to build then necessary, maintaining and extending it is harder and the overall design is much more complex, as various aspects of the functionality aren&#8217;t separated clearly enough.</p>
<p>Why is it this way? I think there are three keywords that lead to the answer:</p>
<ol>
<li><strong>Perspective</strong> - without conscious effort, one tends to have the &#8220;just get the task done&#8221; perspective on software. Programmers don&#8217;t ordinarily think of the code they write as of something that is meant for other people to use directly, but as of an mean to make the computer do a particular thing - it is both.</li>
<li><strong>Communication</strong> - very often team members simply don&#8217;t know each others work, do not agree on common practices or on places to look for documentation and don&#8217;t build modules to be used by everyone, even for the most common little tasks.</li>
<li><strong>Technical skills</strong> - building modules other people will want do use requires particular skills that can only be acquired by continuous practice and proper training.</li>
</ol>
<p>I think that the true indicator of a successful programming team, is people using each others code without anyone explicitly urging anyone else to do so. This can be achieved only be everyone having the necessary skills individually and by having appropriate procedures and conventions in place for the whole team. What I want to encourage in this article, is a shift of perspective that will emphasize communication and a set of best practices to help one acquire the technical skills needed to build clean software as a member of a larger team.</p>
<p>Try the following: the next time you are done with a piece of work you have done in your usual way, try to take a look at it as if you were designing an API for other programmers to do similar things to the one you just implemented. Try to really get into skin of another person trying to modify your code or use it for his/her own purposes. Is it clear what the code does? Are the parts well separated? I put together a set of specific guidelines to help one design programs with this API perspective in mind:</p>
<ol>
<li><strong>Look for abstractions.</strong> This is the key point, with each given task, one has to decide if it is a specific instance of some more general problem, how much additional effort does solving the general problem take (sometimes the general one is simpler to solve than the specific one!) and if it is worth to design an API for tasks of this kind. It takes some experience, which comes from a lot of experimentation, to recognize the situations where generalization is worth it. Sometimes the whole &#8220;API&#8221; you may extract from the task at hand is a single method to format the date in a consistent way across the whole project.</li>
<li><strong>Split things into pieces.</strong> It is surprising how underused are the simplest ways of managing complexity, like splitting modules into separate files, splitting methods into smaller ones, distributing code across classes and so on. To avoid every team member &#8220;reinventing the wheel&#8221;, the modules for common tasks have to be easy to find by just browsing the source tree. If you have your date function in a &#8220;date.c&#8221; file it is much easier to find it, than if it is in an &#8220;utils.c&#8221; file. Think of it - if you don&#8217;t see an obvious place where to look for a method you need, you will most probably assume it doesn&#8217;t exist at all and proceed with writing your own one. Every project has some files or directories that are just there to keep things that people do not know where to put,  with names like &#8220;utils&#8221;, &#8220;misc&#8221; etc. A good first exercise in API design would be to take such a file and split it into well-named modules, preferably until there is no need for &#8220;utils&#8221; at all anymore.</li>
<li><strong>Use design methods other then just direct experimentation with code.</strong> You don&#8217;t have the right perspective to do API-level design when looking at your individual classes or functions. I like text-based approaches - a short spec of the public interface of the code you added, consisting of a list of classes/methods with short descriptions might already give you some new insights. Pseudocode can be very helpful when doing lower-level design. You may try UML diagrams, informal pictures, mind-maps or anything else you think may work.</li>
<li><strong>Document and communicate your APIs.</strong> You have to agree with other team members on a place where all of you will list and document the APIs you create - perhaps a Wiki page. Let each of the members put descriptions of their modules there. Over time, see if they use your modules or not, if they have any problems with them and so on. This is invaluable feedback on what is good about your code and what isn&#8217;t. Every week let one person (alternating between all team members) review all the code added during this week and write an e-mail summarizing any issues found.</li>
<li><strong>Keep consistent.</strong> Remember you are programming things for other people. They did not build the API you provided them, so they will certainly make guesses about how it works. To make it easier for them to comprehend your API, you have to strive for maximum consistency to make their guesses right as often as possible. This is in the spirit of &#8220;The principle of least surprise&#8221;.</li>
<li><strong>Clearly state contracts and signal their violations.</strong> In a similar way to 4., the pre- and post- conditions that were obvious to you during writing the code, may not be obvious to other people, so you have to state them explicitly, to make sure that your users immediately know when they are misusing your API. Don&#8217;t be afraid to define and use a few custom exception classes for every larger general module you build, it will pay-off very quickly.</li>
<li><strong>Write tests.</strong> A module will not really be general and reusable unless it is really well tested. It might be that the API you created works well for your particular problem, but will it also work correctly for a similar one? You have to make sure that what the API promises to do for the user really holds true.</li>
<li><strong>Provide extensions points.</strong> If you work on a single project for a longer time, you might sometimes see in advance the ways in which you or other people will want to extend something in the future. You might also have some intuition for what pieces of the program are most likely to change. It is possible to take some steps ahead of time and provide explicit extension points, for example allow the API user to define callbacks that will be used at particular moments of your API operation. In fact, if you have striven for a clear design for some functionality, it might well be that some natural extension points are already in place and if you would extend your code yourself you would use them. The point is to make them explicit and documented, so other people who do not know the merits of your design, but have to extend upon your code, know they exist.</li>
<li><strong>Avoid over-generalization.</strong> All of the above points can be misunderstood or misapplied. There are situations where generalization does not make a system cleaner, in fact it does the opposite. Unfortunately, I do not see a clear rule here, this is again a place where you acquire the necessary intuition by experience and experimentation.</li>
</ol>
<p><strong>Further resources</strong></p>
<p>If you listen carefully to experienced programmers, you might find traces of what I have written in what they say. The closest to saying it directly I think is Joshua Bloch in his presentation <a href="http://www.infoq.com/presentations/effective-api-design">How to Design a Good API</a>. There also two great books showcasing how to write really reusable code: <a href="http://www.amazon.com/Paradigms-Artificial-Intelligence-Programming-Studies/dp/1558601910">Paradigms Of Artificial Intelligence Programming</a> and <a href="http://www.amazon.com/Interfaces-Implementations-Techniques-Creating-Reusable/dp/0201498413">C: Interfaces and implementations</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stifflog.com/2010/08/26/thinking-in-apis/feed/</wfw:commentRss>
		</item>
		<item>
		<title>What is wrong with Ruby</title>
		<link>http://www.stifflog.com/2009/12/16/what-is-wrong-with-ruby/</link>
		<comments>http://www.stifflog.com/2009/12/16/what-is-wrong-with-ruby/#comments</comments>
		<pubDate>Wed, 16 Dec 2009 15:13:52 +0000</pubDate>
		<dc:creator>stiff</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.stifflog.com/?p=75</guid>
		<description><![CDATA[After using Ruby massively for a few years, I think I have now enough understanding to finally see its main flaw. As a starting point to try to see it too, consider mentally splitting the Ruby language into two parts - &#8220;programming part&#8221; and &#8220;metaprogramming part&#8221;. This is of course a fully artificial distinction, as [...]]]></description>
			<content:encoded><![CDATA[<p>After using Ruby massively for a few years, I think I have now enough understanding to finally see its main flaw. As a starting point to try to see it too, consider mentally splitting the Ruby language into two parts - &#8220;programming part&#8221; and &#8220;metaprogramming part&#8221;. This is of course a fully artificial distinction, as in reality they are closely tangled together, but I find such an attempt a useful experiment.</p>
<p>What I would consider a part of Ruby&#8217;s normal programming features are the things programmers who ship end-user applications use everyday - classes, objects, methods, loops, variables etc. The metaprogramming features are what is mostly used by people who build applications for other programmers, but normally not by the &#8220;average Joe&#8221;, so the techniques behind things like Rails, RSpec, Rake, Rack and other major Ruby frameworks and libraries. Much of the appeal of those projects lies in the elegance of the languages they make available to their users, making it easy to describe solutions to problems the given framework is targeting. The specific features I have in mind are things like metaclasses, instance_eval, class_eval, method_missing, alias_method an so on, all hidden behind an easy to use abstraction layer.<span id="more-75"></span></p>
<p>The big success of Ruby was that it enabled things like Rails to happen at all. They were languages before that could make frameworks of this kind possible, like Common Lisp or Smalltalk, but they never became mainstream and nothing similar in popularity and impact to Rails never was built around them. Ruby had some of the same capabilities of Lisp or Smalltalk, while being more accessible to the average Joe (or to the <a href="http://www.loudthinking.com/">not-so-average David</a>). It is interesting to consider how much syntax Ruby has - I am not strongly conviced about this myself, but after reading parts of Chomsky&#8217;s <a href="http://www.amazon.com/Language-Chomskys-Classic-Responsibility-Reflections/dp/1565844750">&#8220;On Language&#8221;</a> it occurred to me that maybe the more syntax a programming language has, the better it maps to the parts of our brains shaped by the syntax-rich natural languages. This would perhaps explain why Lisp or Smalltalk with their minimal syntax didn&#8217;t gain that much popularity despite their huge advantages. Instead they ended up being used mostly by people that have their brains already trained at thinking about things in different ways then just with natural language, for example people well versed in mathematics or physics, or specifically trained in programming with them for a prolonged period of time.</p>
<p>The problem I see is that the superiority of Ruby in the domain of creating programming frameworks or DSLs happened to a great extent accidentally. Ruby was not designed with things like Rails in mind and it is clearly visible now. The metaprogramming features are very specific and very chaotic, they do not form a coherent set of generic tools, the way the &#8220;programming part&#8221; of Ruby is a coherent set of generic tools for describing computations. People building advanced libraries like Rails have to use those features in ways they were not meant for.</p>
<p>You can see <a href="http://www.stifflog.com/2008/04/19/metaprogramming-ruby/">my metaprogramming presentation</a> for advanced examples of various Ruby oddities in this area, one simple example is the situation where you want to augument an existing method with some code around it. The way you do it in Ruby is by aliasing methods - the language feature you use has no relation to your intent. This is how it looks like:</p>
<pre>
<span class="keyword">def</span> <span class="function-name">wrapped_method</span>
  puts <span class="string">"2 + 2 = 4"</span>
<span class="keyword">end</span>

puts <span class="string">"Before augumentation"</span>
wrapped_method

puts

<span class="keyword">alias</span> <span class="constant">:old_wrapped_method</span> <span class="constant">:wrapped_method</span>

<span class="keyword">def</span> <span class="function-name">wrapped_method</span>
  puts <span class="string">"1 + 1 = 2"</span>
  old_wrapped_method
  puts <span class="string">"3 + 3 = 6"</span>
<span class="keyword">end</span>

puts <span class="string">"After augumentation"</span>
wrapped_method
</pre>
<p>The lack of an adequate programming &#8220;metalanguage&#8221; is what I consider the biggest flaw of Ruby, but also the most promising direction of programming languages development. It is good to look at some other languages and compare them in this respect. For example JavaScript can achieve some of the same metaprogramming capabilities of Ruby with much less language constructs - objects as hash-maps, first order functions, the ability to changes the context of a function etc. are all aplicable to a wide variety of problems without having the narrow nature of the Ruby techniques used to achieve the same effects.  Alan Kay has some very interesting things to say about this, so if you are interested in those topics, you may start with <a href="http://video.google.com/videoplay?docid=-2950949730059754521#">listening what he has to say</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stifflog.com/2009/12/16/what-is-wrong-with-ruby/feed/</wfw:commentRss>
		</item>
		<item>
		<title>An open platform for publishing applications</title>
		<link>http://www.stifflog.com/2009/11/24/an-open-platform-for-publishing-applications/</link>
		<comments>http://www.stifflog.com/2009/11/24/an-open-platform-for-publishing-applications/#comments</comments>
		<pubDate>Tue, 24 Nov 2009 19:47:03 +0000</pubDate>
		<dc:creator>stiff</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.stifflog.com/?p=26</guid>
		<description><![CDATA[HTTP, HTML and CSS are inadequate for developing complex end user applications that have hard latency requirements, depend on more sophisticated input-output facilities or need to integrate closely with the clients computing environment. Examples include games, multimedia or attempts to reproduce modern desktop applications on the web.
The failure to deliver browser-based applications in those domains [...]]]></description>
			<content:encoded><![CDATA[<p>HTTP, HTML and CSS are inadequate for developing complex end user applications that have hard latency requirements, depend on more sophisticated input-output facilities or need to integrate closely with the clients computing environment. Examples include games, multimedia or attempts to reproduce modern desktop applications on the web.</p>
<p>The failure to deliver browser-based applications in those domains is in my opinion caused by:</p>
<ul>
<li>
the weakness of the request-response scheme of HTTP as a basis for a   programming model - it works well for the operations on hypertext   documents it was designed for, but it is a poor basis in almost all   domains that do not naturally deal with documents, especially those   requiring sending excessive amounts of information back and forth
</li>
<li>
poor capabilities of the browser itself - what is being made   available to the programmer is insufficient for any kind of more   sophisticated development, as no access at all is given to important   parts of the user environment - neither to the hardware (graphic cards, sound cards, video cameras, gaming devices) nor to the software resources (files on the client computer)
</li>
</ul>
<p>Many technologies were created to deal with the two problems. AJAX, continuations-based web servers or Comet were attempts to workaround the first issue, but they all have been built on top of the flawed model, while also suffering problems with the web browsers, without trying to directly fix them. The second problem was meant to be solved by the likes of Flash or Silverlight, which do not integrate well with the rest of the web (for example search engines), making it questionable why do they at all run inside the web browser, experiencing efficiency and stability issues. Java the platform was the closest to what I want to propose, but even through it had the necessary pieces, it wasn&#8217;t clearly steered in this direction and suffered from slow start-up times, slow and ugly GUI tool-kits and weaknesses of Java the programming language.</p>
<p>The author is seeing much potential in an integrated attempt to solve both of those problems with a new set of standardized technologies. We already have excellent protocols for hypertext, efficient file transfer or sending messages, why shouldn&#8217;t a protocol for sharing applications exist? Links could be put to apps://musicplayer.com/ on traditional web pages in the same way as links to e-mail addresses or file servers, leaving the browsers with what they do best - processing documents.</p>
<p>The proposed solution that will be described here is called <i>OAPP</i>, standing for <i>Open Application Publishing Platform</i>. The following things should be specified as a part of <i>OAPP</i>:</p>
<ol>
<li>A virtual machine of predefined capabilities running on the client computer</li>
<li>A way of sending executable computer programs to the virtual machine from the server</li>
<li>A way of singalizing events on the virtual machine to the server</li>
<li>A programming model based on points 1, 2 and 3</li>
</ol>
<p><span id="more-26"></span></p>
<p>Having each aplication run in a separate virtual machine creates a common denominator for all the client platforms, while giving the possibility to privilege access to the sensitive parts of the clients environment. The virtual machine should not only deliver means of executing programs, but also give abstractions (libraries) over users hardware and software resources. In fact, applications could require additional libraries that would also be delivered on demand to the client from different <i>OAPP</i> servers. This forms a rich and fully programmable platform developers can target. This virtual machine, together with the libraries and an interface for choosing from the available programs, is in <i>OAPP</i> terms an <i>application browser</i>.</p>
<p>For a practical demonstration of the benefits of such approach, the <a href="http://code.google.com/p/v8/">V8 virtual machine</a> was chosen, both for the server and for the client. JavaScript is already well-known by web developers, while being a powerful programming language, in fact turning out to be surprisingly well suited for the problem. The quality of the virtual machine may decide about the success of the project and <a href="http://code.google.com/p/v8/">V8</a> with its beautiful design, very quick start-up time and some decent libraries already available seems to be a good candidate. The package <a href="http://nodejs.org/">Node.js</a> which provides a modified version of <a href="http://code.google.com/p/v8/">V8</a> will be used, as it contains networking support - to run one of the examples, just use the &#8216;node&#8217; executable with the name of the source file as an argument. Links to the source files can be found at the end of the article.</p>
<p>The <i>OAPP</i> communication protocol consists of <i>packets</i> in the form of JSON literals. For simplification of the examples packets are separated simply by three consecutive newline characters, while in practice a thin transport layer should be implemented, with the ability to store different applications under the same host name and to compress and encrypt the information being exchanged.</p>
<p>After a connection is established, the <i>OAPP</i> server sends the first packet with the initial code to the client. For example, a server delivering an application showing the start-up time looks like this:</p>
<pre>
<span class="keyword">var</span> <span class="variable-name">sys</span> = require(<span class="string">'sys'</span>);
<span class="keyword">var</span> <span class="variable-name">tcp</span> = require(<span class="string">'tcp'</span>);

<span class="keyword">function</span> <span class="function-name">remoteClosure</span>(<span class="js2-function-param">fun</span>, <span class="js2-function-param">variables</span>) {
  <span class="keyword">return</span> <span class="string">"("</span> + JSON.stringify({
    <span class="variable-name">proc</span>: <span class="string">"("</span> + fun.toString() + <span class="string">")"</span>,
    <span class="variable-name">data</span>: variables
  }) + <span class="string">")\r\n\r\n\r\n"</span>;
}

<span class="keyword">function</span> <span class="function-name">Application</span>() {
  <span class="keyword">var</span> <span class="variable-name">sys</span> = require(<span class="string">'sys'</span>);
  sys.puts(<span class="string">"Server was started at: "</span> + <span class="builtin">this</span>.date);
};

<span class="keyword">var</span> <span class="variable-name">date</span> = <span class="keyword">new</span> Date();

<span class="keyword">var</span> <span class="variable-name">server</span> = tcp.createServer(<span class="keyword">function</span> (<span class="js2-function-param">socket</span>) {
  socket.addListener(<span class="string">"connect"</span>, <span class="keyword">function</span> (<span class="js2-function-param">conn</span>) {
    socket.send(remoteClosure(Application, {<span class="variable-name">date</span>: date.toString()}));
  });

  socket.addListener(<span class="string">"eof"</span>, <span class="keyword">function</span> () {
    socket.close();
  });
});

server.listen(7000, <span class="string">"localhost"</span>);</pre>
<p>The Application function is the code that will initially be sent to the client, which in this example is rather trivial. The JSON object transferred is built from two fields:</p>
<ul>
<li><i>proc</i> stores the text of the Application function, retrieved using the toString() method of the function object</li>
<li><i>data</i> is any data dynamically computed on the server, in this particular case it is the date the server saved at startup</li>
</ul>
<p>The extra parenthesis are just syntactic sugar for easier evaluation on the client side. This is how the sent JSON actually looks like:</p>
<pre>
({
  <span class="variable-name">"proc"</span>: "(<span class="keyword">function</span> <span class="function-name">ClientApp</span>() {
              <span class="keyword">var</span> <span class="variable-name">sys</span> = require(<span class="string">'sys'</span>);
              sys.puts(<span class="string">"Server started at: "</span> + <span class="builtin">this</span>.date);
            <span class="js2-warning">})</span>",
  <span class="variable-name">"data"</span>: {
    <span class="variable-name">"date"</span>: <span class="string">"Sat Nov 21 2009 19:00:18 GMT+0100 (CET)"</span>
  }
})
</pre>
<p>The client role is very simple - it is supposed to fetch consecutive packets and evaluate the code that is represented by them. When a valid packet arrives, the client parses the received JSON literal. By using eval on the <i>proc</i> field, it gets an identical Application function to the one that was defined in the code of the server, on the client side. It executes the function by using the <i>apply</i> method, making all the usages of <i>this</i> inside the function code refer to what is in the JSON literal under the <i>data</i> key. In this way, the function is executed in a dynamic context specified by the server. Otherwise, it would not be possible to have the entire source code of the application in one source file in normal form. I call it a <i>remote closure</i>, because I look at it as an analogy to the <i>closure</i> concept you may know from programming languages. That&#8217;s how the code for the client looks like:</p>
<pre>
<span class="keyword">var</span> <span class="variable-name">tcp</span> = require(<span class="string">'tcp'</span>);

<span class="keyword">var</span> <span class="variable-name">jsonBuffer</span> = <span class="string">""</span>;
<span class="keyword">var</span> <span class="variable-name">connection</span> = tcp.createConnection(7000, <span class="string">"localhost"</span>);

connection.addListener(<span class="string">"receive"</span>, <span class="keyword">function</span>(<span class="js2-function-param">data</span>) {
  jsonBuffer += data;
  <span class="keyword">if</span>(jsonBuffer.indexOf(<span class="string">"\r\n\r\n\r\n"</span>) &gt; -1) {
    <span class="keyword">var</span> <span class="variable-name">remoteClosure</span> = JSON.parse(jsonBuffer);
    remoteClosure.proc = eval(remoteClosure.proc);
    remoteClosure.proc.apply(remoteClosure.data);
    connection.close();
  }
});</pre>
<p>For the communication to be complete, a way of signalizing the events on the clients virtual machine to the server has to be established. For security reasons, it seems that it is better to use simple data objects in this direction, instead of the code evaluation scheme just presented. Each event sent will also be a JSON <i>packet</i>.</p>
<p>To clarify the code of the next example, a library was built around the concepts discussed so far:</p>
<pre>
<span class="keyword">var</span> <span class="variable-name">tcp</span> = require(<span class="string">'tcp'</span>);

<span class="keyword">function</span> <span class="function-name">packet</span>(<span class="js2-function-param">object</span>) {
  <span class="keyword">return</span> <span class="string">"("</span> + JSON.stringify(object) + <span class="string">")\r\n\r\n\r\n"</span>;
}

<span class="keyword">function</span> <span class="function-name">packetBuffer</span>() {
  <span class="keyword">var</span> <span class="variable-name">buffer</span> = <span class="string">""</span>;

  <span class="keyword">return</span> {
    <span class="function-name">append</span>: <span class="keyword">function</span>(<span class="js2-function-param">data</span>) {
      buffer += data;
    },
    <span class="function-name">packetReady</span>: <span class="keyword">function</span>() {
      <span class="keyword">return</span> buffer.indexOf(<span class="string">"\r\n\r\n\r\n"</span>) &gt; - 1;
    },
    <span class="function-name">fetchPacket</span>: <span class="keyword">function</span> () {
      <span class="keyword">var</span> <span class="variable-name">packetEnd</span> = buffer.indexOf(<span class="string">"\r\n\r\n\r\n"</span>);
      <span class="keyword">var</span> <span class="variable-name">packet</span> = buffer.substring(0, packetEnd);
      buffer = buffer.substring(packetEnd + 1, buffer.length);
      <span class="keyword">return</span> JSON.parse(packet);
    }
  };
}

<span class="keyword">function</span> <span class="function-name">event</span>(<span class="js2-function-param">name</span>, <span class="js2-function-param">data</span>) {
  env.connection.send(
    packet({
      <span class="variable-name">name</span>: name,
      <span class="variable-name">data</span>: data
    }));
}

<span class="keyword">function</span> <span class="function-name">closure</span>(<span class="js2-function-param">fun</span>, <span class="js2-function-param">variables</span>) {
  <span class="keyword">return</span> packet({
    <span class="variable-name">proc</span>: <span class="string">"("</span> + fun.toString() + <span class="string">")"</span>,
    <span class="variable-name">data</span>: variables
  });
}

<span class="keyword">function</span> <span class="function-name">publish</span>(<span class="js2-function-param">application</span>, <span class="js2-function-param">host</span>, <span class="js2-function-param">port</span>) {
  <span class="keyword">var</span> <span class="variable-name">handlers</span> = {};
  <span class="keyword">var</span> <span class="variable-name">buffer</span>   = packetBuffer();

  <span class="keyword">var</span> <span class="variable-name">server</span> = tcp.createServer(<span class="keyword">function</span> (<span class="js2-function-param">socket</span>) {
    socket.addListener(<span class="string">"connect"</span>, <span class="keyword">function</span> (<span class="js2-function-param">conn</span>) {
      socket.send(closure(application, {}));
    });

    socket.addListener(<span class="string">"receive"</span>, <span class="keyword">function</span>(<span class="js2-function-param">data</span>) {
      buffer.append(data);

      <span class="keyword">while</span>(buffer.packetReady()) {
        <span class="keyword">var</span> <span class="variable-name">event</span>   = buffer.fetchPacket();
        <span class="keyword">var</span> <span class="variable-name">handler</span> = handlers[event.name];
        socket.send(handler(event.data));
      }
    });

    socket.addListener(<span class="string">"eof"</span>, socket.close);
  });

  server.listen(port, host);

  <span class="keyword">return</span> {
    <span class="function-name">addListener</span>: <span class="keyword">function</span>(<span class="js2-function-param">eventName</span>, <span class="js2-function-param">listener</span>) {
      handlers[eventName] = listener;
    }
  };
};

<span class="js2-external-variable">exports</span>.packetBuffer = packetBuffer;
<span class="js2-external-variable">exports</span>.packet       = packet;
<span class="js2-external-variable">exports</span>.event        = event;
<span class="js2-external-variable">exports</span>.closure      = closure;
<span class="js2-external-variable">exports</span>.publish      = publish;</pre>
<p>The library introduces two major new elements:</p>
<ul>
<li>an event function to send event objects from the client to the server</li>
<li>a set of event handlers for the application server, each reacting to a particular kind of event</li>
</ul>
<p>To illustrate how the full communication scheme works in practice, a slightly more complex program should be considered: a calculator. It is the simplest possible example of the general two-way communication scheme that is the basis for all <i>OAPP</i> applications:</p>
<pre>
<span class="keyword">var</span> <span class="variable-name">sys</span>  = require(<span class="string">'sys'</span>);
<span class="keyword">var</span> <span class="variable-name">tcp</span>  = require(<span class="string">'tcp'</span>);
<span class="keyword">var</span> <span class="variable-name">oapp</span> = require(<span class="string">'./oapp'</span>);

<span class="keyword">function</span> <span class="function-name">Calculator</span>() {
  <span class="keyword">function</span> <span class="function-name">parse</span>(<span class="js2-function-param">input</span>) {
    <span class="keyword">var</span> <span class="variable-name">position</span> = 0;

    <span class="keyword">function</span> <span class="function-name">peek</span>()    { <span class="keyword">return</span> input[position]; }
    <span class="keyword">function</span> <span class="function-name">consume</span>() { <span class="keyword">return</span> input[(position += 1) - 1];  }

    <span class="keyword">function</span> <span class="function-name">token</span>() {
      <span class="keyword">var</span> <span class="variable-name">token</span> = consume(), <span class="variable-name">c</span>;
      <span class="keyword">if</span>(token &lt; <span class="string">'0'</span> || token &gt; <span class="string">'9'</span>)
        <span class="keyword">return</span> token;

      <span class="keyword">while</span>((c = peek()) &amp;&amp; c &gt;= <span class="string">'0'</span> &amp;&amp; c &lt;= <span class="string">'9'</span>)
        token += consume();
      <span class="keyword">return</span> parseInt(token);
    }

    <span class="keyword">function</span> <span class="function-name">binary</span>(<span class="js2-function-param">left</span>, <span class="js2-function-param">right</span>, <span class="js2-function-param">ops</span>) {
      <span class="keyword">var</span> <span class="variable-name">token</span>, <span class="variable-name">a</span> = left();
      <span class="keyword">if</span>((token = peek()) &amp;&amp; (ops.indexOf(token) == -1))
        <span class="keyword">return</span> a;
      <span class="keyword">var</span> <span class="variable-name">op</span> = consume(), <span class="variable-name">b</span> = right();
      <span class="keyword">return</span> [op, a, b];
    }

    <span class="keyword">function</span> <span class="function-name">term</span>() { <span class="keyword">return</span> binary(token, term, [<span class="string">'*'</span>, <span class="string">'/'</span>]); }
    <span class="keyword">function</span> <span class="function-name">expr</span>() { <span class="keyword">return</span> binary(term, expr, [<span class="string">'+'</span>, <span class="string">'-'</span>]); }

    <span class="keyword">return</span> expr();
  }

  process.stdio.open();
  process.stdio.addListener(<span class="string">"data"</span>, <span class="keyword">function</span>(<span class="js2-function-param">input</span>) {
    oapp.event(<span class="string">"expressionEntered"</span>, { <span class="variable-name">expr</span>: parse(input) });
  });
};

<span class="keyword">var</span> <span class="variable-name">app</span> = oapp.publish(Calculator, <span class="string">"localhost"</span>, 7000);

app.addListener(<span class="string">"expressionEntered"</span>, <span class="keyword">function</span>(<span class="js2-function-param">event</span>) {
  <span class="keyword">function</span> <span class="function-name">compute</span>(<span class="js2-function-param">expr</span>) {
    <span class="keyword">if</span>(!(expr <span class="keyword">instanceof</span> Array))
      <span class="keyword">return</span> expr;

    <span class="keyword">var</span> <span class="variable-name">op</span> = expr[0];
    <span class="keyword">var</span> <span class="variable-name">a</span>  = compute(expr[1]);
    <span class="keyword">var</span> <span class="variable-name">b</span>  = compute(expr[2]);

    <span class="keyword">switch</span>(op) {
      <span class="keyword">case</span> <span class="string">'+'</span>: <span class="keyword">return</span> a + b; <span class="keyword">case</span> <span class="string">'-'</span>: <span class="keyword">return</span> a - b;
      <span class="keyword">case</span> <span class="string">'*'</span>: <span class="keyword">return</span> a * b; <span class="keyword">case</span> <span class="string">'/'</span>: <span class="keyword">return</span> a / b;
      <span class="keyword">default</span>:  <span class="keyword">return</span> <span class="constant">null</span>;
    }
  }

  <span class="keyword">return</span> oapp.closure(<span class="keyword">function</span>() {
    sys.puts(<span class="string">"Result is: "</span> + <span class="builtin">this</span>.result);
  }, { <span class="variable-name">result</span>: compute(event.expr) });
});</pre>
<p>The following scenario is executed when a client connects to the server:</p>
<ul>
<li>The Calculator <i>application</i> is sent to the client and <i>installed</i>. In JavaScript terms the <i>application</i> is a function, and <i>installation</i> is just function evaluation.</li>
<li>The client application waits for a line of input from the user</li>
<li>The input is parsed, forming a tree from the infix expression the user entered, for example parsing 9*8+2*3 returns   ['+', ['*', 9, 8], ['*', 2, 3]]</li>
<li>The resulting expression tree is sent to the server with the <i>expressionEntered</i> event</li>
<li>The server computes the answer and sends back a closure displaying the result to the client</li>
</ul>
<p>As one can see, the abstractions introduced make the application code look almost indistinguishable from an event-driven client side program, for example one built with a toolkit like Swing. For a library that is not even 2 kilobytes large, this is not a bad result and a big compliment for the techniques and technologies used.</p>
<p>The slightly extended client code looks like this:</p>
<pre>
<span class="keyword">var</span> <span class="variable-name">sys</span>  = require(<span class="string">'sys'</span>);
<span class="keyword">var</span> <span class="variable-name">tcp</span>  = require(<span class="string">'tcp'</span>);
<span class="keyword">var</span> <span class="variable-name">oapp</span> = require(<span class="string">'./oapp'</span>);

<span class="keyword">var</span> <span class="variable-name">buffer</span> = oapp.packetBuffer();
<span class="keyword">var</span> <span class="variable-name">global</span> = <span class="builtin">this</span>;

<span class="js2-external-variable">env</span> = {};
<span class="js2-external-variable">env</span>.connection = tcp.createConnection(7000, <span class="string">"localhost"</span>);

env.connection.addListener(<span class="string">"receive"</span>, <span class="keyword">function</span>(<span class="js2-function-param">data</span>) {
  buffer.append(data);

  <span class="keyword">while</span>(buffer.packetReady()) {
    <span class="keyword">var</span> <span class="variable-name">remoteClosure</span> = buffer.fetchPacket();
    remoteClosure.proc = eval(remoteClosure.proc);
    remoteClosure.proc.apply(remoteClosure.data);
  }
});</pre>
<p>The two examples considered were of course trivial, meant to illustrate the techniques used for developing <i>OAPP</i> programs. To check if the idea for the platform is at all bearable and sensible, one should consider how more complex kinds of applications would look and work like, especially if the virtual machine would be extended with additional capabilities, for example with a graphics library. This will perhaps be a topic of another article in the future.</p>
<p>I think that the set of ideas presented, if complemented with a much more mature implementation, would offer an interesting alternative to the way we develop web applications today. A real-life project based on this would of course have to deal with the topics of latencies, security or ease of debugging and be tested much more extensively. I leave the evaluation of the usefulness of such a project to the reader, at the very least I hope you have just seen an interesting usage of the JavaScript programming language.</p>
<p>Code of the first example (server start-up time):</p>
<p><a href="/oapp/one/server.js">server.js</a><br />
<a href="/oapp/one/client.js">client.js</a></p>
<p>Code of the second example (calculator):</p>
<p><a href="/oapp/two/oapp.js">oapp.js</a><br />
<a href="/oapp/two/server.js">server.js</a><br />
<a href="/oapp/two/client.js">client.js</a></p>
<p><a href="http://github.com/sztywny/oapp/">Github repository</a></p>
<hr />
<strong class="signature"><br />
<a href="mailto:sztywny@gmail.com">Jarosław Rzeszótko</a>, student of Polish-Japanese Institute of Technology<br />
Idea sparked by conversations with <a href="http://claygirl.jogger.pl">Magdalena Wójcik</a> and Karol Kozub<br />
</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://www.stifflog.com/2009/11/24/an-open-platform-for-publishing-applications/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Proel - Project support for Emacs</title>
		<link>http://www.stifflog.com/2008/12/14/proel-project-support-for-emacs/</link>
		<comments>http://www.stifflog.com/2008/12/14/proel-project-support-for-emacs/#comments</comments>
		<pubDate>Sun, 14 Dec 2008 14:17:34 +0000</pubDate>
		<dc:creator>stiff</dc:creator>
		
		<category><![CDATA[Emacs]]></category>

		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.stifflog.com/2008/12/14/proel-project-support-for-emacs/</guid>
		<description><![CDATA[One of the most fundamental features that Emacs is missing among all the goodness available for programmers is the support for handling software projects ie. the way TextMate or IDEs does this. Not having a quick way to navigate between files, classes, methods and other symbols starts to significantly suck if you&#8217;re working with bigger [...]]]></description>
			<content:encoded><![CDATA[<p>One of the most fundamental features that Emacs is missing among all the goodness available for programmers is the support for handling software projects ie. the way TextMate or IDEs does this. Not having a quick way to navigate between files, classes, methods and other symbols starts to significantly suck if you&#8217;re working with bigger bases of source code. Because of this, a year or two ago I rolled two screen pages of Elisp or so, to make the basic operations I want to have available project-wide available. It served me very well ever since than, but it was a dirty hack and I really didn&#8217;t knew much Lisp at that time. Recently, seeing some other attempts at solving this problem, I decided to cleanup and extend my solution a little bit and make it available for the general public. So the <a href="http://www.stifflog.com/proel.el"><strong>proel</strong></a> package was born.<span id="more-25"></span></p>
<p>Proel makes one fundamental assumption - you have a set of dedicated directories for your software projects (ie. ~/code/work or ~/code/own), and each project has a single root directory in one of the projects directory, which name is also the name of the project (ie. ~/code/work/boring-app or ~/code/own/fun-app).</p>
<p>If you&#8217;re configuration is meeting this assumption, proel enables you to effectively open one of the projects and than to find files in the project using fuzzy matching (like in TextMate) ie. you can type SemaAn.g to open SemanticAnalysis.g. You have to have the wonderful <a href="http://www.emacswiki.org/emacs/anything.el">&#8220;anything&#8221;</a> package for that (see also <a  href="http://www.emacswiki.org/emacs/Anything">here</a>), and <a href="http://www.emacswiki.org/emacs/fuzzy-match.el">&#8220;fuzzy-match&#8221;</a>, the library doing the string matching.</p>
<p>Proel also arguments the find-file function, so whenever you open a file &#8220;manually&#8221;, the project gets recognized. If the project directory contains the &#8220;TAGS&#8221; or &#8220;cscope.out&#8221; files, proel will also automatically visit the tags table or load the cscope database. You can also use the &#8216;proel-vc-in-project&#8217; command to open up the Emacs version control status interface in projects directory (SVN and git are currently supported, but you can easily add your preffered VC) or &#8216;proel-grep-in-project&#8217; to do a recursive grep somewhere in the project directory.</p>
<p>This is now one of the most producitivity-enhancing packages I have installed (together with anything, psvn, git.el, ediff and some other stuff I rolled on my own I will relase one day hopefully). The only thing I miss is being able to locate symbols/definitions using<br />
anything and fuzzy matching the way locating files work, but I hope I will be able to work out that one too. Also, for other people, another way of recognizing projects could be desirable (ie. by detecting the topmost parent directory of the current file has a &#8220;Makefile&#8221; or &#8220;build.xml&#8221; like <a href="http://blog.jrock.us/articles/eproject.pod">eproject</a>).</p>
<p>A picture is worth a thousand words, so here you can see how it works in practice:</p>
<p><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/15DUGERq9oY&#038;hl=en&#038;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/15DUGERq9oY&#038;hl=en&#038;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></p>
<p><strong>(Download the original, sharp video in Theora <a href="http://www.stifflog.com/proel.ogv">here</a>)</strong></p>
<p>And here&#8217;s a sample .emacs I use in the screencast:</p>
<pre>
(add-to-list 'load-path "/home/sztywny/.elisp")
(add-to-list 'load-path "/home/sztywny/.elisp/git")

(require 'anything)
(require 'git)
(require 'proel)
(require 'xcscope)

(tool-bar-mode nil)
(scroll-bar-mode nil)

(setq cscope-do-not-update-database t
      grep-find-template "find . <X> -type f <F> -print0 | xargs -0 -e grep <C> -nH -e <R>"
      anything-sources
        '(proel-anything-projects
          proel-anything-current-project-files))
</pre>
<p>You will probably want to customize other things too, just look through the source code to get an idea what variable controls what<br />
aspect of proels behaviour. I hope you will like it :)</p>
<p><a href="http://www.stifflog.com/proel.el"><strong>proel.el</strong></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.stifflog.com/2008/12/14/proel-project-support-for-emacs/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Metaprogramming Ruby</title>
		<link>http://www.stifflog.com/2008/04/19/metaprogramming-ruby/</link>
		<comments>http://www.stifflog.com/2008/04/19/metaprogramming-ruby/#comments</comments>
		<pubDate>Sat, 19 Apr 2008 16:15:24 +0000</pubDate>
		<dc:creator>stiff</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.stifflog.com/2008/04/19/metaprogramming-ruby/</guid>
		<description><![CDATA[On this year&#8217;s RuPy I gave a talk about Metaprogramming Ruby. Unfortunately I didn&#8217;t have the time to prepare the presentation exactly the way I wanted, nor did the organisators gave me enough time to present what I wanted to present. Anyway, I made some changes to the slides, which are now of some value [...]]]></description>
			<content:encoded><![CDATA[<p>On this year&#8217;s <a href="http://www.rupy.eu/">RuPy</a> I gave a talk about Metaprogramming Ruby. Unfortunately I didn&#8217;t have the time to prepare the presentation exactly the way I wanted, nor did the organisators gave me enough time to present what I wanted to present. Anyway, I made some changes to the slides, which are now of some value on they own I believe, so I put them <a href="http://www.stifflog.com/presentation.pdf"><strong>here</strong></a> for everybody to enjoy. Things covered include: Ruby&#8217;s object model, differencies between instance_eval/class_eval, hooks, reflection, wrapping methods, DSLs, Higher-Order Messanging, getting the parse tree from Ruby code and vice versa, and so on. There is also a nice resources section, where you will find the gems I found across all the available material about the topics covered, and from which I&#8217;ve picked up a lot of really interesting meta-ideas. If you find any errors, please let me know, this stuff is really fuzzy, and I really want to have it covered in a clear and precise way.</p>
<p><i>Despite the quirk with my own presentation, I really enjoyed RuPy as a participiant and I think it&#8217;s a great event. Zed Shaw had a really nice presentation, with some funny bits, but also with many things you can pick up and use weeks after the conference ended. I also liked the talk about PyPy by Carl Friedrich Bolz, even through I&#8217;m a Ruby guy - they really have some interesting ideas about compiling/interpreting dynamic languages and they made a hell of the effort to push it forward. I hope I will be able to visit Poznań again the next year and I encourage you to do the same too.</i></p>
]]></content:encoded>
			<wfw:commentRss>http://www.stifflog.com/2008/04/19/metaprogramming-ruby/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Erlang, the functional Smalltalk?</title>
		<link>http://www.stifflog.com/2007/12/01/erlang-the-functional-smalltalk/</link>
		<comments>http://www.stifflog.com/2007/12/01/erlang-the-functional-smalltalk/#comments</comments>
		<pubDate>Sat, 01 Dec 2007 08:21:32 +0000</pubDate>
		<dc:creator>stiff</dc:creator>
		
		<category><![CDATA[Erlang]]></category>

		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.stifflog.com/2007/12/01/erlang-the-functional-smalltalk/</guid>
		<description><![CDATA[Let&#8217;s start with a confession. I&#8217;m not a Erlang weenie, I&#8217;m not even a decent part-time Erlang hacker. But for some reason, I keep coming back to it, even through I don&#8217;t normally work in the problem domain I think Erlang is best suited for, like servers of various kinds (from MMORPG games to Jabber), [...]]]></description>
			<content:encoded><![CDATA[<p>Let&#8217;s start with a confession. I&#8217;m not a Erlang weenie, I&#8217;m not even a decent part-time Erlang hacker. But for some reason, I keep coming back to it, even through I don&#8217;t normally work in the problem domain I think Erlang is best suited for, like servers of various kinds (from <a href="http://www.vendetta-online.com/">MMORPG games</a> to <a href="http://www.ejabberd.im/">Jabber</a>), or large scale, distributed applications. But in this case, it works differently - I keep coming up with problems that could be nicely solved in Erlang, instead of matching the language to the problem.</p>
<p>I wrote about the great fun factor of programming in Erlang before, but I didn&#8217;t quite get the reason this is the case. Now, after thinking about for a while, I think I know what Erlang does so well, that it makes programming a joy.<span id="more-20"></span></p>
<p>You see, Erlang creators criticize OOP eagerly, distancing from it as much as possible, which is a bit misleading. I believe Erlang is the quintessentional cross between object orientation and functional programming. Even through Erlang doesn&#8217;t have implict support for &#8220;objects&#8221; of any kind, it does have processes. Contrary to what the Erlang crowd says, they seem to share all the common properties of object/classes in traditional object oriented languages - they capture state, express behaviour and you can even (sort of) inherit a process from another process or compose them, if you think this is necessary to call something object-oriented, and/or if you think this has use in Erlang. You can also build reusable components with them, as you can see for example in the OTP behaviours.</p>
<p>This is a simple observation, but it has some strong consequences - this programming model seems to has some unique advantages. I observed that while using traditional OOP, I tend to think much more about classes, one piece at a time, thinking in terms of fields/methods. Erlang shifts the focus from classes/methods/state towards interactions, or messages crossing, between objects/processes in time. Also, you think about the whole thing at once, about all the components involved and cooperating in solving a subproblem/problem of your program. To put it in another way, you don&#8217;t think only about the internal construction of the entities involved, but you also think about how they&#8217;re playing together to solve the problem. It feels like the concurrent language was promoting more &#8220;concurrent&#8221;, cooperative, big-picture thinking. Than, when you get the picture, you can compose the the bigger things (processes) from little, stateless functions doing the things you want.</p>
<p>As a result of this paradigm change, it seems that it&#8217;s easier to write more modular and coherent applications. It doesn&#8217;t even have anything to do with so-called &#8220;concurrent&#8221; programs, think of it for a while. Aren&#8217;t objects in your traditional language exchanging messages all the time? Aren&#8217;t they independent &#8220;beings&#8221; exisiting concurrently in some &#8220;space&#8221;? That&#8217;s where the title reference to Smalltalk came from. Erlang only removes the limitation that only two object can talk to each other at a time (when your traditional program isn&#8217;t threaded, and I&#8217;m talking concept-wise, not implementation-wise). At the same time, the functional nature forces you to use as small amounts of state as possible, which in consequence rewards writting very small modules.</p>
<p>Obviously, they are also strong differencies ie. you have many things in Erlang that aren&#8217;t at all realized using processes, whereas in &#8220;true&#8221; OO languages everything is an object. Processes aren&#8217;t also used as a data type, as you have records and tuples for this. Still, through, the essential modelling is done using processes. I believe that what Erlang does with them is the best way you currently can cross a variant of object orientation with functional programming, even if concurrency isn&#8217;t a priority. It certainly seems much more reasonable than trying to fit the traditional model with classes to the functional world.</p>
<p>Joe Armstrong certainly knows all this, and talks about it between the lines sometimes, but I didn&#8217;t seen it discussed in depth anywhere. For some more insight into the language, you may want to see this great talk with Joe: <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=351659">part1</a>, <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=352136">part2</a>, and also <a href="http://www.sics.se/~joe/bluetail/vol1/v1_oo.html">this article</a> on oop.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stifflog.com/2007/12/01/erlang-the-functional-smalltalk/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Html generation in JavaScript</title>
		<link>http://www.stifflog.com/2007/06/10/html-generation-in-javascript/</link>
		<comments>http://www.stifflog.com/2007/06/10/html-generation-in-javascript/#comments</comments>
		<pubDate>Sun, 10 Jun 2007 18:49:26 +0000</pubDate>
		<dc:creator>stiff</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.stifflog.com/2007/06/10/html-generation-in-javascript/</guid>
		<description><![CDATA[I started playing a little bit more with JavaScript recently, and one thing that bothered me was generating HTML. For example, if you have a AJAX application of any reasonable size, it probably has to change a lot of stuff inside of the various divs  or other elements as it runs. For that, you [...]]]></description>
			<content:encoded><![CDATA[<p>I started playing a little bit more with JavaScript recently, and one thing that bothered me was generating HTML. For example, if you have a AJAX application of any reasonable size, it probably has to change a lot of stuff inside of the various divs  or other elements as it runs. For that, you need to write a lot of ugly-looking, long-running string concatenations. So, I took an idea used by the Lisp folks or in the Ruby <a href="http://redhanded.hobix.com/inspect/markabyForRails.html">Markaby</a> library and I created a library to write HTML in JavaScript. I&#8217;m not sure if I&#8217;m the first one to come up with this, but my Google-fu failed in this case, so maybe&#8230; Anyway, with my JsTemple you write something like this:</p>
<pre>
$table({cellpadding: 10},
  $tr(
    $td(
      $div({klass: <span class="string">'container'</span>, id: <span class="string">'main'</span>},
        $h1(<span class="string">'Foobar'</span>),
        $h2(<span class="string">'Foobar2'</span>),
        $h3(<span class="string">'Foobar3'</span>),
        $h4(<span class="string">'Foobar4'</span>),
        $h5(<span class="string">'Foobar5'</span>),
        $div({id: <span class="string">'layer'</span>, style: <span class="string">'border: solid 3px #f00; padding: 10px;'</span>},
          $p({klass: <span class="string">'foo'</span>},
            <span class="string">'foo'</span>, $strong(<span class="string">'bar'</span>)),
          $p({klass: <span class="string">'shmoo'</span>},
            <span class="string">'shmoo'</span>))))));</pre>
<p>And you get this:</p>
<pre>
&lt;<span class="function-name">table</span> <span class="variable-name">cellpadding</span>=<span class="string">"30"</span>&gt;
  &lt;<span class="function-name">tr</span>&gt;
    &lt;<span class="function-name">td</span>&gt;
      &lt;<span class="function-name">div</span> <span class="variable-name">class</span>=<span class="string">"container"</span> <span class="variable-name">id</span>=<span class="string">"main"</span>&gt;
        &lt;<span class="function-name">h1</span>&gt;Foobar&lt;/<span class="function-name">h1</span>&gt;
        &lt;<span class="function-name">h2</span>&gt;Foobar2&lt;/<span class="function-name">h2</span>&gt;
        &lt;<span class="function-name">h3</span>&gt;Foobar3&lt;/<span class="function-name">h3</span>&gt;
        &lt;<span class="function-name">h4</span>&gt;Foobar4&lt;/<span class="function-name">h4</span>&gt;
        &lt;<span class="function-name">h5</span>&gt;Foobar5&lt;/<span class="function-name">h5</span>&gt;
        &lt;<span class="function-name">div</span> <span class="variable-name">id</span>=<span class="string">"layer"</span> <span class="variable-name">style</span>=<span class="string">"border: 3px solid #f00; padding: 10px;"</span>&gt;
          &lt;<span class="function-name">p</span> <span class="variable-name">class</span>=<span class="string">"foo"</span>&gt;foo&lt;<span class="function-name">strong</span>&gt;bar&lt;/<span class="function-name">strong</span>&gt;&lt;/<span class="function-name">p</span>&gt;
          &lt;<span class="function-name">p</span> <span class="variable-name">class</span>=<span class="string">"shmoo"</span>&gt;shmoo&lt;/<span class="function-name">p</span>&gt;
        &lt;/<span class="function-name">div</span>&gt;
      &lt;/<span class="function-name">div</span>&gt;
    &lt;/<span class="function-name">td</span>&gt;
  &lt;/<span class="function-name">tr</span>&gt;
&lt;/<span class="function-name">table</span>&gt;
</pre>
<p>I generated the necessary data about tags / possible properties from HTML 4.01 W3C specification, so all the tags should work and invalid properties should be ignored. &#8220;Should&#8221;, because the generating was a little bit tricky and I&#8217;m not 100% sure if everything is the way it should be. The dollar sign is a bit annoying, too, but my goal was to avoid cluttering of the global namespace, especially a variable name like &#8220;i&#8221; may be quite popular&#8230; I don&#8217;t know how it works performance-wise or memory-wise either (certainly some optimizations are possible), but it seems to work under Firefox, Opera, Konqueror (Safari?) and MSIE 6/7 and it even doesn&#8217;t crash any of them in a short time, what I consider a big success. I don&#8217;t really know if this is useful at all (most people don&#8217;t seem to like balancing parenthesis or don&#8217;t know a decent editor which highlight pairs of matching parenthesis, judging by Lisp popularity), but you can grab it <a href="http://www.stifflog.com/jsTemple.js"><strong>here</strong></a>. To start using it simply include the js file using &lt;script&gt;, nothing more. If you somehow find it fun, just leave a comment. Afterwards, feel free to do whatever you want with the code.</p>
<p>One more tip: keep in mind that jsTemple just returns a string, so you can for example use it with Prototype&#8217;s <a href="http://www.prototypejs.org/api/template">Template class</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stifflog.com/2007/06/10/html-generation-in-javascript/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Guerilla Computing</title>
		<link>http://www.stifflog.com/2007/06/02/guerilla-computing/</link>
		<comments>http://www.stifflog.com/2007/06/02/guerilla-computing/#comments</comments>
		<pubDate>Sat, 02 Jun 2007 11:18:36 +0000</pubDate>
		<dc:creator>stiff</dc:creator>
		
		<category><![CDATA[Emacs]]></category>

		<category><![CDATA[Getting Things Done]]></category>

		<category><![CDATA[Lifehacks]]></category>

		<category><![CDATA[Linux]]></category>

		<guid isPermaLink="false">http://www.stifflog.com/2007/06/02/guerilla-computing/</guid>
		<description><![CDATA[The title mem spawned in my mind as a result of two things. First, I finally tried a tiling window manager, after many people recommending it to me throughout the last year or two (most recently in the comments to &#8220;My Linux Stack&#8221;, thanks Torben!). Secondly, I didn&#8217;t have too much time recently to play [...]]]></description>
			<content:encoded><![CDATA[<p>The title mem spawned in my mind as a result of two things. First, I finally tried a tiling window manager, after many people recommending it to me throughout the last year or two (most recently in the comments to &#8220;My Linux Stack&#8221;, thanks Torben!). Secondly, I didn&#8217;t have too much time recently to play with my setup, having high school final exams and getting back to work, so I found 900mb of updates waiting for me in portage.</p>
<p>Now, 900mb is a lot. A few years ago I had a pretty complete and useful Slackware setup on my old computer weighing 900mb. I choosed packages by hand, I used some advice from the <a href="http://tldp.org/HOWTO/Saving-Space.html">Saving Space HOWTO</a>, made ruthless decisions about what software I need and what not. Now, I have 12gb filled up on the partition with Gentoo. I wonder how much of it is garbage. I decided I don&#8217;t want it this way anymore and I don&#8217;t want to spend that much time on keeping up to date with the software, upgrading packages, fiddling with this stuff etc. <span id="more-18"></span></p>
<p>Anyway, the idea is to keep the set of the software you use as minimal and as portable as it gets - in guerilla you never know where you will wake up the next day if you wake up at all, and software certainly is one hell of a battlefield those days. The first step for me was kicking out XFCE and installing dwm, the tiling window manager I told you about in the beginning. Actually I installed a lot of tiling window managers, but this is the one I sticked with for now, as it&#8217;s so small it&#8217;s easy to learn and start using.</p>
<p><a href="http://www.suckless.org/wiki/dwm">Dwm</a> &#038; <a href="http://www.suckless.org/wiki/tools/xlib">dmenu</a> are plain cool. Their compressed sources take up 27,121 <strong>bytes</strong>, yet they manage to make a better job managing windows and streamlining work than anything else I used. What makes dwm cool? Short version: tags and tiling. Basically, you define a set of tags for the things you&#8217;re doing with you computer, or for the programs you use, or whatever you will come up with. I currently have 8 major tags: &#8220;firefox&#8221;, &#8220;emacs&#8221;, &#8220;terminal&#8221;, &#8220;docs&#8221;, &#8220;chat&#8221;, &#8220;music&#8221;, &#8220;p2p&#8221; and &#8220;graphics&#8221;. Dwm lets you define which window should be tagged which tag. Now when you start it, you have a list of tags in the top bar and you can switch to a particular tag by pressing the shortcut of choice, Alt-1, Alt-2 etc. by default. You can also toggle a tag, for example to display both all the windows tagged &#8220;docs&#8221; and all the windows tagged &#8220;music&#8221;. When you have more than one window with the same tag, the display gets split, so the windows never overlap. One of the advantages of dwm is that it doesn&#8217;t have problems with floating windows - you can toggle a window between being tiled and floating, use whole workspaces containing only floating windows and finally you can resize/move windows, which isn&#8217;t always the case in titling WMs. The reason I finally took tiling window managers for a spin is that I recently found myself using a workspace consiting of fullscreen emacs on first desktop, fullscreen firefox on second desktop, maybe a maximized terminal running screen on the thrid one and everything else (being pretty much unimportant) floating around all the other workspaces. Using dwm was like capturing the pattern of usage into software and making it automatical.</p>
<p>A tiling window manager is like the ultimate answer to &#8220;distraction free&#8221; computing. If you look at the buzz from the MacOsX crowd about apps like WriteRoom, Backdrop, SpiritedAway etc. you can understand how a tiling wm can make sense. It just doesn&#8217;t have a cool logo and a good marketing campaign, but it realizes the same goal quite nicely.</p>
<p>Dmenu is 7,912 bytes and is a hell of a good application. The idea is dead simple, you give a list of options to the standard input, dmenu shows a bar on the top of the screen letting you choose an option using tab completion and substring matching and return the choosed option to the standard output. When someone says it&#8217;s like Quicksilver, you may think he&#8217;s nuts, as I first did. But hell, yes, it&#8217;s like Quicksilver made the unix way. It&#8217;s a simple tool, which power lies in the combination with other tools. The first thing I did with it and already used a hundred of times or so is selecting music to play. I bound Mod+Shift+m to the following command:</p>
<pre>
cd ~ &#038;&#038; exec audacious "$((find downloads/ -name '*.mp3' &#038;&#038; find music/) | dmenu)"
</pre>
<p>What id does is that it feeds dmenu with a list of loose mp3 in ~/downloads and all the music files and directories in ~/music. I can press the shortcut, type in the first few letters of the band / album / song I wanna play, press enter and audacious is going to play it. With a bit of fantasy you can do literally thousands of things this way. By using tools like xclip, which let you access the kill buffer from command line and a good scripting language or shell you can do thousands of _wicked cool_ things this way. When I realized this, the Quicksilver comparison didn&#8217;t seem that funny anymore.</p>
<p>Let&#8217;s see how we can achieve something more sophisticated using dmenu (or a simillar tool, the idea is important here, you can roll your own one without too much struggle). Let&#8217;s say we have an address book kept as a text file:</p>
<pre>
John Kowalsky &lt;john@kowalsky.com&gt;
Chuck Norris &lt;chuck@karate.com&gt;
Elvis Presley &lt;the@king.com&gt;</pre>
<p>We would like to press a shortcut, select a person using dmenu and had a gmail &#8220;new message&#8221; page opened in firefox with the right data filled in. I never really used Quicksilver, but guessing from screencasts/articles, this is one of the common ways people use it. It&#8217;s not a big deal to implement this:</p>
<pre>
URL=$(echo -n "http://mail.google.com/mail/?view=cm&#038;fs=1&#038;to=" &#038;&#038; \
  (cat < addresses | dmenu))
firefox -remote "openUrl($URL)"
</pre>
<p>You make a shell script from this, bind it to a key and you have one more thing automatized. Using tools that let you access the X11 kill you could also implement easy adding of addresses to the text-file address book etc. Your imagination is the main limit here, the other being your knowledge of the shell, your scripting language of choice etc. Also remember you can nest dmenus to create something actually more reassembling a menu, without binding every single command to a keyboard shortcut.</p>
<p>What I want to achieve with my setup now is as much portability as you can get - I need an environment I can set up as quickly as possible on any modern computer no matter what. If my current box explodes, I want to be able to recreate the very same configuration in one day, nothing more. Currently, recreating my Gentoo setup would take a few weeks.</p>
<p>The next step I took after removing the bloated desktop environment is moving some of the activites to the web. I uninstalled Sage, putting my RSS feeds into Google Reader, and removed Sylpheed in favour of GMail and setting up forwarding from my second mail account. I always was and I still am a bit sceptical about web applications, but those two things I should have moved to the web long time ago. I&#8217;m only not sure about the Google, Che Guevara certainly wouldn&#8217;t like the idea of someone reading his e-mails. From the other side, they simply have the best products right now.</p>
<p>Now the basic stuff I spend most of my time in everyday looks like this:</p>
<p>Dwm, Emacs, Urxvt+Screen+Zsh, Firefox, Gmail, Greader, Ruby/Rails, Pidgin, Audacious</p>
<p>You may wonder about using pidgin or audacious in a tiling window manager, but in fact it works good enough. There is also obviously a whole lot of other apps I use and still need to pick down a bit, but the main set is compact enough. Now I&#8217;m trying to find a distribution that will make setting all this up as fast as possible&#8230; The first thing I come up is a Debian meta-package with all the software I need to get things done. After creating it, I would just install debian from a minimal installation CD, set up the internet connection, and install the metapackage. I have a separate partition for /home (one of the best Linux tips is to have one), so on my main box I wouldn&#8217;t even have to copy the configuration files. I was also thinking about checking out Arch Linux and OpenSuse, two distros I haven&#8217;t seen for a long time, but rising hope to not suck.</p>
<p>The nice thing is that all my major applications can tightly cooperate. Dwm takes the status bar content from Zsh, which for example checks Pidgin for new recieved messages, Dmenu can drive firefox using its remote interface, Emacs can send JavaScript to Firefox using MozRepl (thanks to Phil for this one!), Zsh can send a file to emacs using emacsclient etc. They are also extensible, what makes them the great apps they are. I could get even more from this setup, if I knew more JavaScript, shell magic, regular expressions, Lisp etc. It&#8217;s a nice motivation to expand your knowledge.</p>
<p>As always, here go the mandatory screenshots:</p>
<p><a href="http://img102.imageshack.us/my.php?image=dwm1jj8.jpg" target="_blank"><img src="http://img102.imageshack.us/img102/8537/dwm1jj8.th.jpg" border="0" alt="Free Image Hosting at www.ImageShack.us" /></a></p>
<p><a href="http://img131.imageshack.us/my.php?image=dwm2hq3.jpg" target="_blank"><img src="http://img131.imageshack.us/img131/3383/dwm2hq3.th.jpg" border="0" alt="Free Image Hosting at www.ImageShack.us" /></a></p>
<p><a href="http://img460.imageshack.us/my.php?image=dwm3qt7.jpg" target="_blank"><img src="http://img460.imageshack.us/img460/1725/dwm3qt7.th.jpg" border="0" alt="Free Image Hosting at www.ImageShack.us" /></a></p>
<p><a href="http://img159.imageshack.us/my.php?image=dwm4zf7.jpg" target="_blank"><img src="http://img159.imageshack.us/img159/3951/dwm4zf7.th.jpg" border="0" alt="Free Image Hosting at www.ImageShack.us" /></a></p>
<p>The whole setup is heavily influenced by various writing by various authors, make sure to checkout following articles/webpages if you&#8217;re curious: </p>
<p>- <a href="http://suckless.org/">Suckless</a>, the home of dwm, dmenu,   wmii. You may also want to check out the mailing list and the irc   channel (I got some very helpful advice there)</p>
<p>- <a href="http://www.winterspeak.com/columns/goodeasy.txt">The original &#8220;Good Easy&#8221;</a></p>
<p>- <a href="http://diveintomark.org/archives/2007/03/15/good-easy-2007">Mark Pilgrim&#8217;s &#8220;Good Easy&#8221;</a></p>
<p>- <a href="http://handhelds.freshmeat.net/articles/view/581/">&#8220;The Antidesktop&#8221; from freshmeat.net</a></p>
<p>- Various articles from Fravia <a   href="searchlores.org">searchlores.org</a> (actually not those Linux   related, this one is more about the spirit than about the technical   details)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stifflog.com/2007/06/02/guerilla-computing/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Erlang For The Practical Man</title>
		<link>http://www.stifflog.com/2007/05/09/erlang-for-the-practical-man/</link>
		<comments>http://www.stifflog.com/2007/05/09/erlang-for-the-practical-man/#comments</comments>
		<pubDate>Wed, 09 May 2007 09:42:32 +0000</pubDate>
		<dc:creator>stiff</dc:creator>
		
		<category><![CDATA[Erlang]]></category>

		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.stifflog.com/2007/05/09/erlang-for-the-practical-man/</guid>
		<description><![CDATA[Table of contents: 
1: General overview
2: Making an RSS
3: Fighting with POP3 / SSL
4: Serving the thing through HTTP
5: Putting the pieces together
6: Conlusions
This article is my submission for the Erlang blogging contest. You can also grab it as a PDF file - in a4 format or in letter format.
1: General overview
Functional programming languages are [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Table of contents: </strong></p>
<p><a href="http://www.stifflog.com/2007/05/09/erlang-for-the-practical-man/#overview">1: General overview</a><br />
<a href="http://www.stifflog.com/2007/05/09/erlang-for-the-practical-man/#rss">2: Making an RSS</a><br />
<a href="http://www.stifflog.com/2007/05/09/erlang-for-the-practical-man/#pop3">3: Fighting with POP3 / SSL</a><br />
<a href="http://www.stifflog.com/2007/05/09/erlang-for-the-practical-man/#http">4: Serving the thing through HTTP</a><br />
<a href="http://www.stifflog.com/2007/05/09/erlang-for-the-practical-man/#pieces">5: Putting the pieces together</a><br />
<a href="http://www.stifflog.com/2007/05/09/erlang-for-the-practical-man/#conclusions">6: Conlusions</a></p>
<p>This article is my submission for the <a href="http://on-erlang.blogspot.com/2007/05/may-blogging-contest.html">Erlang blogging contest</a>. You can also grab it as a PDF file - <a href="http://www.stifflog.com/erlang-a4.pdf">in a4 format</a> or <a href="http://www.stifflog.com/erlang-letter.pdf">in letter format</a>.</p>
<p><a name="overview"></a><strong>1: General overview</strong></p>
<p>Functional programming languages are often underestimated, as they seem to be not suited for the &#8220;real world&#8221;, being thought of as designed by scientists who spend their time mainly developing theories, not practical software. What makes Erlang stand out from the crowd is the fact it was designed by the industry and for the industry. Ericsson, where the language originated, has a telecom switch with more than 2 million lines of Erlang code running it that has a downtime of a few minutes per year - now this is reliability!</p>
<p>Telecom switches don&#8217;t make programmers too excited those days through, so we will try to do something more related to your everyday hacking. In this tutorial I will show you how to write a standalone daemon, that checks your email every x minutes, and makes the results available as an RSS feed. If you want to centralize all your notifications around RSS this may even be useful a bit and even if not, at least it makes a good example of some of Erlang strengths. I try to explain everything in as much detail as possible, but be warned - we won&#8217;t be writing any &#8220;hello worlds&#8221; here, we will just rapidly introduce a lot of awkward stuff as it becomes necessary, so if you don&#8217;t have a solid programming background you may have serious trouble. Either way, you will probably want to consult <a href="http://www.pragmaticprogrammer.com/titles/jaerlang/">Programming Erlang</a> and the <a href="http://www.erlang.org/doc.html">free, official Erlang docs</a> if you want to do anything serious in Erlang. Also see <a href="http://www.stifflog.com/2007/03/12/having-fun-with-erlang/">my previous post</a> for an overview of general high level Erlang concepts.<span id="more-17"></span></p>
<p>Let&#8217;s start with an overview of the parts that we will need. One component will have to connect to a POP3 server once in a while, grab the list of messages (or message titles) and make a nice list out of it. We don&#8217;t want it to interfere in any way with accessing the feed, so it will be a separate process. We&#8217;ll also need a function that given a simple list of messages, returns a well formed RSS feed created from it. When we have the feed, we want to have a simple HTTP server running that will simply send the feed to anyone who will make a GET. Of course there should be a possibility to update the feed the server is sending, when new mail arrives or simply when we check it the next time. As we said before, serving the feed should be independent from checking email, so it will be another process - and as we allow multiple connections to the server at the same time (maybe you will want to show you email to the world one day, who knows?), it will spawn a new request handling process for each accepted TCP connection, so multiple requests will be handled concurrently. Thinking in terms of processes and concurrent activities in the system is the core of Erlang programming paradigm and is the essence of learning the language. The cool part is that in Erlang modeling software as multiple processes cooperating finally becomes a natural, seamless abstraction and you don&#8217;t have to worry all the time about low-level stuff like deadlocks.</p>
<p><a name="rss"></a><strong>2 : Making an RSS</strong></p>
<p>The data structures we will use are rather basic - we represent messages as tuples and store them in a list. A tuple simply groups a bunch of variables into a single entity. Our program will use tuples to represent messages - the first field will be the &#8220;message&#8221; symbol used to emphasize the meaning of the gathered data, then goes the date of arrival, sender, subject and body. Here are examples of our messages using Erlang syntax:</p>
<pre>
{message, <span class="string">"12:00 01-10-1987"</span>, <span class="string">"Foo Bar"</span>, <span class="string">"Hello Bar!"</span>, <span class="string">"Nice to meet you"</span>}

{message, <span class="string">"16:32 05-05-2006"</span>, <span class="string">"Whoever"</span>, <span class="string">"Some subject"</span>, <span class="string">"Whatever"</span>}</pre>
<p>You can get to individual tuple fields using the element function:</p>
<pre>
1&gt; <span class="keyword">element</span>(2, {abc, def, ghi}).
def</pre>
<p>We want to store at least the 10 most recent messages, so we have to group them somehow. Erlang has a powerful list abstraction in the spirit of Lisp or Scheme, so it should suit our needs. A list in Erlang syntax looks like that:</p>
<pre>
[{message, <span class="string">"12:00 01-10-1987"</span>, <span class="string">"Foo Bar"</span>, <span class="string">"Hello Bar!"</span>, <span class="string">"Nice to meet you"</span>},
 {message, <span class="string">"16:32 05-05-2006"</span>, <span class="string">"Whoever"</span>, <span class="string">"Some subject"</span>, <span class="string">"Whatever"</span>}]</pre>
<p>From the components we outlined, creating the feed from a supplied list of messages seems to be the simplest task to do. Just put the various message field into corresponding XML fields and wrap it with some more XML on the beginning and on the end.</p>
<pre>
<span class="function-name">-module</span>(rss_wrap).
<span class="function-name">-compile</span>(export_all).

<span class="function-name">-define</span>(<span class="constant">prologue</span>(<span class="variable-name">Date</span>),
        <span class="string">"&lt;?xml version=\"1.0\"?&gt;
         &lt;rss version=\"2.0\"&gt;
         &lt;channel&gt;
         &lt;title&gt;GMailRSS&lt;/title&gt;
         &lt;description&gt;Your mailbox in RSS using Erlang.&lt;/description&gt;
         &lt;language&gt;en-us&lt;/language&gt;
         &lt;docs&gt;http://blogs.law.harvard.edu/tech/rss&lt;/docs&gt;
         &lt;generator&gt;RssGmail&lt;/generator&gt;"</span> ++
         <span class="string">"&lt;pubDate&gt;"</span> ++ <span class="variable-name">Date</span> ++ <span class="string">"&lt;/pubDate&gt;"</span>).

<span class="function-name">-define</span>(<span class="constant">epilogue</span>,
        <span class="string">"&lt;/channel&gt;
         &lt;/rss&gt;"</span>).

<span class="function-name">escape_from</span>(<span class="variable-name">From</span>) -&gt;
    <span class="variable-name">Left</span> = <span class="keyword">element</span>(2, regexp:gsub(<span class="variable-name">From</span>, <span class="string">"&lt;"</span>, <span class="string">"("</span>)),
    <span class="variable-name">Right</span> = <span class="keyword">element</span>(2, regexp:gsub(<span class="variable-name">Left</span>, <span class="string">"&gt;"</span>, <span class="string">")"</span>)),
    <span class="variable-name">Right</span>.

<span class="function-name">rss_wrap</span>(<span class="variable-name">MsgList</span>) -&gt;
    <span class="keyword">case</span> <span class="variable-name">MsgList</span> <span class="keyword">of</span>
        [] -&gt;
            <span class="variable-name">CurrTime</span> = erlang:universaltime(),
            <span class="variable-name">Date</span> = httpd_util:rfc1123_date(<span class="variable-name">CurrTime</span>);
        <span class="variable-name">List</span> -&gt;
            <span class="variable-name">Date</span> = <span class="keyword">element</span>(2, lists:last(<span class="variable-name">MsgList</span>)),
    <span class="keyword">end</span>,

    ?<span class="constant">prologue</span>(<span class="variable-name">Date</span>) ++ rss_wrap_list(<span class="variable-name">MsgList</span>) ++ ?<span class="constant">epilogue</span>.

<span class="function-name">rss_wrap_list</span>(<span class="variable-name">MsgList</span>) -&gt;
    <span class="variable-name">WrapItem</span> = <span class="keyword">fun</span>(<span class="variable-name">Item</span>, <span class="variable-name">Result</span>) -&gt;<span class="function-name"> </span><span class="variable-name">Result</span> ++ rss_wrap_item(<span class="variable-name">Item</span>) <span class="keyword">end</span>,
    lists:foldl(<span class="variable-name">WrapItem</span>, <span class="string">""</span>,  <span class="variable-name">MsgList</span>).

<span class="function-name">rss_wrap_item</span>({message, <span class="variable-name">Date</span>, <span class="variable-name">From</span>, <span class="variable-name">Subject</span>, <span class="variable-name">Content</span>}) -&gt;
    <span class="string">"&lt;item&gt;"</span> ++
      <span class="string">"&lt;title&gt;"</span> ++ <span class="variable-name">Subject</span> ++ <span class="string">"&lt;/title&gt;"</span> ++
      <span class="string">"&lt;description&gt;"</span> ++
        <span class="string">"From: "</span> ++ escape_from(<span class="variable-name">From</span>) ++
        <span class="variable-name">Content</span> ++
      <span class="string">"&lt;/description&gt;"</span> ++
      <span class="string">"&lt;pubDate&gt;"</span> ++ <span class="variable-name">Date</span> ++ <span class="string">"&lt;/pubDate&gt;"</span> ++
    <span class="string">"&lt;/item&gt;"</span>.</pre>
<p>The &#8220;-module&#8221; declaration gives you a namespace for the functions you will define in the file and it must be the same as the filename in which the code is stored (but without the &#8220;.erl&#8221;). &#8220;-compile(export_all)&#8221; - tells the Erlang compiler to export all function automatically, so that they become globally available. In production you would like to export each of them manually, but while you are developing something it&#8217;s convenient not too change the exports everytime you add a function. </p>
<p>&#8220;-define&#8221; lets you define constants, which you can later refer to with a preceding quotation mark. You can also use it to write something similar to C macros - like in the prologue definition. &#8220;++&#8221; is string concatenation, so the prologue will contain the beginning of the feed&#8217;s with the publication date embedded somewhere inside.</p>
<p>The main function &#8220;rss_wrap&#8221; checks if the message list is empty and either sets the date to the current time using the matching RFC&#8217;s syntax, or to the arrival date of the last message in the list. Later it returns the result - the concatenation of the XML &#8220;prologue&#8221; with the date embedded, the result of the rss_wrap_list function call and the XML &#8220;epilogue&#8221;. Note that consecutive statements in functions are separated by commas, and that each definition ends with a dot. We will cover the details of the &#8220;case&#8221; construction later on.</p>
<p>The rss_wrap_list function shows one of the most common used idioms in any serious programming language. What foldl does (it is also present in Lisp, and in Ruby as &#8220;inject&#8221;) is accumulating all the elements of a list into a single variable in a way defined by the user. In Erlang you first define a fun (which is simply a function with no name bound to it, that&#8217;s why we have to assign it to something or pass to a function immediately) taking two parameters, one representing the element of the list that is currently being processed and the second one being the accumulator. The fun has to return the new value of the accumulator after processing one element. We give that fun to foldl, together with the initial value of the accumulator and with the actual list. If you have trouble understanding it look at a simpler example first:</p>
<pre>
<span class="function-name">-module</span>(test123).
<span class="function-name">-compile</span>(export_all).

<span class="function-name">foldl_test</span>() -&gt;
  <span class="variable-name">ProcessedList</span> = [1, 2, 3, 4, 5],
  <span class="variable-name">CollectFun</span> = <span class="keyword">fun</span>(<span class="variable-name">ProcessedItem</span>, <span class="variable-name">Accumulator</span>) -&gt;<span class="function-name"> </span><span class="variable-name">Accumulator</span> + <span class="variable-name">ProcessedItem</span> <span class="keyword">end</span>,
  lists:foldl(<span class="variable-name">CollectFun</span>, 0, <span class="variable-name">ProcessedList</span>).</pre>
<p>We start the foldl with the initial accumulator value of 0. The first item of the array is 1 and the fun returns the accumulator summed with the item, so here it returns 1, which becomes the new value of the accumulator. Now the fun is called for the second item, which is 2, summing it up with the accumulator we get 3, which becomes the new accumulator. And so it goes until the end of the list - finally foldl returns the sum of all elements in the array.</p>
<p>In rss_wrap_list we do preciesly the same thing, but we&#8217;re using a string accumulator and the rss_wrap_item function which wraps each message tuple in XML conforming to the RSS 2.0 standard. We also need to escape the &#8220;<" and ">&#8221; characeters the From header may contain, so we introduce the escape_from function doing preceisly that. We use &#8220;element&#8221; in it, because the gsub function returns a tuple with several fields, not only the string after the substitution.</p>
<p>One more thing: in the above examples we&#8217;re using assignment - keep in mind that in Erlang all &#8220;variables&#8221; are immutable - once you define something, you can&#8217;t change its value. This may sound bad to you, but this is also one of the reasons concurrency in Erlang is easy. </p>
<p>Now we have one component ready. We can save it in a file named &#8220;rss_wrap.erl&#8221; and test it in the Erlang shell:</p>
<pre>
<span class="function-name">c</span>(rss_wrap).
rss_wrap:rss_wrap([{}, {}]).</pre>
<p><a name="pop3"></a><strong>3: Fighting with POP3 / SSL</strong></p>
<p>Now time for the tough part. We need to connect to the POP3 server and create the list we will wrap in the XML later on. This is about writing practical stuff, so we will use GMail&#8217;s POP3 as a testbed. This doesn&#8217;t make things easier, as Google requires you to use ssl. Could it be so hard with Erlang excellent libraries, will it be so hard? Lets see&#8230;</p>
<p>First of all, if you happen to not know anything about the POP3 protocol, consult the <a href="http://www.ietf.org/rfc/rfc1939.txt">suitable RFC</a>. RFCs aren&#8217;t an easy read (well, <a href="http://www.ietf.org/rfc/rfc2324.txt">sometimes</a> they are), but hey, studying them will make you feel like a real hacker and may even turn you into one someday (if you really want it). Basically it&#8217;s a simple dialogue:</p>
<p><strong>Client:</strong> [opens the socket]<br />
<strong>Server:</strong> +OK I&#8217;m one cool pop3 server [Introduces himself, waits for authorization]<br />
<strong>Client:</strong> USER foobar<br />
<strong>Server:</strong> +OK Give me the password<br />
<strong>Client:</strong> PASS whatever<br />
<strong>Server:</strong> +OK [Gets into transaction mode]</p>
<p>When in transaction mode, you can send any number of commands you want, until a final QUIT. You can actually have this kind of conversation with your POP3 server using the fabulous netcat tool. Sadly, the standard netcat doesn&#8217;t support SSL, so for gmail you will have to download something more fancy like socat or ncat. Or you could write a short app for chatting with remote hosts through SSL&#8230;</p>
<p>Anyway, let&#8217;s see how the basic communication works. We will open a SSL socket, receive the initial POP3 greeting line, display it, close the socket and exit:</p>
<pre>
<span class="function-name">-module</span>(pop3).
<span class="function-name">-compile</span>(export_all).

<span class="function-name">fetch</span>() -&gt;
    application:start(ssl),
    {ok, <span class="variable-name">SecureSock</span>} = ssl:connect(<span class="string">"pop.gmail.com"</span>, 995,
                                   [{mode, list}, {packet, 0}, {active, false}]),
    {ok, <span class="variable-name">Response</span>} = ssl:recv(<span class="variable-name">SecureSock</span>, 0),
    io:format(<span class="string">"~s~n"</span>, [<span class="variable-name">Response</span>]),
    ssl:close(<span class="variable-name">SecureSock</span>).</pre>
<p>What do those fancy statements looking like assignments with tuples mean? Well, this is pattern matching - yet another feature of many functional languages that didn&#8217;t yet made it into the mainstream. If you look at the <a href="http://www.erlang.org/doc/doc-5.5.4/lib/ssl-3.1/doc/html/index.html">docs for the ssl module</a> you will see that the ssl:connect function either returns a tuple where the first element is the symbol &#8220;ok&#8221;, and the second the socket you just opened, or accordingly the &#8220;error&#8221; symbol and the cause of the error, also as symbol ie. &#8220;timeout&#8221;. If everything goes good than the leftside &#8220;ok&#8221; will get matched with the rightside &#8220;ok&#8221; doing preciesly nothing, and the leftside unbound variable &#8220;SecureSock&#8221; will get matched with the returned socket - assigning the socket to the variable. But if an error occurs, than &#8220;ok&#8221;, will be matched with &#8220;error&#8221;, the match will not succeed and you will get a runtime error from Erlang. Trust me, you really don&#8217;t want to see an Erlang runtime error - they are mostly incomprehensible without the use of the Erlang debugger, which can at least show you the line the error occurred. You can avoid seeing them with writing your code in a fault-tolerant way - we could do error handling by matching the result of the call against more than one pattern, but this article is already getting long&#8230; Also, we should have been using pattern matching instead of the &#8220;element&#8221; function before - this way we make sure the tuple is of the format we&#8217;re expecting.</p>
<p>Going back to pop3, the general pattern of communication will be not too surprisingly Request -> Response, so maybe we can capture a higher level abstraction&#8230; Actually, we also don&#8217;t have a guarantee that the response will come in one portion (hence one ssl:recv), so we need to pull data out of the socket until we reach a CR/LF at the end:</p>
<pre>
<span class="function-name">request</span>(<span class="variable-name">Socket</span>, <span class="variable-name">Command</span>) -&gt;
    io:format(<span class="string">"Request: ~s~n"</span>, [<span class="variable-name">Response</span>]),
    ssl:send(<span class="variable-name">Socket</span>, <span class="variable-name">Command</span> ++ <span class="string">"\n"</span>).

<span class="function-name">retrieve_line</span>(<span class="variable-name">Socket</span>, <span class="variable-name">Data</span>) -&gt;
    <span class="variable-name">Length</span> = <span class="keyword">length</span>(<span class="variable-name">Data</span>),
    <span class="variable-name">ValidP</span> = (<span class="variable-name">Length</span> &gt; 2) <span class="keyword">andalso</span> (string:substr(<span class="variable-name">Data</span>, <span class="variable-name">Length</span> - 1, 2) =:= <span class="string">"\r\n"</span>),
    <span class="keyword">if</span>
        <span class="variable-name">ValidP</span> =:= true -&gt;
            <span class="variable-name">Data</span>;
        true -&gt;
            {ok, <span class="variable-name">NewData</span>} = ssl:recv(<span class="variable-name">Socket</span>, 0),
            retrieve_line(<span class="variable-name">Socket</span>, <span class="variable-name">Data</span> ++ <span class="variable-name">NewData</span>)
    <span class="keyword">end</span>.

<span class="function-name">response_line</span>(<span class="variable-name">Socket</span>) -&gt;
    <span class="variable-name">Response</span> = retrieve_line(<span class="variable-name">Socket</span>, []),
    io:format(<span class="string">"Response: ~s~n"</span>, [<span class="variable-name">Response</span>]),
    string:substr(<span class="variable-name">Response</span>, 1, string:len(<span class="variable-name">Response</span>) - 2).</pre>
<p>The request method simply sends whatever you want through the socket, only adding a newline so that you don&#8217;t have to type it every time.</p>
<p>Getting the response is a bit more complicated. Before checking the string ending for the CR/LF we need to check if the string is long enough - if the indicies in string:substr are out of string bounds we will get a run-time error from Erlang. We do it using &#8220;andalso&#8221; - if the length is less than or equal to two the second statement will not be evaluated. Afterwards we actually check for the CR/LF, and if it is found, we return the data to the caller function. Otherwise, we try to get yet more data from the socket and we call the function we&#8217;re actually in - note that nothing gets returned to the caller until the recursion ends. Also, the if statement works different a bit than we&#8217;re used to - it does pattern matching in fact, that&#8217;s why use &#8220;true&#8221; instead of &#8220;else&#8221;, because &#8220;true&#8221; always matches.</p>
<p>Receive_line may look inconspicuous, but it illustrates one of the important &#8220;patterns&#8221; in Erlang - the way you deal with things that change over time. Normally you would use variables for that, but as we already said they are immutable. So in Erlang you use function parameters and recursive calls to deal with that. Actually, to represent a process, one also uses something that looks like a recursive function call running for very long.</p>
<p>Stepping back to our program, the response_rn method strips the final newline from the response and outputs it to the standard output - it&#8217;s mainly a convenience wrapper. Notice that things in Erlang are numbered from one, not from zero like in C for example.</p>
<p>Now we can have the conversation we talked about:</p>
<pre>
<span class="function-name">fetch</span>() -&gt;
    application:start(ssl),
    {ok, <span class="variable-name">SecureSock</span>} = ssl:connect(<span class="string">"pop.gmail.com"</span>, 995,
                                   [{mode, list}, {packet, 0}, {active, false}]),
    response(<span class="variable-name">SecureSock</span>),

    request(<span class="variable-name">SecureSock</span>, <span class="string">"USER foobar"</span>),
    response(<span class="variable-name">SecureSock</span>),
    request(<span class="variable-name">SecureSock</span>, <span class="string">"PASS hello"</span>),
    response(<span class="variable-name">SecureSock</span>),

    ssl:close(<span class="variable-name">SecureSock</span>).
</pre>
<p>Just remember to replace foobar with your gmail user name and hello with you password. Here comes the hardest part - we need to get the emails out of the POP3 and turn them into a nice list in the format we introduced on the very beginning. This sounds like pain to me. We will also need to take a look at another RFC, describing the format of the message returned by the server.</p>
<p>Generally, after authenticating we need to do a STAT. This will give us the number of messages in the mailbox. Than we need to make a RETR for each consecutive message number. </p>
<pre>
<span class="function-name">-module</span>(pop3).
<span class="function-name">-compile</span>(export_all).

<span class="function-name">response</span>(<span class="variable-name">Socket</span>) -&gt;
    {ok, <span class="variable-name">Response</span>} = ssl:recv(<span class="variable-name">Socket</span>, 0),
    io:format(<span class="string">"Response: ~s"</span>, [<span class="variable-name">Response</span>]),
    <span class="variable-name">Response</span>.

<span class="function-name">request</span>(<span class="variable-name">Socket</span>, <span class="variable-name">Command</span>) -&gt;
    io:format(<span class="string">"Request: ~s~n"</span>, [<span class="variable-name">Command</span>]),
    ssl:send(<span class="variable-name">Socket</span>, <span class="variable-name">Command</span> ++ <span class="string">"\n"</span>).

<span class="function-name">authenticate</span>(<span class="variable-name">Socket</span>, <span class="variable-name">Login</span>, <span class="variable-name">Pass</span>) -&gt;
    request(<span class="variable-name">Socket</span>, <span class="string">"USER "</span> ++ <span class="variable-name">Login</span>),
    response(<span class="variable-name">Socket</span>),
    request(<span class="variable-name">Socket</span>, <span class="string">"PASS "</span> ++ <span class="variable-name">Pass</span>),
    response(<span class="variable-name">Socket</span>).

<span class="function-name">do_stat</span>(<span class="variable-name">Socket</span>) -&gt;
    request(<span class="variable-name">Socket</span>, <span class="string">"STAT"</span>),
    {ok, <span class="variable-name">Tokens</span>} = regexp:split(response(<span class="variable-name">Socket</span>), <span class="string">" "</span>),
    {<span class="keyword">list_to_integer</span>(lists:nth(2, <span class="variable-name">Tokens</span>)),
     <span class="keyword">list_to_integer</span>(lists:nth(3, <span class="variable-name">Tokens</span>))}.

<span class="function-name">fetch</span>() -&gt;
    application:start(ssl),
    {ok, <span class="variable-name">SecureSock</span>} = ssl:connect(<span class="string">"pop.gmail.com"</span>, 995,
                                   [{mode, list}, {packet, 0}, {active, false}]),
    response(<span class="variable-name">SecureSock</span>),
    authenticate(<span class="variable-name">SecureSock</span>, <span class="string">"foobar"</span>, <span class="string">"barfoo"</span>),
    {<span class="variable-name">MessageCount</span>, <span class="variable-name">_</span>} = stat(<span class="variable-name">SecureSock</span>),
    ssl:close(<span class="variable-name">SecureSock</span>).</pre>
<p>I extracted the authentication into a separate method, and added the &#8220;stat&#8221; function. It makes a STAT request, which in response gives you something like this:</p>
<pre>
+OK 10 12345 Anything can be here
</pre>
<p>Where 10 is the number of messages and 12345 size of all of them. So what the stat function does is to split the response on spaces, extract the two fields we may care about, and convert them to integers. Strings in Erlang are just a list of integers (unfortunately), so the function list_to_integer is also used for converting strings to integer. The function nth from the lists module simply extracts the nth element from a list.</p>
<p>Now we need to make a &#8220;RETR&#8221; request for every message. It takes a number as an argument, where valid numbers go from one to the number STAT gave us. So &#8220;normally&#8221; we would probably use a for loop for this, but in Erlang iteration is often done in a different manner, take a look at the following code snippet:</p>
<pre>
<span class="function-name">retrieve_messages</span>(<span class="variable-name">Socket</span>, <span class="variable-name">From</span>, <span class="variable-name">To</span>) <span class="keyword">when</span> <span class="variable-name">From</span> &lt; <span class="variable-name">To</span> -&gt;
    [retr(<span class="variable-name">Socket</span>, <span class="variable-name">From</span>)|retrieve_messages(<span class="variable-name">Socket</span>, <span class="variable-name">From</span>+1, <span class="variable-name">To</span>)];

<span class="function-name">retrieve_messages</span>(<span class="variable-name">Socket</span>, <span class="variable-name">To</span>, <span class="variable-name">To</span>) -&gt;
    [retr(<span class="variable-name">Socket</span>, <span class="variable-name">To</span>)].</pre>
<p>This may look like a nonsense, but you must know that Erlang does also pattern matching on function arguments. Thus, the second definition of &#8220;retrieve_messages&#8221; will only be called when the second and third argument is exactly the same, otherwise the first definition will be used. Syntactically, notice that multiple &#8220;versions&#8221; of the same function are separated with semicolons, the only exception being the last definition, which you end with a dot. Also, if you define a &#8220;retrieve_messages&#8221; with two arguments, it will be a completely different function.</p>
<p>If you&#8217;ve written functional programs before, you probably already know what the code above does, otherwise it may be a little bit hard to wrap your mind around this for the first time. What the first definition says is that the result of calling it is a list built from calling retr and from calling retrieve_messages with the same arguments, except the From parameter being increased by one. &#8220;|&#8221; is the basic list building thing, like &#8220;cons&#8221; from Lisp. This obviously is recursive, so the second call to retrieve_messages may also expand futher. Let&#8217;s say we call retrieve_messages(SomeSocket, 1, 3). It will go like this:</p>
<p>retrieve_messages(SomeSocket, 1, 3) returns:</p>
<pre>
[retr(<span class="variable-name">Socket</span>, 1) | retrieve_messages(<span class="variable-name">Socket</span>, 2, 3)]</pre>
<p>But retrieve_messages(Socket, 2, 3) returns:</p>
<pre>
[retr(<span class="variable-name">Socket</span>, 2) | retrieve_messages(<span class="variable-name">Socket</span>, 3, 3)]</pre>
<p>So the first call gets futher expanded to:</p>
<pre>
[retr(<span class="variable-name">Socket</span>, 1), retr(<span class="variable-name">Socket</span>, 2) | retrieve_messages(<span class="variable-name">Socket</span>, 3, 3)]</pre>
<p>retrieve_messages(Socket, 3, 3) matches the second definition, so<br />
the recursion ends, because we get &#8220;[retr(Socket, 3)]&#8221; from it. So the<br />
final expansion looks like this:</p>
<pre>
[retr(<span class="variable-name">Socket</span>, 1), retr(<span class="variable-name">Socket</span>, 2) | [retr(<span class="variable-name">Socket</span>, 3)]]</pre>
<p>Which is evaluated simply to:</p>
<pre>
[retr(<span class="variable-name">Socket</span>, 1), retr(<span class="variable-name">Socket</span>, 2), retr(<span class="variable-name">Socket</span>, 3)]</pre>
<p>Well, nobody said that this is going to be easy&#8230; Doing the actual RETR isn&#8217;t all that fun either. More often than not, the message will be send in portions, so our response method isn&#8217;t exactly valid anymore. As we can read in the RFC, a multiline response is terminated by the &#8220;\r\n.\r\n&#8221; string. So we can write another response function:</p>
<pre>
<span class="function-name">retrieve_multiline</span>(<span class="variable-name">Socket</span>, <span class="variable-name">Data</span>) -&gt;
    <span class="variable-name">Length</span> = string:len(<span class="variable-name">Data</span>),
    <span class="variable-name">Ending</span> = string:substr(<span class="variable-name">Data</span>, <span class="variable-name">Length</span> - 4, 5),
    <span class="variable-name">ValidP</span> = (<span class="variable-name">Length</span> &gt; 5) <span class="keyword">andalso</span> (<span class="variable-name">Ending</span> =:= <span class="string">"\r\n.\r\n"</span>),
    <span class="keyword">if</span>
        <span class="variable-name">ValidP</span> =:= true -&gt;
            <span class="variable-name">Data</span>;
        true -&gt;
            {ok, <span class="variable-name">NewData</span>} = ssl:recv(<span class="variable-name">Socket</span>, 0),
            retrieve_multiline(<span class="variable-name">Socket</span>, <span class="variable-name">Data</span> ++ <span class="variable-name">NewData</span>)
    <span class="keyword">end</span>.

<span class="function-name">response_multiline</span>(<span class="variable-name">Socket</span>) -&gt;
    <span class="variable-name">Response</span> = retrieve_multiline(<span class="variable-name">Socket</span>, []),
    io:format(<span class="string">"Response: ~s~n"</span>, [<span class="variable-name">Response</span>]),
    string:substr(<span class="variable-name">Response</span>, 1, string:len(<span class="variable-name">Response</span>) - 5).</pre>
<p>But that is very repetitive. Let&#8217;s rewrite both response functions in a more generic way:</p>
<pre>
<span class="function-name">retrieve</span>(<span class="variable-name">Socket</span>, <span class="variable-name">Data</span>, <span class="variable-name">Ending</span>) -&gt;
    <span class="variable-name">DataLen</span> = <span class="keyword">length</span>(<span class="variable-name">Data</span>),
    <span class="variable-name">EndingLen</span> = <span class="keyword">length</span>(<span class="variable-name">Ending</span>),
    <span class="variable-name">ValidP</span> = (<span class="variable-name">DataLen</span> &gt; <span class="variable-name">EndingLen</span>) <span class="keyword">andalso</span>
             (string:substr(<span class="variable-name">Data</span>, <span class="variable-name">DataLen</span> - <span class="variable-name">EndingLen</span> + 1, <span class="variable-name">EndingLen</span>) =:= <span class="variable-name">Ending</span>),
    <span class="keyword">if</span>
        <span class="variable-name">ValidP</span> =:= true -&gt;
            <span class="variable-name">Data</span>;
        true -&gt;
            {ok, <span class="variable-name">NewData</span>} = ssl:recv(<span class="variable-name">Socket</span>, 0),
            retrieve(<span class="variable-name">Socket</span>, <span class="variable-name">Data</span> ++ <span class="variable-name">NewData</span>, <span class="variable-name">Ending</span>)
    <span class="keyword">end</span>.

<span class="function-name">response</span>(<span class="variable-name">Socket</span>, <span class="variable-name">Ending</span>) -&gt;
    <span class="variable-name">Response</span> = retrieve(<span class="variable-name">Socket</span>, [], <span class="variable-name">Ending</span>),
    io:format(<span class="string">"Response: ~s~n"</span>, [<span class="variable-name">Response</span>]),
    string:substr(<span class="variable-name">Response</span>, 1, string:len(<span class="variable-name">Response</span>) - <span class="keyword">length</span>(<span class="variable-name">Ending</span>)).

<span class="function-name">response_line</span>(<span class="variable-name">Socket</span>) -&gt;
    response(<span class="variable-name">Socket</span>, <span class="string">"\r\n"</span>).

<span class="function-name">response_multiline</span>(<span class="variable-name">Socket</span>) -&gt;
    response(<span class="variable-name">Socket</span>, <span class="string">"\r\n\r\n"</span>).</pre>
<p>Now we can retrieve every message in the mailbox:</p>
<pre>
<span class="function-name">fetch</span>() -&gt;
    application:start(ssl),
    {ok, <span class="variable-name">SecureSock</span>} = ssl:connect(<span class="string">"pop.gmail.com"</span>, 995,
                                   [{mode, list}, {packet, 0}, {active, false}]),
    response(<span class="variable-name">SecureSock</span>),
    authenticate(<span class="variable-name">SecureSock</span>, <span class="string">"foobar"</span>, <span class="string">"barfoo"</span>),
    {<span class="variable-name">MessageCount</span>, <span class="variable-name">_</span>} = stat(<span class="variable-name">SecureSock</span>),
    <span class="keyword">if</span> <span class="variable-name">MessageCount</span> &gt; 0 -&gt;
            <span class="variable-name">Messages</span> = retrieve_messages(<span class="variable-name">SecureSock</span>, 1, <span class="variable-name">MessageCount</span>),
       true -&gt;
            io:format(<span class="string">"No new messages~n"</span>),
            <span class="variable-name">Messages</span> = []
    <span class="keyword">end</span>,
    ssl:close(<span class="variable-name">SecureSock</span>),
    <span class="variable-name">Messages</span>.</pre>
<p>The fetch function should return the list of messages at the end; I showed it at the very beginning. So the last thing we need to do is to write something that will make a tuple of the format we want out of a plain text message. When we have this function, we will map it over the Messages list and our POP3 mission will finally be finished. Parsing the message has not much to do with pop3, so we will create another module:</p>
<pre>
<span class="function-name">-module</span>(message).
<span class="function-name">-compile</span>(export_all).

<span class="function-name">get_header</span>(<span class="variable-name">Headers</span>, <span class="variable-name">HeaderName</span>) -&gt;
    <span class="variable-name">FindHeader</span> = <span class="keyword">fun</span>(<span class="variable-name">Item</span>) -&gt;<span class="function-name"> </span>lists:prefix(<span class="variable-name">HeaderName</span>, <span class="variable-name">Item</span>) <span class="keyword">end</span>,
    <span class="variable-name">Header</span> = lists:nth(1, lists:filter(<span class="variable-name">FindHeader</span>, <span class="variable-name">Headers</span>)),
    <span class="keyword">element</span>(2, regexp:sub(<span class="variable-name">Header</span>, <span class="variable-name">HeaderName</span>, <span class="string">""</span>)).

<span class="function-name">parse</span>(<span class="variable-name">Message</span>) -&gt;
    {<span class="variable-name">_</span>, <span class="variable-name">Boundary</span>, <span class="variable-name">_</span>} = regexp:first_match(<span class="variable-name">Message</span>, <span class="string">"\r\n\r\n"</span>),
    <span class="variable-name">Header</span> = string:substr(<span class="variable-name">Message</span>, 1, <span class="variable-name">Boundary</span>),
    <span class="variable-name">Body</span> = string:substr(<span class="variable-name">Message</span>, <span class="variable-name">Boundary</span> + 4, <span class="keyword">length</span>(<span class="variable-name">Message</span>) - <span class="variable-name">Boundary</span>),
    {ok, <span class="variable-name">Headers</span>} = regexp:split(<span class="variable-name">Header</span>, <span class="string">"\r\n"</span>),
    {message, get_header(<span class="variable-name">Headers</span>, <span class="string">"Date: "</span>), get_header(<span class="variable-name">Headers</span>, <span class="string">"From: "</span>),
     get_header(<span class="variable-name">Headers</span>, <span class="string">"Subject: "</span>), <span class="variable-name">Body</span>}.</pre>
<p>Lets start the analysis with the function parse. First we need to split the header part of the message from the body - they are separated by an empty line, or two CR/LFs if you wish. The function regexp:first_match return a tuple of the format &#8220;{match, Start, Length}&#8221;, but we only care about that the middle field - thats why we use &#8220;_&#8221;. Its simply a way to say that you know about the presence of other fields, but you don&#8217;t want them to be bound to anything. We could also say: </p>
<pre>
<span class="variable-name">Boundary</span> = <span class="keyword">element</span>(2, regexp:first_match(<span class="variable-name">Message</span>, <span class="string">"\r\n\r\n"</span>))</pre>
<p>because the element function simply extracts the nth element of the tuple. Than we actually split the string using the found Boundary. The extracted header gets splitted one more time, so that each line (and each header field at the same time) is an element in a list. The final expression builds the tuple representing the message using the function get_header.</p>
<p>In get_header we use another powerful function operating on lists - filter. It takes a fun returning a boolean value as an argument and returns only those elements of the list, which when supplied to the fun give &#8220;true&#8221; as a result. </p>
<p>In the definition of the fun we once again take advantage of the misery of Erlang string as a list approach - thats why we can use lists:prefix to check if the string starts with the header name we supply to get_header as an argument. </p>
<p>We actually only care about the first occurrence of the header, so we make it a variable instead of a list using lists:nth. We don&#8217;t want to have the header name in our final tuple, so in the last step we remove it and return only the &#8220;body&#8221; of the header. Now we only have to modify the fetch function from the pop3 module to apply message:parse to each message:</p>
<pre>
<span class="function-name">fetch</span>() -&gt;
    application:start(ssl),
    {ok, <span class="variable-name">SecureSock</span>} = ssl:connect(<span class="string">"pop.gmail.com"</span>, 995,
                                   [{mode, list}, {packet, 0}, {active, false}]),
    response_line(<span class="variable-name">SecureSock</span>),
    authenticate(<span class="variable-name">SecureSock</span>, <span class="string">"foobar"</span>, <span class="string">"barfoo"</span>),
    {<span class="variable-name">MessageCount</span>, <span class="variable-name">_</span>} = do_stat(<span class="variable-name">SecureSock</span>),
    <span class="keyword">if</span> <span class="variable-name">MessageCount</span> &gt; 0 -&gt;
            <span class="variable-name">Messages</span> = retrieve_messages(<span class="variable-name">SecureSock</span>, 1, <span class="variable-name">MessageCount</span>),
            <span class="variable-name">MsgProc</span> = <span class="keyword">fun</span>(<span class="variable-name">Item</span>) -&gt;<span class="function-name"> </span>message:parse(<span class="variable-name">Item</span>) <span class="keyword">end</span>,
            <span class="variable-name">ProcessedMessages</span> = lists:map(<span class="variable-name">MsgProc</span>, <span class="variable-name">Messages</span>);
       true -&gt;
            <span class="variable-name">ProcessedMessages</span> = []
    <span class="keyword">end</span>,
    ssl:close(<span class="variable-name">SecureSock</span>),
    <span class="variable-name">ProcessedMessages</span>.</pre>
<p>Voila - after all the struggles we have our messages ready for processing. We can call something like rss_wrap:rss_wrap(pop3:fetch()) to get a nice feed representing our mailbox content.</p>
<p><a name="http"></a><strong>4: Serving the thing through HTTP</strong></p>
<p>Now we need a simple web server to make our feed available in the browser. We could use Erlangs built-in inets module for doing HTTP, but since we don&#8217;t need anything fancy here we can as well implement it on our own, as it will be an excellent opportunity to introduce more language features - what we did above was all sequential stuff, now we will get to the part that makes people curious about Erlang - concurrency.</p>
<p>The basic skeleton of a server operating through TCP looks like this:</p>
<pre>
<span class="function-name">-module</span>(http).
<span class="function-name">-compile</span>(export_all).

<span class="function-name">start</span>() -&gt;
    <span class="keyword">spawn</span>(http, server, []).

<span class="function-name">server</span>() -&gt;
    {ok, <span class="variable-name">ListenSocket</span>} = gen_tcp:listen(80, [list, {packet, 0}, {active, false}]),
    listen(<span class="variable-name">ListenSocket</span>).          

<span class="function-name">listen</span>(<span class="variable-name">ListenSocket</span>) -&gt;
    <span class="keyword">case</span> gen_tcp:accept(<span class="variable-name">ListenSocket</span>) <span class="keyword">of</span>
        {ok, <span class="variable-name">Socket</span>} -&gt;<span class="function-name"> </span>-&gt;
            <span class="keyword">spawn</span>(http, retrieve, [<span class="variable-name">Socket</span>, []]),
            listen(<span class="variable-name">ListenSocket</span>);
        <span class="variable-name">_</span> -&gt;
            listen(<span class="variable-name">ListenSocket</span>)
    <span class="keyword">end</span>.

<span class="function-name">retrieve</span>(<span class="variable-name">Socket</span>, <span class="variable-name">Data</span>) -&gt;
    <span class="keyword">case</span> gen_tcp:recv(<span class="variable-name">Socket</span>, 0) <span class="keyword">of</span>
        {ok, <span class="variable-name">Packet</span>} -&gt;
            <span class="comment-delimiter">%% </span><span class="comment">Do something with the retrieved data
</span>            retrieve(<span class="variable-name">Socket</span>, <span class="variable-name">Data</span> ++ <span class="variable-name">Packet</span>);
        {error, closed} -&gt;
            gen_tcp:close(<span class="variable-name">Socket</span>)
    <span class="keyword">end</span>.</pre>
<p>Several new constructions appear in this example. The most important thing here is the spawn function - it runs a function as a separate process. This means that you don&#8217;t recieve any return value immediately like when normally calling function - instead computing the function starts, but at the same time the control flow is passed back to the caller function. Spawn in the most commonly used from takes three parameters - the module name, the function name, and a list of arguments to be supplied to the function. It returns a pid - a unique identifier of the process in the Erlang system, which can be used later mainly for passing messages. Knowing that, understanding start() shouldn&#8217;t be hard - it simply starts the http server (represented by the server() function) without blocking any other activities going on in the system and returning the control flow to the caller function as soon as the server process starts.</p>
<p>The spawned process sets up a socket for accepting incoming connections. The socket is passed to the listen function. Listen() makes use of the case instruction, used very often in Erlang. It basically does pattern matching on the result of the expression you supply it - here it checks for a incoming connection, if there is one pending it spawns a separate process to handle the request and goes back to listening for new connections. If there are no connection attempts, it just waits. Notice another use of recursive function definitions - here they are used to make a continuously running process.</p>
<p>Finally, the retrieve function pulls data out of the supplied socket and responds somehow to the recognized request. It uses its second argument to accumulate the received data over time.</p>
<p>Now we need to extend the general scheme to use HTTP. We will simplify it as much as possible - we will only respond to one kind of request, to a &#8220;GET /&#8221;. For now, we will also respond with some hardcoded text, not with content that can be dynamically changed:</p>
<pre>
<span class="function-name">-module</span>(http).

<span class="function-name">-compile</span>(export_all).

<span class="function-name">-define</span>(<span class="constant">ok_200</span>, <span class="string">"HTTP 1.1 200 OK\r\n"</span>).
<span class="function-name">-define</span>(<span class="constant">content_type</span>,
        <span class="string">"Content-Type: text/plain\r\n"</span>).
<span class="function-name">-define</span>(<span class="constant">content_length</span>(<span class="variable-name">Length</span>),
        <span class="string">"Content-Length: "</span> ++ <span class="keyword">integer_to_list</span>(<span class="variable-name">Length</span>) ++ <span class="string">"\r\n"</span>).

<span class="function-name">start</span>() -&gt;
    <span class="keyword">spawn</span>(http, server, []).

<span class="function-name">server</span>() -&gt;
    {ok, <span class="variable-name">ListenSocket</span>} = gen_tcp:listen(80, [list, {packet, 0}, {active, false}]),
    listen(<span class="variable-name">ListenSocket</span>).          

<span class="function-name">listen</span>(<span class="variable-name">ListenSocket</span>) -&gt;
    <span class="keyword">case</span> gen_tcp:accept(<span class="variable-name">ListenSocket</span>) <span class="keyword">of</span>
        {ok, <span class="variable-name">Socket</span>} -&gt;
            <span class="keyword">spawn</span>(http, retrieve, [<span class="variable-name">Socket</span>, []]),
            listen(<span class="variable-name">ListenSocket</span>);
        <span class="variable-name">_</span> -&gt;
            listen(<span class="variable-name">ListenSocket</span>)
    <span class="keyword">end</span>.

<span class="function-name">retrieve</span>(<span class="variable-name">Socket</span>, <span class="variable-name">Data</span>) -&gt;
    <span class="keyword">case</span> gen_tcp:recv(<span class="variable-name">Socket</span>, 0) <span class="keyword">of</span>
        {ok, <span class="variable-name">Packet</span>} -&gt;
            <span class="variable-name">Request</span> = <span class="variable-name">Data</span> ++ <span class="variable-name">Packet</span>,
            process_request(<span class="variable-name">Socket</span>, <span class="variable-name">Request</span>),
            retrieve(<span class="variable-name">Socket</span>, <span class="variable-name">Request</span>);
        {error, closed} -&gt;
            gen_tcp:close(<span class="variable-name">Socket</span>)
    <span class="keyword">end</span>.

<span class="function-name">process_request</span>(<span class="variable-name">Socket</span>, <span class="string">"GET / "</span> ++ <span class="variable-name">_</span>) -&gt;
    <span class="variable-name">Text</span> = <span class="string">"Hello, HTTP!"</span>,
    <span class="variable-name">Response</span> = ?<span class="constant">ok_200</span> ++
        ?<span class="constant">content_type</span> ++
        ?<span class="constant">content_length</span>(<span class="keyword">length</span>(<span class="variable-name">Text</span>)) ++ <span class="string">"\r\n"</span> ++
        <span class="variable-name">Text</span>,
    gen_tcp:send(<span class="variable-name">Socket</span>, <span class="variable-name">Response</span>),
    gen_tcp:close(<span class="variable-name">Socket</span>).

<span class="function-name">process_request</span>(<span class="variable-name">Socket</span>, <span class="variable-name">_</span>) -&gt;
    0.</pre>
<p>The function process_request does something only when the request begins with a &#8220;GET / &#8221; - the &#8220;++&#8221; in patterns is spliting the string, not concatencating it. In case of a GET, we compose a simple response consisting of the HTTP headers and some hardcoded text. Than we send the response through the socket and close it - remember that in HTTP each request is completly independent. If the request is not a GET, we just return 0 and do nothing else with it. We can start in the Erlang shell</p>
<pre>
<span class="function-name">c</span>(http).
http:start().</pre>
<p>Note that Erlang lets only privileged users grab a port, so you may have to run it with sudo.</p>
<p><a name="pieces"></a><strong>5: Putting the pieces together</strong></p>
<p>Until now all the modules we developed were rather separated. Now we need to glue the pieces together, so the processes we will be running can communicate. </p>
<p>Communication between processes in Erlang is done mainly by using two primitives - the &#8220;!&#8221; operator and the &#8220;receive&#8221; block. &#8220;!&#8221; sends a message to a pid. A message can be quite any valid Erlang data type. We use it like this:</p>
<pre>
<span class="variable-name">SomePid</span> ! do_something
<span class="variable-name">SomePid</span> ! {this, is, a, tuple}
<span class="variable-name">SomePid</span> ! [1, 2, 3, 4, 5]</pre>
<p>The only requirement is that the process represented by SomePid has the matching receive that will do something with the message. As many other constructions in Erlang, it uses pattern matching to recognize various kinds of messages, ie.:</p>
<pre>
<span class="keyword">receive</span>
    {something, <span class="variable-name">Data</span>} -&gt;
        io:format(<span class="string">"~s~n"</span>, [<span class="variable-name">Data</span>]);
    {anotherthing, <span class="variable-name">AnotherData</span>} -&gt;
        process(<span class="variable-name">AnotherData</span>)
<span class="keyword">end</span>.</pre>
<p>Before we use it in practice, lets write a separate simple example to illustrate message passing:</p>
<pre>
<span class="function-name">-module</span>(test).
<span class="function-name">-compile</span>(export_all).

<span class="function-name">server</span>() -&gt;
    <span class="keyword">receive</span>
        <span class="variable-name">Data</span> -&gt;
            io:format(<span class="string">"~w~n"</span>, <span class="variable-name">Data</span>),
            server()
    <span class="keyword">end</span>.</pre>
<p>This tiny function listens for any kind of message. When it recieves one, it simply outputs it using standard Erlang syntax. You can now send something to it from the shell:</p>
<pre>
<span class="variable-name">SomePid</span> = <span class="keyword">spawn</span>(test, server, []).
<span class="variable-name">SomePid</span> ! {something, foobar}.
<span class="variable-name">SomePid</span> ! [1, 2, 3, 4, 5].
<span class="variable-name">SomePid</span> ! <span class="string">"Whatever"</span>.</pre>
</pre>
<p>Going back to our main program, we need messages to pass the feed to the HTTP server. What we will try do is making the main function server accept two kinds of messages - one for setting the server response, and another for returning it. Actually &#8220;returning&#8221; is a tricky word here - a process wanting to get the response will have to supply his Pid and we sent the result back using messages. Look at the final version of the module:</p>
<pre>
<span class="function-name">-module</span>(http).

<span class="function-name">-compile</span>(export_all).

<span class="function-name">-define</span>(<span class="constant">ok_200</span>, <span class="string">"HTTP 1.1 200 OK\r\n"</span>).
<span class="function-name">-define</span>(<span class="constant">content_type</span>, <span class="string">"Content-Type: text/plain\r\n"</span>).
<span class="function-name">-define</span>(<span class="constant">content_length</span>(<span class="variable-name">Length</span>),
        <span class="string">"Content-Length: "</span> ++ <span class="keyword">integer_to_list</span>(<span class="variable-name">Length</span>) ++ <span class="string">"\r\n"</span>).

<span class="function-name">control_server</span>(<span class="variable-name">Response</span>) -&gt;
    <span class="keyword">receive</span>
        {set, response, <span class="variable-name">NewResponse</span>} -&gt;
            control_server(<span class="variable-name">NewResponse</span>);
        {get, response, <span class="variable-name">Pid</span>} -&gt;
            <span class="variable-name">Pid</span> ! {response, <span class="variable-name">Response</span>};
        <span class="variable-name">_</span> -&gt;
            control_server(<span class="variable-name">Response</span>)
    <span class="keyword">end</span>.

<span class="function-name">server</span>() -&gt;
    <span class="variable-name">ControlServerPid</span> = <span class="keyword">spawn</span>(http, control_server, [<span class="string">""</span>]),
    <span class="keyword">register</span>(control_server, <span class="variable-name">ControlServerPid</span>),
    <span class="keyword">spawn</span>(http, initialize, []),
    <span class="variable-name">ControlServerPid</span>.

<span class="function-name">initialize</span>() -&gt;
    <span class="keyword">case</span> gen_tcp:listen(80, [list, {packet, 0}, {active, false}]) <span class="keyword">of</span>
        {ok, <span class="variable-name">ListenSocket</span>} -&gt;
            listen(<span class="variable-name">ListenSocket</span>);
        <span class="variable-name">_</span> -&gt;
            stop
    <span class="keyword">end</span>.

<span class="function-name">listen</span>(<span class="variable-name">ListenSocket</span>) -&gt;
    <span class="keyword">case</span> gen_tcp:accept(<span class="variable-name">ListenSocket</span>) <span class="keyword">of</span>
        {ok, <span class="variable-name">Socket</span>} -&gt;
            <span class="keyword">spawn</span>(http, retrieve, [<span class="variable-name">Socket</span>, []]),
            listen(<span class="variable-name">ListenSocket</span>);
        <span class="variable-name">_</span> -&gt;
            listen(<span class="variable-name">ListenSocket</span>)
    <span class="keyword">end</span>.

<span class="function-name">retrieve</span>(<span class="variable-name">Socket</span>, <span class="variable-name">Request</span>) -&gt;
    <span class="keyword">case</span> gen_tcp:recv(<span class="variable-name">Socket</span>, 0) <span class="keyword">of</span>
        {ok, <span class="variable-name">Packet</span>} -&gt;
            process_request(<span class="variable-name">Socket</span>, <span class="variable-name">Request</span> ++ <span class="variable-name">Packet</span>),
            retrieve(<span class="variable-name">Socket</span>, <span class="variable-name">Request</span> ++ <span class="variable-name">Packet</span>);
        {error, closed} -&gt;
            gen_tcp:close(<span class="variable-name">Socket</span>)
    <span class="keyword">end</span>.

<span class="function-name">process_request</span>(<span class="variable-name">Socket</span>, <span class="string">"GET / "</span> ++ <span class="variable-name">_</span>) -&gt;
    control_server ! {get, response, <span class="keyword">self</span>()},
    <span class="keyword">receive</span>
        {response, <span class="variable-name">Text</span>} -&gt;
            <span class="variable-name">Response</span> = ?<span class="constant">ok_200</span> ++
                ?<span class="constant">content_type</span> ++
                ?<span class="constant">content_length</span>(<span class="keyword">length</span>(<span class="variable-name">Text</span>)) ++ <span class="string">"\r\n"</span> ++
                <span class="variable-name">Text</span>,
            gen_tcp:send(<span class="variable-name">Socket</span>, <span class="variable-name">Response</span>),
            gen_tcp:close(<span class="variable-name">Socket</span>)
    <span class="keyword">end</span>;

<span class="function-name">process_request</span>(<span class="variable-name">Socket</span>, <span class="variable-name">Request</span>) -&gt;
    0.</pre>
<p>First we introduce a &#8220;control server&#8221;. This process will serve as a buffer between the outside world and the HTTP server. The function starting the server (http:server()) returns the Pid of the control server to the caller process, so the user of the http module can send messages to the control server, altering the behaviour of the http server. But since we don&#8217;t have explict state in Erlang, all the &#8220;variables&#8221; are stored as function parameters. We have only one dynamic thing here, but if there was more of them, we would probably want to use a property list for storing various settings of the server. server() does also one more interesting thing - it registers the control server process, so you can refer to it by a symbolic name instead of the pid and you don&#8217;t have to pass its pid to every function.</p>
<p>The reason we want the control server to be available everywhere is that the only way to check a setting (or in our case the desired server response) is to send a message to it. This is exactly what we do in the process_request function, body of which also explains why we called the process a &#8220;control_server&#8221;. We send a message to it that we want to get the reponse and we also supply the pid the control server should respond to, by using the function self() returning the pid of the current process. Than we wait for the response from the control server and when it arrives we&#8217;re ready to actually send the response through the socket.</p>
<p>Now we can finally put the pieces together using this little beauty:</p>
<pre>
<span class="function-name">-module</span>(gmailrss).
<span class="function-name">-compile</span>(export_all).

<span class="function-name">main</span>() -&gt;
    <span class="variable-name">ServerPid</span> = http:server(),
    <span class="keyword">spawn</span>(gmailrss, loop, [<span class="variable-name">ServerPid</span>]).

<span class="function-name">loop</span>(<span class="variable-name">ServerPid</span>) -&gt;
    <span class="variable-name">Messages</span> = pop3:fetch(),
    <span class="variable-name">Rss</span> = rss_wrap:rss_wrap(<span class="variable-name">Messages</span>),
    <span class="variable-name">ServerPid</span> ! {set, response, <span class="variable-name">Rss</span>},
    timer:sleep(300000),
    loop(<span class="variable-name">ServerPid</span>).</pre>
<p>Just run the Erlang shell and call:</p>
<pre>
gmailrss:main().
</pre>
<p>Than you can fire up your RSS reader, add &#8220;http://localhost/&#8221; as the feeds adress and enjoy your email in it! The time value for the sleep function is measured in miliseconds, so it will get checked every 5 minutes.</p>
<p><a name="conclusions"></a><strong>6: Conclusions</strong></p>
<p>Wow, that turned out really long and comprehensive, considering it was first meant to be a short blog post. You can grab the source code of the finished code <a href="http://www.stifflog.com/gmailrss.zip">here</a>. We still skipped a lot of subjects ie. we totally ignored any errors that might occur, to make explaining things easier. We didn&#8217;t care too much about message encoding and stuff like that either. There is also obviously much more cool stuff in Erlang, but that&#8217;s what books and docs are for. I wonder if someone made it this far at all, but nevertheless&#8230;</p>
<p><strong>Happy hacking!</strong></p>
<p>[ Additional thanks for <a href="http://marcin.af.gliwice.pl/if-then-else">Martinez</a>, who reviewed the article and pointed out some language mistakes ]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stifflog.com/2007/05/09/erlang-for-the-practical-man/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Having Fun With Erlang</title>
		<link>http://www.stifflog.com/2007/03/12/having-fun-with-erlang/</link>
		<comments>http://www.stifflog.com/2007/03/12/having-fun-with-erlang/#comments</comments>
		<pubDate>Mon, 12 Mar 2007 18:09:57 +0000</pubDate>
		<dc:creator>stiff</dc:creator>
		
		<category><![CDATA[Erlang]]></category>

		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://www.stifflog.com/2007/03/12/having-fun-with-erlang/</guid>
		<description><![CDATA[It seems that the times when programs run sequentially using one main processor are finally getting to an end&#8230; Not only more and more computations get so complex you need to use a whole network of computers to do them, not only computer clusters are increasingly popular, but also our own home computers finally have [...]]]></description>
			<content:encoded><![CDATA[<p>It seems that the times when programs run sequentially using one main processor are finally getting to an end&#8230; Not only more and more computations get so complex you need to use a whole network of computers to do them, not only computer clusters are increasingly popular, but also our own home computers finally have become somewhat &#8220;parallel&#8221;. As we reached the border where we can&#8217;t tune the processor frequencies so much, chip vendors seem to look for hope in multi-CPU, multi-core circuits as in Intel Core 2 Duo for example. This has multiple benefits, but also raises one big issue - the troubles with writing programs that use the multiple chips or even multiple computers efficiently. At the same time, the Web still grows, and we have more and more systems where hundreds of thousands of people interact with the software in real time (examples vary from MMORPGs to web servers).</p>
<p><span id="more-16"></span></p>
<p>Now, have you ever tried to do a different thing with your left hand and a different one with your right at the same time? Ask somebody playing a piano how hard it can be without a good amount of practice. Most of the time, our brain isn&#8217;t too good at doing more than one thing at once - no wonder we have also problems conceptualizing computer programs that do multiple things simultaneously. The only thing we can do is use our intelligence and write tools that will ease the job. Here also lies the biggest problem - most of our tools for writing concurrent applications are dumb and more often they cause a lot of confusion than help us build better software. When you say &#8220;concurrent&#8221; in the presence of a programmer, he will probably have those four associations - Java, threads, deadlocks, headache.</p>
<p>Threads as most of us know them suck big time, even on a conceptual ground, as a model of computation, what to say about the practical realizations. It&#8217;s hard to get something non-trivial done with them, it&#8217;s hard to prove the correctness of a thread-based computer program and when later something goes wrong it&#8217;s sometimes almost impossible to find the bug and even harder to remove it. Of course, it&#8217;s possible to write correct and efficient concurrent applications like this, but it requires a lot of knowledge and skills from the programmer, which he could otherwise use to work on the actual program logic.</p>
<p>Actually, the problem does not only apply to threads, it&#8217;s also the paradigm of the most popular languages that makes concurrency a serious issue. It&#8217;s hard to write a parallel program when state is shared between multiple processes running at the same time and in commonly used imperative languages there is a lot to share. That&#8217;s the chance for Erlang. It&#8217;s the only relatively known language that tackles concurrency in a different way. First of all, it is declarative, so there is no state to share. The declarativeness will strike you from the very beginning - once you &#8220;assign&#8221;, or rather match a variable with a value you cannot change it in Erlang, so most of your Java/C++/Python/Ruby tricks won&#8217;t work and you will have to learn a different way of thinking about programming.</p>
<p>The basic unit of Erlang concurrency model is called a process. Processes are a bit like threads, but they can communicate only using messages, there is no other way they can share anything. They are also very lightweight, so you can have a whole lot of them without worrying too much about hogging resources. Processes are also a way to model real-world objects, as there is no traditional OOP in Erlang. Each process has a unique id, through, and you can easily replace one process accepting a set of messages with another one accepting the same set as a form of polymorphism, so you can think of processes also like of a substitution for classes.</p>
<p>As you see, even when you forget about the parallel stuff, Erlang has some interesting traits, and we didn&#8217;t touch everything yet. You will find pattern matching, higher order functions, list comprehensions and other weird stuff in the language. Besides, it has some commercial support behind it and they were some serious projects at Ericsson using it, unlike many of the other languages that are theoretically interesting in some way. The libraries are quite big and well enough documented (at least for my standards) so there is a solid base for doing something useful. By being a declarative language it is also totally different from the stuff you usually code in &#8220;software factories&#8221;, so it also seems to be fun and challenging to learn.</p>
<p>I tried it a month or two ago, mostly by accident, researching options for writing a backend server needed for my job. I didn&#8217;t have to write it in the end, but instead I found some nifty and surprising stuff in Erlang and got into it a bit. One more unusual thing that strike me was the runtime environment - it&#8217;s very powerful and you can do a wide variety of things using it. Its something between an interpreter, compiler, debugger etc. all driven by a single shell. The system has also the advantage <a href="http://steve-yegge.blogspot.com/2007_01_01_archive.html">Steve Yegge blogged about</a> - it doesn&#8217;t have to reboot. You can hot swap a piece of code without problems while the rest of the system is running. When one of the processes fails, the rest can continue to operate perfectly, like you can see in the <a href="http://video.google.pl/videoplay?docid=-5830318882717959520&#038;q=erlang">Erlang movie</a>. Like most good languages, Erlang has also a Emacs mode bundled ;)</p>
<p>There is so much new stuff to discover here, that I feel a lot of fun trying to explore it - the last time I felt like this was when I started learning Ruby a few years ago. Of course, the field where you can apply it in &#8220;real world&#8221; maybe isn&#8217;t that wide, but the fun factor makes other things less important&#8230;</p>
<p>If you think Erlang may be interesting, check out some more resources:</p>
<p><a href="http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.html">The Problem With Threads</a> (through <a href="http://www.algorithm.com.au/blog/files/the-problem-with-threads.html">Algorithm.au</a>) - A in-depth paper explaining why traditional threading sucks</p>
<p><a href="http://www.erlang.org/">Erlang Homepage</a> - with a complete <a href="http://www.erlang.se/doc/doc-5.5.3/doc/index.html">reference</a>, <a href="http://www.erlang.se/doc/doc-5.5.3/doc/getting_started/part_frame.html">tutorials</a>, <a href="http://www.erlang.se/doc/programming_rules.shtml">programming guidelines</a>, the interpreter etc.</p>
<p><a href="http://www.castro.aus.net/~maurice/serc/erlbk/">Erlang In Real Time</a> - A free, quite comprehensive book about Erlang</p>
<p><a href="http://chuffyrodents.org/erlang.pdf">Thinking In Erlang</a> [pdf] - A short (30 pages), but really nice tutorial on the basics of Erlang</p>
<p><a href="http://www.sics.se/~joe/thesis/armstrong_thesis_2003.pdf">Joe Armstrong&#8217;s thesis</a> - The best introduction to the language you can get for free, if you don&#8217;t mind the formal, scientific tone</p>
<p><a href="http://www.pragmaticprogrammer.com/titles/jaerlang/">Programming Erlang</a> - A new, in-progress book from the Pragmmatic Programmes about Erlang, you can download a beta pdf right now</p>
<p><a href="http://tamale.net/erlang/tutorial.shtml">Erlang For C, C++, and Java Programmers</a> - Another short tutorial, aiming to teach Erlang quickly to people with experience in more traditional, imperative languages.</p>
<p><a href="http://erlide.sourceforge.net/">Erlide</a> - An eclipse plugin for Erlang</p>
<p><a href="http://yarivsblog.com/">Yariv&#8217;s Blog</a> - A weblog mostly about writing web applications in Erlang</p>
<p><a href="http://www.erlang.org/ml-archive/erlang-questions/200302/msg00013.html">Why I choose Erlang</a> - An interesting rant about programming languages</p>
<p><a href="http://www.trapexit.org/">TrapExit</a> - A wiki about Erlang, with lots of excellent practical articles</p>
]]></content:encoded>
			<wfw:commentRss>http://www.stifflog.com/2007/03/12/having-fun-with-erlang/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
