<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
    <channel>
        <title>igstan.ro</title>
        <link>http://igstan.ro</link>
        <description><![CDATA[RSS feed for igstan.ro blog]]></description>
        <atom:link href="http://igstan.ro/rss.xml" rel="self"
                   type="application/rss+xml" />
        <lastBuildDate>Tue, 23 Sep 2014 00:00:00 UT</lastBuildDate>
        <item>
    <title>Calculating an Object Graph's Size on the JVM</title>
    <link>http://igstan.ro/posts/2014-09-23-calculating-an-object-graphs-size-on-the-jvm.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Calculating an Object Graph's Size on the JVM</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Calculating an Object Graph's Size on the JVM</h1>
    <time pubdate>September 23, 2014</time>
    <p>Here’s a little something I learned today. Recently, I had the task of adding an in memory cache for an exchange rate web service to the project I’m working on. I’ve used Guava’s <code>CacheBuilder</code> and set some random values for its maximum size and expiry periods. And the I got wondering, what would be the amount of memory this cache will need when full?</p>
<p>I had a faint idea, from Twitter, that a tool called <a href="http://openjdk.java.net/projects/code-tools/jol/">jol (Java Object Layout)</a> might be exactly what I needed, but I wasn’t exactly sure. I investigated and, sure enough, it is a very good tool for finding not only the memory size of an object graph, but also how objects are laid out in memory on different JVMs. This later feature is useful when optimizing for CPU caches, but I’ve got no experience with this yet.</p>
<p>Back to the subject of this blog post — finding the total amount of memory for an object graph — things are actually quite simple.</p>
<h2 id="add-dependency">Add Dependency</h2>
<p>First, you want to add jol as a dependency in your favourite build system. I’m using sbt here.</p>
<pre class="sourceCode scala"><code class="sourceCode scala">libraryDependencies += <span class="st">&quot;org.openjdk.jol&quot;</span> % <span class="st">&quot;jol-core&quot;</span> % <span class="st">&quot;1.0-SNAPSHOT&quot;</span> % <span class="st">&quot;compile&quot;</span></code></pre>
<p>As you may have noticed, I’ve declared this dependency as compile time only. We need it during interactive development, but not (yet) at runtime.</p>
<h2 id="start-exploring">Start Exploring</h2>
<p>Next, fire up <code>sbt console</code> and try these commands:</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">import</span> org.<span class="fu">openjdk</span>.<span class="fu">jol</span>.<span class="fu">info</span>.<span class="fu">GraphLayout</span>

<span class="fu">println</span>(GraphLayout.<span class="fu">parseInstance</span>(<span class="st">&quot;USD&quot;</span>).<span class="fu">toFootprint</span>)
<span class="fu">println</span>(GraphLayout.<span class="fu">parseInstance</span>(<span class="st">&quot;USD&quot;</span>).<span class="fu">toPrintable</span>)
<span class="fu">println</span>(GraphLayout.<span class="fu">parseInstance</span>(<span class="st">&quot;USD&quot;</span> -&gt; <span class="st">&quot;EUR&quot;</span>).<span class="fu">totalSize</span>)</code></pre>
<p>Here’s the output I got when inspecting a simple tuple value.</p>
<pre class="terminal">
scala&gt; println(GraphLayout.parseInstance("USD" -&gt; "EUR").toFootprint)
scala.Tuple2 instance footprint:
 COUNT   AVG   SUM DESCRIPTION
     2    24    48 [C
     2    24    48 java.lang.String
     1    24    24 scala.Tuple2
     5         120 (total)
</pre>

<p>In the first column we have an instance count per class: two instances of type <code>[C</code> or <code>Array[Char]</code>, two instance of type <code>String</code> and one instance of type <code>Tuple2</code>.</p>
<p>The third column shows how much memory all the instance of a particular type occupy. The char arrays and the strings occupy 48 bytes each. The tuple takes 24 bytes. They all add up to a total memory size of 120 bytes.</p>
<p>The average column says what amount of memory is consumed, on average, by each instance. Why on average though? I don’t have an answer to this yet, but I presume is becuse of byte alignment rules.</p>
<p>Another question might be why does a single <code>String</code> instance occupy 24 bytes? This is where another utility, called <code>ClassLayout</code> comes in handy:</p>
<pre class="terminal">
scala&gt; println(ClassLayout.parseClass(classOf[String]).toPrintable)
java.lang.String object internals:
 OFFSET  SIZE   TYPE DESCRIPTION                    VALUE
      0    12        (object header)                N/A
     12     4 char[] String.value                   N/A
     16     4    int String.hash                    N/A
     20     4    int String.hash32                  N/A
Instance size: 24 bytes (estimated, the sample instance is not available)
Space losses: 0 bytes internal + 0 bytes external = 0 bytes total
</pre>

<p>The output says precisely how the object fields will be lay out in the computer memory and how much space they take up.</p>
<p>The first item, the object header, contains class type information. It starts at offset 0 and takes up 12 bytes.</p>
<p>The second item is the first object field. In this case we have an array of chars, which is used to store the actual characters that make up the string. It starts at offset 12 and occupies 4 bytes. Similar for the subsequent two fields.</p>
<p>If you’d like to know more, the <a href="http://hg.openjdk.java.net/code-tools/jol">project’s source tree</a> contains a directory of samples demonstrating some of its features. It’s a good place to learn more about jol.</p>
<h2 id="references">References</h2>
<ul>
<li>jol — <a href="http://openjdk.java.net/projects/code-tools/jol/">http://openjdk.java.net/projects/code-tools/jol/</a></li>
<li><a href="http://psy-lob-saw.blogspot.ro/2014/03/java-object-layout-tale-of-confusion.html">Java Object Layout: A Tale Of Confusion</a></li>
<li><a href="http://bboniao.com/openjdk/2014-06/java-object-layoutjol.html">http://bboniao.com/openjdk/2014-06/java-object-layoutjol.html</a></li>
</ul>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Tue, 23 Sep 2014 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2014-09-23-calculating-an-object-graphs-size-on-the-jvm.html</guid>
</item>
<item>
    <title>Run a single specs2 example from sbt</title>
    <link>http://igstan.ro/posts/2014-08-13-run-a-single-specs2-example-from-sbt.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Run a single specs2 example from sbt</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Run a single specs2 example from sbt</h1>
    <time pubdate>August 13, 2014</time>
    <p>Every now and then I need to run an single failing specs2 test from the sbt command line. Because it happens so seldom, though, I keep on forgetting how to do it. Google isn’t very helpful either because I have to remember the specs2 terminology, i.e., specification vs example, when searching.</p>
<p>In this blog post I’ll work with the following test:</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">package</span> com.<span class="fu">example</span>.<span class="fu">quux</span>

<span class="kw">import</span> org.<span class="fu">specs2</span>.<span class="fu">mutable</span>.<span class="fu">_</span>

<span class="co">// This class represents a **specification**.</span>
<span class="kw">class</span> ExampleSpec <span class="kw">extends</span> Specification {
  <span class="st">&quot;this is a group of example&quot;</span> should {
    <span class="st">&quot;this is example one&quot;</span> in {
      <span class="kw">true</span> must <span class="fu">be</span>(<span class="kw">true</span>)
    }

    <span class="st">&quot;this is example two&quot;</span> in {
      <span class="kw">true</span> must <span class="fu">be</span>(<span class="kw">true</span>)
    }
  }
}</code></pre>
<h2 id="running-a-single-specification">Running a Single Specification</h2>
<p>If you’re interested in running all the <em>examples</em> in the <code>ExampleSpec</code> <em>specification</em>, the following sbt command will do.</p>
<pre class="terminal">sbt&gt; testOnly com.example.quux.ExampleSpec</pre>

<p>Or, using a wildcard for the package name, which is what I personally prefer.</p>
<pre class="terminal">sbt&gt; testOnly *ExampleSpec</pre>

<h2 id="running-a-single-example">Running a Single Example</h2>
<p>If, on the other hand, you’d like to run just the <em>example</em> named <code>this is example two</code>, you have to make use of the <code>-ex</code> specs2 flag. Please note, this argument only works with the specs2 testing framework. ScalaTest supports a different <a href="http://www.scalatest.org/user_guide/using_the_runner">set of arguments</a>.</p>
<pre class="terminal">sbt&gt; testOnly -- -ex "this is example two"</pre>

<p>This works, but the test reporter will show even the names of the groups that haven’t been run, which makes it hard to figure out where’s the actual failed test. For this reason, the command I’m actually using is akin to this one:</p>
<pre class="terminal">sbt&gt; testOnly *ExampleSpec -- -ex "this is example two"</pre>

<p><strong>NB</strong>: you have to wrap the example name in double quotes. Single quotes won’t do it.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Wed, 13 Aug 2014 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2014-08-13-run-a-single-specs2-example-from-sbt.html</guid>
</item>
<item>
    <title>Contravariant Functors — An Intuition</title>
    <link>http://igstan.ro/posts/2013-10-31-contravariant-functors-an-intuition.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Contravariant Functors — An Intuition</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Contravariant Functors — An Intuition</h1>
    <time pubdate>October 31, 2013</time>
    <p>Today I came across a <a href="http://tmorris.net/posts/functors-and-things-using-scala/index.html">blog post listing different types of functors</a> (expressed using Scala), and once again I found a mention of contravariant functors. I heard about them in the past, saw their signature, but… no epiphany.</p>
<p>In this post I’d like to gain an intution for what a contravariant functor is. I’ll leave it for another post to understand the other scary one, the exponential functor (shouldn’t be much harder I presume, seems to be composed of two other functors — one covariant, the other contravariant).</p>
<p>Here’s the signature given for contravariant functor in the above blog post:</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">trait</span> Contravariant[F[_]] {
  <span class="kw">def</span> contramap[A, B](f: B =&gt; A): F[A] =&gt; F[B]
}</code></pre>
<p>It’s pretty mind bending (for me) to understand how that <code>f</code> function can possibly get a handle over a value of type <code>B</code> when <code>B</code> can’t be found in the argument list, only in the return type (as opposed to <code>A</code>). What’s going on then?</p>
<h2 id="a-concrete-example">A Concrete Example</h2>
<p>After a brief search on the internet I found out that a good example of a contravariant functor can actually be seen in the Scala standard library. <a href="https://github.com/scala/scala/blob/v2.10.3/src/library/scala/math/Ordering.scala#L218"><code>Ordering.by</code></a> is a <code>contramap</code> incarnation, specialized for instances of <code>Ordering</code>.</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">def</span> by[T, S](f: T =&gt; S)(<span class="kw">implicit</span> ord: Ordering[S]): Ordering[T]</code></pre>
<p>The signature looks a bit different that the one used by Tony Morris, but they’re the same conceptually (the former is just more general). What it says is that if you know how to compare elements of type <code>S</code> and you have a function relating elements of type <code>T</code> to elements of type <code>S</code>, then you know how to compare elements of type <code>T</code>.</p>
<p>There are two conceptual mappings here. At a higher-level you want to map <code>Ordering[S]</code> to <code>Ordering[T]</code>, but in order to achieve that an opposite mapping is required — from <code>T</code> to <code>S</code> — hence “contra”.</p>
<p>Generalizing we get that <code>contramap</code> is a function which says that if you give it some abstraction over a concept <code>A</code>, i.e., <code>F[A]</code>, and a function that maps from a different concept <code>B</code> to the concept <code>A</code>, then it is able to give you back an abstraction over <code>B</code>, i.e., <code>F[B]</code>. Pretty abstract maybe, but bear with me.</p>
<h2 id="intuition">Intuition</h2>
<p>Here’s a simple real world example inspired by <a href="http://www.scala-lang.org/old/node/3819.html">this thread</a>.</p>
<p>Everybody knows how to compare numbers, right? 2 is smaller than 3, 3 is greater than 2. Also, everybody knows what money are. It’s a concept we’ve been using for ages now, and it’s pretty trivial to draw a correspondence between money and numbers. We’d map a one dollar bill (100 cents) to the number 100 for example.</p>
<p>Because we know these two things: 1. how to compare numbers; 2. how to map from money to numbers, we can actually compare money. Obvious, right? Well, calling <code>contramap</code> using those two facts as arguments will provide you the knowledge of how to compare money. That’s exactly the knowledge that a contravariant functor encodes, but in a more general way, not only for numbers, money and comparisons.</p>
<p>As I said, the final goal is to actually map <code>F[A] =&gt; F[B]</code>, but in order to achieve that we need a function that maps <code>B =&gt; A</code>, i.e. the opposite (contra) direction. It’s basic abstraction. You build new abstraction out of old ones by specifying relationships between concepts.</p>
<h2 id="translating-to-scala">Translating to Scala</h2>
<p>Let’s put the above example in Scala code. First, let’s represent <code>Money</code>:</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">case</span> <span class="kw">class</span> <span class="fu">Money</span>(amount: Int)</code></pre>
<p>Scala already knows how to compare <code>Int</code>s and based on that knowledge we want to specify how <code>Money</code> should be compared, i.e., derive <code>Ordering[Money]</code> from <code>Ordering[Int]</code>. To achieve that, we need a way to specify which sub-component of <code>Money</code> is our desired <code>Int</code>, which is trivial in this example:</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">val</span> contramapFn: Money =&gt; Int = (money) =&gt; money.<span class="fu">amount</span></code></pre>
<p>Having defined that, and given that an implicit instance for <code>Ordering[Int]</code> is already in scope, all we need now is to call the <code>contramap</code> function defined on the <code>Ordering</code> object, namely, the <code>by</code> method. The resulted <code>Ordering[Money]</code> is marked as being implicit because we want the compiler to use it when we use the comparison method <code>&lt;</code>.</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">implicit</span> <span class="kw">val</span> moneyOrd: Ordering[Money] = Ordering.<span class="fu">by</span>(contramapFn)</code></pre>
<p>Now we can easily compare <code>Money</code> instances (we still need an implicit conversion from <code>Ordering</code> to <code>Ordered</code> in scope, hence the first import):</p>
<pre class="sourceCode scala"><code class="sourceCode scala">scala&gt; <span class="kw">import</span> scala.<span class="fu">math</span>.<span class="fu">Ordered</span>.<span class="fu">_</span>
<span class="kw">import</span> scala.<span class="fu">math</span>.<span class="fu">Ordered</span>.<span class="fu">_</span>

scala&gt; <span class="fu">Money</span>(<span class="dv">13</span>) &lt; <span class="fu">Money</span>(<span class="dv">20</span>)
res0: Boolean = <span class="kw">true</span>

scala&gt; <span class="fu">Money</span>(<span class="dv">23</span>) &lt; <span class="fu">Money</span>(<span class="dv">20</span>)
res1: Boolean = <span class="kw">false</span></code></pre>
<h2 id="implementing-by">Implementing <code>by</code></h2>
<p>How is <code>Ordering.by</code> implemented though? One possible implementation looks like this (the <a href="https://github.com/scala/scala/blob/v2.10.3/src/library/scala/math/Ordering.scala#L218">real one</a> is a bit more complicated due to optimizations):</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">def</span> by[T, S](f: T =&gt; S)(<span class="kw">implicit</span> ord: Ordering[S]): Ordering[T] =
  <span class="kw">new</span> Ordering[T] {
    <span class="kw">def</span> <span class="fu">compare</span>(x:T, y:T) = ord.<span class="fu">compare</span>(<span class="fu">f</span>(x), <span class="fu">f</span>(y))
  }</code></pre>
<p>As you can see, it creates an <code>Ordering</code> instance whose <code>compare</code> method simply delegates to the <code>compare</code> method of the known <code>Ordering[S]</code>, but <strong>not before</strong> transforming the <code>x</code> and <code>y</code> parameters by passing them through <code>f</code>.</p>
<p>This simple implementation also gives an idea of how <code>f</code> is able to receive an argument of type <code>T</code>. It creates a new “function” that will receive <code>T</code>s and inside that “function” will we have access to these <code>T</code>s to pass to <code>f</code>. When you need a value of a specific type and you don’t have it, what do you do? You return a function that asks for one. In this particular case we don’t have a proper function, but an object (an instance of <code>Ordering</code>), which is nothing more than a collection of functions, so the reasoning holds.</p>
<h2 id="conclusion">Conclusion</h2>
<p>There are a few more concrete implementation of contravariant functors in the pages I’ve linked to in the <a href="#resources">resources section</a> below, but the principle remains the same — you build new abstractions out of old ones by providing a mapping function from the new concept being abstracted to the old one that has already been abstracted.</p>
<h2 id="resources">Resources</h2>
<ul>
<li><a href="http://tmorris.net/posts/functors-and-things-using-scala/index.html">Functors and things using Scala</a></li>
<li><a href="https://www.fpcomplete.com/school/to-infinity-and-beyond/pick-of-the-week/profunctors">I love profunctors. They’re so easy.</a></li>
<li><a href="http://hackage.haskell.org/package/contravariant-0.4.4/docs/Data-Functor-Contravariant.html">Contravariant functors package</a> on Hackage</li>
</ul>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Thu, 31 Oct 2013 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2013-10-31-contravariant-functors-an-intuition.html</guid>
</item>
<item>
    <title>Dependencies and Modules In Scala</title>
    <link>http://igstan.ro/posts/2013-06-08-dependencies-and-modules-in-scala.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Dependencies and Modules In Scala</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Dependencies and Modules In Scala</h1>
    <time pubdate>June 08, 2013</time>
    <p>I’ve watched <a href="http://www.youtube.com/watch?v=yLbdw06tKPQ">two</a> <a href="http://2013.flatmap.no/spiewak.html">presentations</a> on how traits make for a “really, really, really” awesome module system in Scala, while:</p>
<blockquote>
<p>Dependency Injection is like a poor man’s module system that isn’t typechecked.</p>
</blockquote>
<p>I’d like to know what was meant by Dependency Injection there, because in my world <abbr title="Dependency Injection">DI</abbr> is just as typechecked. I understand Scala is the new shit, and the ability to bake enormous <a href="http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di/">cakes</a> is tantalizing, but seriously… let’s stop the hand waving. Describing something as being “really, really, really intersting”, “profound”, or whatever won’t prove anything.</p>
<p>Why is the cake pattern better than the “classical” constructor-based injection? How isn’t a simple interface/trait better than this contraption using nested traits, abstract type aliases, and long lists of traits being mixed in. Or… ok, let me rephrase it. <strong>When</strong> is the cake pattern better than “classical” constructor-based injection? I have yet to see a convincing answer. On the other hand, I can tell you when the cake pattern is categorically weaker than normal constructors.</p>
<p>But maybe people are not aware of constructor based injection… I can’t blame them though, given that Spring has tried very hard to hide this behind their bloated XML files. One thing that might help in accepting this type of DI is to think of it as a partial application over a collection of related functions. I’m sure you’ve heard this one before, right?</p>
<p>Here’s what I mean by “classical”, constructor-based, injection. We’ve got a <code>Cache</code> trait and two concrete implementations, one based on Mongo and one based on Redis.</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">trait</span> Cache[K, V] {
  <span class="kw">def</span> <span class="fu">get</span>(k: K): Option[V]
  <span class="kw">def</span> <span class="fu">set</span>(k: K, v: V): Cache[K, V]
}

<span class="kw">class</span> MongoCache[K, V]() <span class="kw">extends</span> Cache[K, V] {
  <span class="kw">override</span> <span class="kw">def</span> <span class="fu">get</span>(k: K) = ???
  <span class="kw">override</span> <span class="kw">def</span> <span class="fu">set</span>(k: K, v: V) = ???
}

<span class="kw">class</span> RedisCache[K, V]() <span class="kw">extends</span> Cache[K, V] {
  <span class="kw">override</span> <span class="kw">def</span> <span class="fu">get</span>(k: K) = ???
  <span class="kw">override</span> <span class="kw">def</span> <span class="fu">set</span>(k: K, v: V) = ???
}</code></pre>
<p>We’ve also got two abstract repositories for students and teachers.</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">trait</span> StudentRepository {
  <span class="kw">def</span> all: Seq[Student]
  <span class="kw">def</span> <span class="fu">get</span>(id: String): Option[Student]
}

<span class="kw">trait</span> TeacherRepository {
  <span class="kw">def</span> all: Seq[Teacher]
  <span class="kw">def</span> <span class="fu">get</span>(id: String): Option[Teacher]
}</code></pre>
<p>There are two implementations of them that support caching, which can be inferred by observing the constructor arguments.</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="co">/**</span>
<span class="co"> </span>*<span class="co"> A PostgreSQL backed implementation that supports caching. Notice how</span>
<span class="co"> * the cache dependency is passed through the constructor</span>.
<span class="co"> */</span>
<span class="kw">class</span> <span class="fu">PostgresStudentRepository</span>(cache: Cache[String, String]) <span class="kw">extends</span> StudentRepository {
  <span class="kw">override</span> <span class="kw">def</span> all = ???
  <span class="kw">override</span> get <span class="fu">get</span>(id: String) = ???
}

<span class="co">/**</span>
<span class="co"> </span>*<span class="co"> Same thing as with PostgresStudentRepository.</span>
<span class="co"> */</span>
<span class="kw">class</span> <span class="fu">PostgresTeacherRepository</span>(cache: Cache[String, String]) <span class="kw">extends</span> TeacherRepository {
  <span class="kw">override</span> <span class="kw">def</span> all = ???
  <span class="kw">override</span> get <span class="fu">get</span>(id: String) = ???
}</code></pre>
<p>Now that we have some components, let’s build the graph of objects/modules and let the whole system run.</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">class</span> Main {
  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]): Unit = {
    <span class="kw">val</span> mongoCache = <span class="kw">new</span> MongoCache[String, String]
    <span class="kw">val</span> redisCache = <span class="kw">new</span> RedisCache[String, String]
    <span class="kw">val</span> studentRepository = <span class="kw">new</span> <span class="fu">PostgresStudentRepository</span>(mongoCache)
    <span class="kw">val</span> teacherRepository = <span class="kw">new</span> <span class="fu">PostgresTeacherRepository</span>(redisCache)

    <span class="co">// Both repositories can now be passed to some other components</span>
    <span class="co">// via constructor injection.</span>
    <span class="kw">val</span> system = <span class="kw">new</span> System(studentRepository, teacherRepository)
    system.<span class="fu">start</span>()
  }
}</code></pre>
<p>Try to do the same thing using the cake pattern. You’ll quickly discover that you won’t be able to provide two different implementations for the <code>Cache</code> module. And that’s because in the end, when you wire together all those modules you mix together all trait members into the same “namespace” (I use it with the literal meaning here, a space for names, not with the meaning of “package”).</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">trait</span> CacheModule {
  <span class="kw">type</span> Cache[K, V] &lt;: CacheLike[K, V]

  <span class="kw">def</span> Cache[K, V]: Cache[K, V]

  <span class="kw">trait</span> CacheLike[K, V] {
    <span class="kw">def</span> <span class="fu">get</span>(k: K): V
    <span class="kw">def</span> <span class="fu">set</span>(k: K, v: V): Cache[K, V]
  }
}

<span class="kw">trait</span> MongoModule <span class="kw">extends</span> CacheModule {
  <span class="kw">override</span> <span class="kw">def</span> Cache[K, V] = <span class="kw">new</span> Cache[K, V]

  <span class="kw">class</span> Cache[K, V] <span class="kw">extends</span> CacheLike[K, V] {
    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">get</span>(k: K): V = ???
    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">set</span>(k: K, v: V): Cache[K, V] = ???
  }
}

<span class="kw">trait</span> RedisModule <span class="kw">extends</span> CacheModule {
  <span class="kw">override</span> <span class="kw">def</span> Cache[K, V] = <span class="kw">new</span> Cache[K, V]

  <span class="kw">class</span> Cache[K, V] <span class="kw">extends</span> CacheLike[K, V] {
    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">get</span>(k: K): V = ???
    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">set</span>(k: K, v: V): Cache[K, V] = ???
  }
}

<span class="kw">trait</span> StudentRepositoryModule {
  <span class="kw">type</span> StudentRepository &lt;: StudentRepositoryLike

  <span class="kw">def</span> StudentRepository: StudentRepository

  <span class="kw">trait</span> StudentRepositoryLike {
    <span class="kw">def</span> all: Seq[Student]
    <span class="kw">def</span> <span class="fu">get</span>(id: String): Option[Student]
  }
}

<span class="kw">trait</span> TeacherRepositoryModule {
  <span class="kw">type</span> TeacherRepository &lt;: TeacherRepositoryLike

  <span class="kw">def</span> TeacherRepository: TeacherRepository

  <span class="kw">trait</span> TeacherRepositoryLike {
    <span class="kw">def</span> all: Seq[Teacher]
    <span class="kw">def</span> <span class="fu">get</span>(id: String): Option[Teacher]
  }
}

<span class="kw">trait</span> PostgresStudentRepositoryModule <span class="kw">extends</span> StudentRepositoryModule {
  self: CacheModule =&gt;

  <span class="kw">override</span> <span class="kw">def</span> StudentRepository = <span class="kw">new</span> StudentRepository

  <span class="kw">class</span> StudentRepository <span class="kw">extends</span> StudentRepositoryLike {
    <span class="kw">override</span> <span class="kw">def</span> all: Seq[Student] = ???
    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">get</span>(id: String): Option[Student] = ???
  }
}

<span class="kw">trait</span> PostgresTeacherRepositoryModule <span class="kw">extends</span> TeacherRepositoryModule {
  <span class="co">// This module needs a CacheModule. Just as in the non-cake case, when</span>
  <span class="co">// the TeacherRepository&#39;s constructor required a Cache instance, in</span>
  <span class="co">// this case we declare our dependency on caching using a self-type.</span>
  self: CacheModule =&gt;

  <span class="kw">override</span> <span class="kw">def</span> TeacherRepository = <span class="kw">new</span> TeacherRepository

  <span class="kw">class</span> TeacherRepository <span class="kw">extends</span> TeacherRepositoryLike {
    <span class="kw">override</span> <span class="kw">def</span> all: Seq[Teacher] = ???
    <span class="kw">override</span> <span class="kw">def</span> <span class="fu">get</span>(id: String): Option[Teacher] = ???
  }
}</code></pre>
<p>This is where it gets interesting. Notice how we can’t provide a <code>RedisCacheModule</code>.</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">class</span> Main {
  <span class="kw">def</span> <span class="fu">main</span>(args: Array[String]): Unit = {
    <span class="kw">val</span> app = <span class="kw">new</span> System <span class="kw">with</span> PostgresStudentRepositoryModule
                         <span class="kw">with</span> PostgresTeacherRepositoryModule
                         <span class="kw">with</span> MongoCacheModule
                      <span class="co">// with RedisCacheModule is impossible...</span>
  }
}</code></pre>
<p>I agree the cake pattern looks cool, but I haven’t seen solid arguments for adopting it. It seems it’s cooler just because it uses quite a few JVM-novel language features, like traits, trait composition at call site, and self-types.</p>
<p>Both of these approaches are just as typesafe. Also, in my opinion, the former approach is easier to comprehend because it’s an old pattern, but that’s not quite a good argument, as time will easily solve this issue. However, as you’ve noticed, the cake pattern is imposing a serious limitation on how many different implementations you can provide for a single trait.</p>
<p>Another point is that both objects created from traits, as well as objects created from classes are objects, i.e. first-class values. You can still use classes and constructor-based DI if you like this idea of first-class modules. A class would be just a factory for modules.</p>
<p>There is however a particular case enabled by the cake pattern, which looks impossible to achieve using normal classes, and that is <strong>abstract interface composition</strong>.</p>
<p>I’m not sure how clearly I can describe this, but… in the above example, you can imagine that the implementation of <code>PostgresStudentRepository.get</code> will first verify the <code>cache</code> and just when there’s no value in the cache it will actually execute a database query. This piece of caching logic can be abstracted away, but notice that it depends on two traits: <code>Cache</code> and <code>StudentRepository</code>. What can we use in Scala to declare these dependencies? Self-types, of course:</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="co">/**</span>
<span class="co"> </span>*<span class="co"> This trait provides the caching boilerplate</span>,<span class="co"> but leaves undefined</span>
<span class="co"> </span>*<span class="co"> the mechanism that provides a fresh</span>,<span class="co"> non</span>-<span class="co">cached</span>,<span class="co"> Student. Also</span>,<span class="co"> we</span>
<span class="co"> * don</span>&#39;<span class="co">t specify anything about the implementation of Cache</span>.<span class="co"> These are</span>
<span class="co"> * the two interfaces</span>:<span class="co"> StudentRepository</span>.<span class="fu">slowGet</span><span class="co"> and Cache</span>.<span class="fu">get</span><span class="co"> that</span>
<span class="co"> * we</span>&#39;<span class="co">re composing within this trait</span>.
<span class="co"> */</span>
<span class="kw">trait</span> CachingStudentRepository <span class="kw">extends</span> StudentRepository {
  self: Cache =&gt;

  <span class="kw">override</span> <span class="kw">def</span> <span class="fu">get</span>(id: String): Option[Student] = {
    self.<span class="fu">get</span>(id).<span class="fu">map</span>(<span class="fu">makeStudent</span>(_)).<span class="fu">orElse</span>(<span class="fu">slowGet</span>(id))
  }

  <span class="kw">def</span> <span class="fu">slowGet</span>(id: String): Option[Student]
}</code></pre>
<p>The only way I can see this implemented without using the cake pattern is by replacing the self-type with an abstract cache member:</p>
<pre class="sourceCode scala"><code class="sourceCode scala"><span class="kw">trait</span> CachingStudentRepository <span class="kw">extends</span> StudentRepository {
  <span class="kw">def</span> cache: Cache

  <span class="kw">override</span> <span class="kw">def</span> <span class="fu">get</span>(id: String): Option[Student] = {
    cache.<span class="fu">get</span>(id).<span class="fu">map</span>(<span class="fu">makeStudent</span>(_)).<span class="fu">orElse</span>(<span class="fu">slowGet</span>(id))
  }

  <span class="kw">def</span> <span class="fu">slowGet</span>(id: String): Option[Student]
}</code></pre>
<p>This will still cause namespacing issues if a <code>CachingTeacherRepository</code> will declare an abstract <code>cache</code> member as well. It’s actually the same problem that the cake pattern suffers from. You won’t be able to provide different implementations for the same interface.</p>
<p>A simple solution is to prepend, or append, the trait name to the member: <code>cachingStudentRepositoryCache</code>. Not so nice, eh? It would be nice if Scala would allow us to rename members inherited from traits, like say… <a href="http://php.net/manual/ro/language.oop5.traits.php">PHP 5.4 does</a>, a language everybody loves to hate:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

trait <span class="kw">A</span> {
  <span class="kw">public</span> <span class="kw">function</span> smallTalk<span class="ot">()</span> {
    <span class="fu">echo</span> <span class="st">&#39;a&#39;</span><span class="ot">;</span>
  }
  <span class="kw">public</span> <span class="kw">function</span> bigTalk<span class="ot">()</span> {
    <span class="fu">echo</span> <span class="st">&#39;A&#39;</span><span class="ot">;</span>
  }
}

trait <span class="kw">B</span> {
  <span class="kw">public</span> <span class="kw">function</span> smallTalk<span class="ot">()</span> {
    <span class="fu">echo</span> <span class="st">&#39;b&#39;</span><span class="ot">;</span>
  }
  <span class="kw">public</span> <span class="kw">function</span> bigTalk<span class="ot">()</span> {
    <span class="fu">echo</span> <span class="st">&#39;B&#39;</span><span class="ot">;</span>
  }
}

<span class="kw">class</span> Talker {
  <span class="kw">use</span> <span class="kw">A</span><span class="ot">,</span> <span class="kw">B</span> {
    <span class="kw">B</span>::smallTalk insteadof <span class="kw">A</span><span class="ot">;</span>
    <span class="kw">A</span>::bigTalk insteadof <span class="kw">B</span><span class="ot">;</span>
  }
}

<span class="kw">class</span> Aliased_Talker {
  <span class="kw">use</span> <span class="kw">A</span><span class="ot">,</span> <span class="kw">B</span> {
    <span class="kw">B</span>::smallTalk insteadof <span class="kw">A</span><span class="ot">;</span>
    <span class="kw">A</span>::bigTalk insteadof <span class="kw">B</span><span class="ot">;</span>
    <span class="kw">B</span>::bigTalk <span class="kw">as</span> talk<span class="ot">;</span>
  }
}</code></pre>
<h2 id="the-cake-pattern.-when">The Cake Pattern. When?</h2>
<p>Okay, that was my little rant concerning the cake pattern. I believe people give it too much credit for no added benefit over what we were already able to do in Java. Any counter-argument will be greatly appreciated. I haven’t written this blog post to prove someone is wrong. I actually wrote it so that I know what’s the best tool for the job. And when it comes to DI in Scala, I see no clear arguments that the cake pattern is best for me.</p>
<p>Oh… I’m lying. There’s actually a situation when there’s no other choice. That’s when you have no control over your own constructors, e.g., the Servlet API. Or when you don’t even have constructors, e.g. Play! Framework controller objects (enforcing objects in Play! is again something I don’t see a good reason for, but that’s another blog post I guess).</p>
<p>So, I’m curious to see a clear example of when I’ll really have to use the cake pattern, because constructor-based injection won’t handle the issue.</p>
<h2 id="unexplored-grounds">Unexplored Grounds</h2>
<p>There are two things I haven’t yet explored in this post:</p>
<ol style="list-style-type: decimal">
<li>Whether any of these two DI patterns helps or hinders an immutable style</li>
<li>Left-most currying vs. right-most currying DI, where left-most currying is represented by constructor-based injection, and right-most currying is represented by the <a href="http://marakana.com/s/post/1108/dependency_injection_in_scala">reader monad</a>. This is also a subject for a future blog post.</li>
</ol>
<h2 id="resources">Resources</h2>
<ul>
<li>Videos
<ul>
<li><a href="http://www.youtube.com/watch?v=yLbdw06tKPQ">Cake Pattern: The Bakery from the Black Lagoon</a></li>
<li><a href="http://2013.flatmap.no/spiewak.html">Living in a Post-Functional World</a></li>
<li><a href="http://marakana.com/s/post/1108/dependency_injection_in_scala">Dead-Simple Dependency Injection is Scala</a></li>
</ul></li>
<li>Articles
<ul>
<li><a href="http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di/">Real-World Scala: Dependency Injection (DI)</a></li>
<li><a href="http://www.cakesolutions.net/teamblogs/2011/12/19/cake-pattern-in-depth/">Cake pattern in depth</a></li>
<li><a href="http://www.cakesolutions.net/teamblogs/2011/12/15/dependency-injection-vs-cake-pattern/">Dependency Injection vs. Cake pattern</a></li>
<li><a href="http://misko.hevery.com/code-reviewers-guide/">Guide: Writing Testable Code</a></li>
<li><a href="http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/">Where Have All the Singletons Gone?</a></li>
</ul></li>
</ul>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Sat, 08 Jun 2013 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2013-06-08-dependencies-and-modules-in-scala.html</guid>
</item>
<item>
    <title>Explore JVM Libraries in a Quick sbt Session</title>
    <link>http://igstan.ro/posts/2013-05-17-explore-jvm-libraries-in-a-quick-sbt-session.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Explore JVM Libraries in a Quick sbt Session</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Explore JVM Libraries in a Quick sbt Session</h1>
    <time pubdate>May 17, 2013</time>
    <p>Dear younger me, here’s a quick way to try out a new third-party library in the Scala REPL without having to create a new sbt project or edit the sbt build file.</p>
<p>In this particular example I’m just playing around with <a href="http://dispatch.databinder.net/Dispatch.html">dispatch</a>, trying to see whether it sends the correct query parameters to <a href="http://httpbin.org">httpbin.org</a>.</p>
<h3 id="create-temp-directory">Create Temp Directory</h3>
<p>This is an optional step, but I do it because sbt creates two sub-directories: project and target, and I don’t like to pollute whatever directory I’m in (usually <code>$HOME</code> or Desktop).</p>
<pre class="terminal">
λ Desktop master: mkdir -p sbt-project
λ Desktop master: cd sbt-project/
λ sbt-project master: sbt
[info] Set current project to default-a63394 (in build file:/Users/igstan/Desktop/sbt-project/)
</pre>

<h3 id="set-scala-version">Set Scala Version</h3>
<pre class="terminal">
> set scalaVersion := "2.10.0"
[info] Defining *:scala-version
[info] The new value will be used by no settings or tasks.
[info] Reapplying settings...
[info] Set current project to default-a63394 (in build file:/Users/igstan/Desktop/sbt-project/)
</pre>

<h3 id="add-library-as-dependency">Add Library as Dependency</h3>
<pre class="terminal">
> set libraryDependencies += "net.databinder.dispatch" %% "dispatch-core" % "0.10.0"
[info] Defining *:library-dependencies
[info] The new value will be used by *:all-dependencies
[info] Reapplying settings...
[info] Set current project to default-a63394 (in build file:/Users/igstan/Desktop/sbt-project/)
</pre>

<h3 id="enter-the-repl">Enter the REPL</h3>
<pre class="terminal">
> console
[info] Updating {file:/Users/igstan/Desktop/sbt-project/}default-a63394...
[info] Resolving org.slf4j#slf4j-api;1.6.2 ...
[info] Done updating.
[info] Starting scala interpreter...
[info]
Welcome to Scala version 2.10.0 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_21).
Type in expressions to have them evaluated.
Type :help for more information.
</pre>

<h3 id="import-dependencies">Import Dependencies</h3>
<pre class="terminal">
scala> import dispatch._, Defaults._
import dispatch._
import Defaults._
</pre>

<h3 id="create-a-request-builder">Create a Request Builder</h3>
<pre class="terminal">
scala> val u = url("http://httpbin.org/get")
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
u: com.ning.http.client.RequestBuilder = com.ning.http.client.RequestBuilder@2cce6b12
</pre>

<h3 id="add-some-query-params">Add Some Query Params</h3>
<pre class="terminal">
scala> u &lt;&lt;? Seq("a" -> "foo", "b" -> "bar")
res0: com.ning.http.client.RequestBuilder = com.ning.http.client.RequestBuilder@2cce6b12
</pre>

<h3 id="execute-request">Execute Request</h3>
<pre class="terminal">
scala> val r = Http(u.OK(as.String))
r: dispatch.Future[String] = scala.concurrent.impl.Promise$DefaultPromise@7495a73e
</pre>

<pre class="terminal">
scala> r.onComplete(println(_))

scala> Success({
  "args": {
    "a": "foo",
    "b": "bar"
  },
  "headers": {
    "Connection": "close",
    "Accept": "*/*",
    "Host": "httpbin.org",
    "User-Agent": "Dispatch/0.10.0"
  },
  "url": "http://httpbin.org/get?q=foo"
})

scala>
</pre>

<h2 id="improvements">Improvements</h2>
<p>I’ve added a bash alias that saves me from creating a scratch directory every time I’d like to play with some library:</p>
<pre class="sourceCode bash"><code class="sourceCode bash"><span class="fu">take ()</span> <span class="kw">{</span>
  <span class="kw">mkdir</span> -p <span class="ot">$1</span> <span class="kw">&amp;&amp;</span>
  <span class="kw">cd</span> <span class="ot">$1</span>
<span class="kw">}</span>

<span class="kw">alias</span> sbt-playground=<span class="st">&quot;take &#39;</span><span class="ot">$HOME</span><span class="st">/.sbt-playground&#39; &amp;&amp; sbt&quot;</span></code></pre>
<p>Also, because the command to add a library dependency is quite long, I’ve created an sbt alias in <code>$HOME/.sbtrc</code>:</p>
<pre><code>alias dep=set libraryDependencies +=</code></pre>
<p>Now, all I have to type in the sbt console is this command:</p>
<pre class="terminal">
> dep "net.databinder.dispatch" %% "dispatch-core" % "0.10.0"
</pre>






    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Fri, 17 May 2013 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2013-05-17-explore-jvm-libraries-in-a-quick-sbt-session.html</guid>
</item>
<item>
    <title>Scala's flatMap is not Haskell's >>=</title>
    <link>http://igstan.ro/posts/2012-08-23-scala-s-flatmap-is-not-haskell-s.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Scala's flatMap is not Haskell's >>=</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Scala's flatMap is not Haskell's >>=</h1>
    <time pubdate>August 23, 2012</time>
    <p>The behaviour of <code>flatMap</code> in Scala:</p>
<pre class="terminal">
scala> List(1, 2, 3, 4) flatMap (Some(_))
res0: List[Int] = List(1, 2, 3, 4)
</pre>

<p>The behaviour of <code>&gt;&gt;=</code> in Haskell:</p>
<pre class="terminal">
> [1, 2, 3, 4] >>= Just

&lt;interactive&gt;:4:18:
    Couldn't match expected type `[b0]' with actual type `Maybe a0'
    Expected type: a0 -> [b0]
      Actual type: a0 -> Maybe a0
    In the second argument of `(>>=)', namely `Just'
    In the expression: [1, 2, 3, 4] >>= Just
</pre>


    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Thu, 23 Aug 2012 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2012-08-23-scala-s-flatmap-is-not-haskell-s.html</guid>
</item>
<item>
    <title>Commonly Used List Processing Functions in FP</title>
    <link>http://igstan.ro/posts/2012-07-26-commonly-used-list-processing-functions-in-functional-programming.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Commonly Used List Processing Functions in FP</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Commonly Used List Processing Functions in FP</h1>
    <time pubdate>July 26, 2012</time>
    <p>A list of commonly used functions for processing collections in <abbr title="Functional Programming">FP</abbr> languages or when adopting an <abbr title="Functional Programming">FP</abbr> style. Grouped by language in alphabetical order. The listing order for the functions is the same for every language. Some functions, though, are missing in some languages or there are alternative ways to accomplish the same goal.</p>
<ul>
<li><a href="#clojure">Clojure</a></li>
<li><a href="#erlang">Erlang</a></li>
<li><a href="#haskell">Haskell</a></li>
<li><a href="#javascript-using-underscore.js">JavaScript</a></li>
<li><a href="#scala">Scala</a></li>
</ul>
<h2 id="clojure">Clojure</h2>
<ul>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/first"><code>first</code></a></li>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/rest"><code>rest</code></a></li>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/map"><code>map</code></a></li>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/filter"><code>filter</code></a> or its dual <a href="http://clojuredocs.org/clojure_core/clojure.core/remove"><code>remove</code></a></li>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/every_q"><code>every?</code></a> or its dual <a href="http://clojuredocs.org/clojure_core/clojure.core/not-every_q"><code>not-every?</code></a></li>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/some"><code>some</code></a> or its dual <a href="http://clojuredocs.org/clojure_core/clojure.core/not-any_q"><code>not-any?</code></a></li>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/zipmap"><code>zipmap</code></a></li>
<li><code>zip-with</code>. There’s no such function in Clojure, but the same thing can be achieved by passing at least two collections to <a href="http://clojuredocs.org/clojure_core/clojure.core/map"><code>map</code></a>.</li>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/take"><code>take</code></a></li>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/take-while"><code>take-while</code></a></li>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/drop"><code>drop</code></a></li>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/drop-while"><code>drop-while</code></a></li>
<li><a href="http://clojuredocs.org/clojure_core/clojure.core/reduce"><code>reduce</code></a></li>
</ul>
<p>Please note that some of the functions above will probably be superseded by the new <a href="http://clojure.com/blog/2012/05/15/anatomy-of-reducer.html">reducers library</a>.</p>
<h2 id="erlang">Erlang</h2>
<ul>
<li><a href="http://www.erlang.org/doc/man/erlang.html#hd-1"><code>hd/1</code></a></li>
<li><a href="http://www.erlang.org/doc/man/erlang.html#tl-1"><code>tl/1</code></a></li>
<li><a href="http://www.erlang.org/doc/man/lists.html#map-2"><code>lists:map/2</code></a></li>
<li><a href="http://www.erlang.org/doc/man/lists.html#filter-2"><code>lists:filter/2</code></a></li>
<li><a href="http://www.erlang.org/doc/man/lists.html#all-2"><code>lists:all/2</code></a></li>
<li><a href="http://www.erlang.org/doc/man/lists.html#any-2"><code>lists:any/2</code></a></li>
<li><a href="http://www.erlang.org/doc/man/lists.html#zip-2"><code>lists:zip2/2</code></a> and <a href="http://www.erlang.org/doc/man/lists.html#zip-2"><code>lists:zip3/3</code></a></li>
<li><a href="http://www.erlang.org/doc/man/lists.html#takewhile-2"><code>lists:takewhile/2</code></a></li>
<li><a href="http://www.erlang.org/doc/man/lists.html#dropwhile-2"><code>lists:dropwhile/2</code></a></li>
<li><a href="http://www.erlang.org/doc/man/lists.html#foldl-3"><code>lists:foldl/3</code></a></li>
<li><a href="http://www.erlang.org/doc/man/lists.html#foldr-3"><code>lists:foldr/3</code></a></li>
</ul>
<h2 id="haskell">Haskell</h2>
<ul>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:head"><code>head</code></a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:tail"><code>tail</code></a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:map"><code>map</code></a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:filter"><code>filter</code></a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:all"><code>all</code></a> or the closely related <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:and"><code>and</code></a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:any"><code>any</code></a> or the closely related <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:or"><code>or</code></a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:zip"><code>zip</code></a> or any of the <code>zip3</code> up to <code>zip7</code> in the <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html#v:zip3"><code>Data.List</code> module</a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:zipWith"><code>zipWith</code></a> or any of the <code>zipWith3</code> up to <code>zipWith7</code> in the <a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Data-List.html#v:zipWith3"><code>Data.List</code> module</a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:take"><code>take</code></a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:drop"><code>drop</code></a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:takeWhile"><code>takeWhile</code></a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:dropWhile"><code>dropWhile</code></a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:foldl"><code>foldl</code></a></li>
<li><a href="http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:foldr"><code>foldr</code></a></li>
</ul>
<h2 id="javascript-using-underscore.js">JavaScript (using underscore.js)</h2>
<ul>
<li><a href="http://underscorejs.org/#first"><code>first</code></a></li>
<li><a href="http://underscorejs.org/#rest"><code>rest</code></a></li>
<li><a href="http://underscorejs.org/#map"><code>map</code></a></li>
<li><a href="http://underscorejs.org/#filter"><code>filter</code></a> and its dual <a href="http://underscorejs.org/#reject"><code>reject</code></a></li>
<li><a href="http://underscorejs.org/#all"><code>all</code></a></li>
<li><a href="http://underscorejs.org/#any"><code>any</code></a></li>
<li><a href="http://underscorejs.org/#zip3"><code>zip</code></a></li>
<li><a href="http://underscorejs.org/#reduce"><code>reduce</code> / <code>inject</code> / <code>foldl</code></a></li>
<li><a href="http://underscorejs.org/#reduceRight"><code>reduceRight</code> / <code>foldr</code></a></li>
</ul>
<h2 id="scala">Scala</h2>
<ul>
<li><a href="http://scalex.org/?q=List.head#scalacollectionimmutableListAheadA"><code>head</code></a></li>
<li><a href="http://scalex.org/?q=List.tail#scalacollectionimmutableListAtailListA"><code>tail</code></a></li>
<li><a href="http://scalex.org/?q=List.map#scalacollectionimmutableListAmapBfABListB"><code>map</code></a></li>
<li><a href="http://scalex.org/?q=List.filter#scalacollectionimmutableListAfilterpABooleanListA"><code>filter</code></a> and its dual <a href="http://scalex.org/?q=List.filter#scalacollectionimmutableListAfilterNotpABooleanListA"><code>filterNot</code></a></li>
<li><a href="http://scalex.org/?q=List.forall#scalacollectionimmutableListAforallpABooleanBoolean"><code>forall</code></a></li>
<li><a href="http://scalex.org/?q=List.forall#scalacollectionimmutableListAexistspABooleanBoolean"><code>exists</code></a></li>
<li><a href="http://scalex.org/?q=List.forall#scalacollectionimmutableListAzipBthatGenIterableBListAB"><code>zip</code></a></li>
<li><code>zipWith</code>. There’s no such method in Scala, instead use the <a href="http://scalex.org/?q=Tuple2.zipped#scalaTuple2T1T2zippedRepr1El1Repr2El2implicitw1T1TraversableLikeEl1Repr1implicitw2T2IterableLikeEl2Repr2ZippedRepr1El1Repr2El2"><code>zipped</code></a> method which is only available for <a href="http://www.scala-lang.org/api/current/scala/Tuple2#!%3D%28Any%29%3ABoolean"><code>Tuple2</code></a> and <a href="http://www.scala-lang.org/api/current/scala/Tuple3#!%3D%28Any%29%3ABoolean"><code>Tuple3</code></a></li>
<li><a href="http://scalex.org/?q=List.zipWith#scalacollectionimmutableListAtakenIntListA"><code>take</code></a></li>
<li><a href="http://scalex.org/?q=List.drop#scalacollectionimmutableListAdropnIntListA"><code>drop</code></a></li>
<li><a href="http://scalex.org/?q=List.zipWith#scalacollectionimmutableListAtakeWhilepABooleanListA"><code>takeWhile</code></a></li>
<li><a href="http://scalex.org/?q=List.dropWhile#scalacollectionimmutableListAdropWhilepABooleanListA"><code>dropWhile</code></a></li>
<li><a href="http://scalex.org/?q=List.reduceLeft#scalacollectionimmutableListAfoldLeftBzBfBABB"><code>foldLeft</code></a></li>
<li><a href="http://scalex.org/?q=List.reduceLeft#scalacollectionimmutableListAreduceLeftBAfBABB"><code>reduceLeft</code></a></li>
<li><a href="http://scalex.org/?q=List.foldRight#scalacollectionimmutableListAfoldRightBzBfABBB"><code>foldRight</code></a></li>
</ul>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Thu, 26 Jul 2012 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2012-07-26-commonly-used-list-processing-functions-in-functional-programming.html</guid>
</item>
<item>
    <title>How Inheritance Violates Encapsulation</title>
    <link>http://igstan.ro/posts/2011-09-09-how-inheritance-violates-encapsulation.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>How Inheritance Violates Encapsulation</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>How Inheritance Violates Encapsulation</h1>
    <time pubdate>September 09, 2011</time>
    <p>I’ve recently finished reading <a href="http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683">Effective Java</a>, and in this book Joshua Bloch gives a simple demonstration on how inheritance can break encapsulation. That composition should be favoured over inheritance is a thing I hear quite a lot and I’m actually trying to follow the rule myself, but I never had a thorough understanding as to why inheritance would be a bad thing besides the fact that certain languages don’t allow multiple inheritance (a problem I hit in the past).</p>
<p>Joshua Bloch actually makes a good example of a situation where inheritance forces the developer of the subclass to know about the internals of the superclass, which means the encapsulation in the superclass is broken. I’ve put his example in a small JUnit test case:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> BrokenEncapsulationTest {

  @Test
  <span class="kw">public</span> <span class="dt">void</span> <span class="fu">testAddCount</span>() {
    InstrumentedHashSet&lt;String&gt; set = <span class="kw">new</span> InstrumentedHashSet&lt;String&gt;();

    set.<span class="fu">addAll</span>(Arrays.<span class="fu">asList</span>(<span class="st">&quot;Snap&quot;</span>, <span class="st">&quot;Crackle&quot;</span>, <span class="st">&quot;Pop&quot;</span>));

    <span class="fu">assertEquals</span>(<span class="dv">3</span>, set.<span class="fu">addCount</span>);
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> InstrumentedHashSet&lt;E&gt; <span class="kw">extends</span> HashSet&lt;E&gt; {

    <span class="kw">public</span> <span class="dt">int</span> addCount = <span class="dv">0</span>;

    @Override
    <span class="kw">public</span> <span class="dt">boolean</span> <span class="fu">add</span>(E a) {
      addCount += <span class="dv">1</span>;
      <span class="kw">return</span> <span class="kw">super</span>.<span class="fu">add</span>(a);
    };

    @Override
    <span class="kw">public</span> <span class="dt">boolean</span> <span class="fu">addAll</span>(Collection&lt;? <span class="kw">extends</span> E&gt; c) {
      addCount += c.<span class="fu">size</span>();
      <span class="kw">return</span> <span class="kw">super</span>.<span class="fu">addAll</span>(c);
    }
  }
}</code></pre>
<p>The above test fails with this message:</p>
<blockquote>
<p>java.lang.AssertionError: expected:&lt;3&gt; but was:&lt;6&gt;</p>
</blockquote>
<p>It is entirely non-obvious why <code>addCount</code> would return 6 instead of 3. After all, we only added three elements, right? The answer is that <code>HashSet.addAll()</code> uses internally the <code>add</code> method. This means, that inside <code>InstrumentedHashSet</code> we add 3 to <code>addCount</code> inside our overridden version of <code>addAll</code>, and then we add 1 three more times to <code>addCount</code> for each call to <code>add</code> that <code>super.addAll</code> executes.</p>
<p>This is such a simple and effective demonstration for a case where you really have to dig up the source of the parent class in order to find out the cause for the unexpected behaviour.</p>
<h2 id="inheritance-overflow">Inheritance Overflow</h2>
<p>Here’s another weird case I came across two times in my developer life. Once a couple of years ago while developing a PHP application, and once a few weeks ago in a Java application. If you try to run the example below you’ll get a <code>StackOverflowError</code>.</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> InheritanceOverflow {

  <span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> Parent {

    <span class="kw">public</span> <span class="dt">void</span> <span class="fu">foo</span>() {
      <span class="fu">bar</span>();
    }

    <span class="kw">public</span> <span class="dt">void</span> <span class="fu">bar</span>() {}
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> Child <span class="kw">extends</span> Parent {
    @Override
    <span class="kw">public</span> <span class="dt">void</span> <span class="fu">bar</span>() {
      <span class="co">// I have no idea that foo in Parent is actually calling bar, that calls</span>
      <span class="co">// this method, which will call foo againg, and so on. Infinite recursion.</span>
      <span class="fu">foo</span>();
    }
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="dt">void</span> <span class="fu">main</span>(String[] args) {
    <span class="kw">new</span> <span class="fu">Child</span>().<span class="fu">bar</span>();
  }
}</code></pre>
<p>Unexpected, isn’t it? As I said, I’m not making up these examples just to find weak spots about inheritance. I actually had to debug stuff like this.</p>
<h2 id="solutions">Solutions</h2>
<p>So, what’s to be done about this kind of problems? The best approach would be to use composition. This basically translates to using the Decorator pattern. For example, <code>InstrumentedHashSet</code> can be rewritten like this:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> InstrumentedHashSet&lt;E&gt; <span class="kw">implements</span> Set&lt;E&gt; {

  <span class="kw">private</span> <span class="dt">final</span> Set&lt;E&gt; wrappedSet;

  <span class="kw">public</span> <span class="dt">int</span> addCount = <span class="dv">0</span>;

  <span class="kw">public</span> <span class="fu">InstrumentedHashSet</span>(Set&lt;E&gt; wrappedSet) {
    <span class="kw">this</span>.<span class="fu">wrappedSet</span> = wrappedSet;
  }

  @Override
  <span class="kw">public</span> <span class="dt">boolean</span> <span class="fu">add</span>(E e) {
    addCount += <span class="dv">1</span>;
    <span class="kw">return</span> wrappedSet.<span class="fu">add</span>(e);
  }

  @Override
  <span class="kw">public</span> <span class="dt">boolean</span> <span class="fu">addAll</span>(Collection&lt;? <span class="kw">extends</span> E&gt; c) {
    addCount += c.<span class="fu">size</span>();
    <span class="kw">return</span> wrappedSet.<span class="fu">addAll</span>(c);
  }

  <span class="co">// The other methods required by the Set interface, which would just</span>
  <span class="co">// delegate to the wrappedSet member. Skipped for brevity.</span>
}</code></pre>
<p>If, for whatever reason, you decide you want your class to be inherited, then make sure overridable methods don’t call other overridable methods. Have them use either private helper methods, or make those helper methods final if you want to allow more relaxed visibility rules.</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> InheritanceOverflowRevisited {

  <span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> Parent {

    <span class="kw">public</span> <span class="dt">void</span> <span class="fu">foo</span>() {
      <span class="fu">barHelper</span>();
    }

    <span class="kw">public</span> <span class="dt">void</span> <span class="fu">bar</span>() {
      <span class="fu">barHelper</span>();
    }
    
    <span class="kw">private</span> <span class="dt">void</span> <span class="fu">barHelper</span>() {
      <span class="co">// do bar stuff</span>
    }
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="kw">class</span> Child <span class="kw">extends</span> Parent {
    @Override
    <span class="kw">public</span> <span class="dt">void</span> <span class="fu">bar</span>() {
      <span class="fu">foo</span>(); <span class="co">// no more StackOverflowError</span>
    }
  }

  <span class="kw">public</span> <span class="dt">static</span> <span class="dt">void</span> <span class="fu">main</span>(String[] args) {
    <span class="kw">new</span> <span class="fu">Child</span>().<span class="fu">bar</span>();
  }
}</code></pre>
<h2 id="references">References</h2>
<ul>
<li><a href="http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683">Effective Java (2nd edition)</a>, Item 16: Favor composition over inheritance</li>
</ul>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Fri, 09 Sep 2011 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2011-09-09-how-inheritance-violates-encapsulation.html</guid>
</item>
<item>
    <title>Composing Java Interfaces Using Generics</title>
    <link>http://igstan.ro/posts/2011-07-09-composing-java-interfaces-using-generics.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Composing Java Interfaces Using Generics</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Composing Java Interfaces Using Generics</h1>
    <time pubdate>July 09, 2011</time>
    <p>A few months ago I noticed an interesting aspect of the Java programming language. Everyone knows that a certain class can implement multiple interfaces in Java, but how would you specify in client code that you expect an instance of an object that implements multiple interfaces, without using the concrete type?</p>
<p>Say for example that you create a <code>QueueSet</code> class which implements both <code>Queue&lt;T&gt;</code> and <code>Set&lt;T&gt;</code>.</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">class</span> QueueSet&lt;T&gt; <span class="kw">implements</span> Queue&lt;T&gt;, Set&lt;T&gt; {
  <span class="co">// methods required by Queue and Set</span>
}</code></pre>
<p>Now, some client code needs such a <code>QueueSet&lt;T&gt;</code>. What are its options? It could require an instance of <code>QueueSet&lt;T&gt;</code> in the method signature…</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> &lt;T&gt; <span class="dt">void</span> <span class="fu">foo</span>(QueueSet&lt;T&gt; queueSet) {}</code></pre>
<p>It works, but if <code>foo</code> is itself part of a library, it would want to be as generic as possible, and as such depend on an interface rather than a concrete class. The obvious answer for this problem is to make <code>QueueSet</code> an interface, and rename the initial concrete class to something else.</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> <span class="kw">interface</span> QueueSet&lt;T&gt; <span class="kw">extends</span> Queue&lt;T&gt;, Set&lt;T&gt; {}

<span class="kw">public</span> <span class="kw">class</span> PeculiarQueueSet&lt;T&gt; <span class="kw">implements</span> QueueSet&lt;T&gt; {
  <span class="co">// methods required by QueueSet, i.e. Queue and Set</span>
}</code></pre>
<p>The problem here is that any other class that implements <code>Queue&lt;T&gt;</code> and <code>Set&lt;T&gt;</code>, but doesn’t implement <code>QueueSet&lt;T&gt;</code>, won’t satisfy the type signature of <code>foo</code>. It’s a shame that we had to create a wrapper interface just for this. It would have been better to be able to specify inside <code>foo</code>, that the <code>queueSet</code> parameter is expected to be an instance of an object that implements both <code>Queue&lt;T&gt;</code> and <code>Set&lt;T&gt;</code>, without any additional wrapper interface. Something like this:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> &lt;T&gt; <span class="dt">void</span> <span class="fu">foo</span>(Queue&lt;T&gt; and Set&lt;T&gt; queueSet) {}</code></pre>
<p>The idea came to me from Haskell’s typeclasses, which allow a notation similar to the one above when you want to enforce a particular type variable to be an instance of multiple typeclasses.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell"><span class="ot">foo ::</span> (<span class="kw">Ord</span> a, <span class="kw">Show</span> a) <span class="ot">-&gt;</span> [a] <span class="ot">-&gt;</span> [a]
foo list <span class="fu">=</span> <span class="co">-- implementation</span></code></pre>
<p>So, my first thought was that Java does not permit this level of abstraction, but I was wrong. A couple of days ago, while playing with some generics, I rediscovered that Java’s generics allow multiple bounded type parameters. So, the generic version of <code>foo</code> that satisfies our needs would be this:</p>
<pre class="sourceCode java"><code class="sourceCode java"><span class="kw">public</span> &lt;T, QS <span class="kw">extends</span> Queue&lt;T&gt; &amp; Set&lt;T&gt;&gt; <span class="dt">void</span> <span class="fu">foo</span>(QS queueSet) {}</code></pre>
<p>My wishful thinking about <code>Queue&lt;T&gt; and Set&lt;T&gt;</code> transformed into <code>QS extends Queue&lt;T&gt; &amp; Set&lt;T&gt;</code>. You can rename <code>QS</code> to whatever you want. I chose a two letter type variable as a means to convey that it uses multiple type bounds, i.e., both <code>Queue&lt;T&gt;</code> and <code>Set&lt;T&gt;</code>.</p>
<p>Regarding the syntax. Well, yes, I agree it is unnecessarily verbose, but at least it’s possible. Although, on a second thought, the real problem is that the type declarations are interleaved with the method name and the formal parameter names. Haskell code seems more legible, to me at least, just because it separates the function signature from its implementation.</p>
<h2 id="references">References</h2>
<ul>
<li>Gilad Bracha’s <a href="http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf">Generics in the Java Programming Language</a></li>
<li><a href="http://download.oracle.com/javase/tutorial/java/generics/bounded.html">Bounded Type Parameters</a></li>
</ul>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Sat, 09 Jul 2011 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2011-07-09-composing-java-interfaces-using-generics.html</guid>
</item>
<item>
    <title>On Life and Evolution</title>
    <link>http://igstan.ro/posts/2011-06-28-on-life-and-evolution.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>On Life and Evolution</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>On Life and Evolution</h1>
    <time pubdate>June 28, 2011</time>
    <div class="warning">
Warning! Serious brain dump ahead!
</div>

<p>So, I know this guy on Twitter (<a href="https://twitter.com/missingfaktor">@missingfaktor</a>, you should follow him), who frequently tweets or re-tweets about religion, atheism, or evolution, and just like in Inception a little idea got inside my head.</p>
<p>I don’t really see the world in black and white, and this is true for the evolutionism and creationism stuff too, although I tend to believe more in evolution than in creation (I don’t see human beings popping out of nowhere on Earth). However… who created evolution? Or, did the evolution, more precisely, the rules for evolution were created or evolved or something? And who planted the initial seed? Is it really necessary that there is some entity out there to create the initial seed? Do we need time?</p>
<p>Now, all these questions above got mixed this morning with some other idea. We have computers, and we can actually model and create worlds inside them. So, what would be the minimum rules necessary to create that would allow evolution and would actually create some intelligent life-form inside our program given a considerable amount of time? Would it even be possible? Conway did his research with his <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Game of Life</a>, and some people (forgot where I read this) wondered how many game generations are needed for a given initial generation in order to reach some sort of life form.</p>
<p>So, these are the initial two questions.</p>
<ul>
<li>is it even possible to devise a world with built-in evolution mechanism which given enough time will produce self-conscious intelligence?</li>
<li>how hard would that be? I mean, how complex could the initial rules be?</li>
</ul>
<p>I’ll assume the answers are that it is possible and not actually very hard, otherwise I’d stop here. So, let’s imagine we’re in front of our artificial, evolving, world were we try to model evolution and see where it ends up.</p>
<p>The big problem now I believe is to spot intelligence. I assume the program we devised is just let to run and we don’t actually attempt to intervene in it. Will we be able to spot intelligence? It doesn’t have to look like what we see among us. It doesn’t have to generate multiple, self-conscious, life forms. One would suffice.</p>
<p>Let’s assume though that we’re able to recognize it. Let’s say we’ve built some visual interface to this world that would allow some sort of representation of it (although I don’t think it should necessarily represent something true to what it is actually). Here’s the thing now. We would be some lousy gods because we depend on time, and our tools depend on that, and the world we devised probably has some form of time in it. The time is generated by the CPU. I assume this world runs entirely in the memory of the computer (no persistence for the moment), and that the amount of memory is infinite. However, the CPU speed does not necessarily have limits, but it is variable. Imagine those creatures inside that world, they would be so constrained to the world they live in that, no matter the CPU speed, for them time will always have the same speed, or… it would be just time. Because, without time they would not exist, and every thought of them would be a certain amount of CPU instructions. So, it doesn’t matter how many instructions per unit of time the CPU executes. All it matters is that they get executed. Do they have any chance to get a feel for this? Is there any chance for them to plan some experiments that will show them that time actually has speed and that it varies? I don’t see one, unless we design the initial world that way.</p>
<p>It would be quite funny to watch those little guys banging their heads against the wall trying to understand their world. With some of them believing in creationism, some others in evolutionism.</p>
<p>Here’s another question. Now that you know your computer holds a world of intelligent life forms, would you unplug the power cable? How would you feel yourself after deliberately obliterating an entire universe?</p>
<p>To me, that seems to be the problem with evolution. Is it necessary that someone lay out the initial rules of evolution, or not?</p>
<p>We, as intelligent entities, cannot really imagine a universe without time. We can imagine ourselves existing in a world without dimensions (see <a href="http://www.amazon.com/Shadows-John-Saul/dp/0553560271/">Shadows</a>), but not a world without time. So, my opinion is that it either has to be some sort of superior entity that lives outside time, or maybe time is just another dimension of the world we live in and it’s just our perception about it that makes us unable to imagine a world without time, but the world can exist just fine all by itself, for ever, since ever (so to say).</p>
<p>How would a world without verbs look like? Because verbs denote time. You wouldn’t “exist” because that’s a verb and it implies time.</p>
<p>What does life actually mean? Would we perceive what we created as life if we know they actually follow some basic rules of evolution? How can order be created out of chaos? Have we actually created life until now and didn’t actually realize it?</p>
<p>Another interesting part is that the universe we created it’s not material. The substrate they would exist on would be material, but that’s our material, our electrons (quarks, strings, whatever), not theirs. Maybe they would perceive their world as material, but that depends entirely on the initial world we create.</p>
<p>The irony is that… oh, well, the chaos that exists in our world would create their world too. So, abstraction will leak, but they probably won’t be able to sense it. Or, if maybe they’ll be able to obtain some buffer overflows, and then some weird things could happen in their world, and as such maybe they will ultimately be able to create some model of their world, i.e. our computer.</p>
<p>How would this experiment makes us able to understand the world we live in? After all, the world we would create would be based on the world we live in. Maybe we can sense some stuff by means of this experiment. Here’s a little analogy for this.</p>
<p>I find it pretty hard to imagine a world with four dimensions, but I can attempt to understand this if I imagine how two 1-dimensional worlds intersect themselves to form a point. Then, two 2-dimensional worlds intersect themselves and form a 1-dimensional world, a line. Finally, two 3-dimensional worlds intersect themselves to form a 2-dimensional world, a plane. However, note that for each intersection you actually need a superior dimension. To intersect two 2-dimensional worlds, that forms a 1-dimensional world, you need a 3-dimensional world, otherwise the intersection of two planes would be the same plane.</p>
<p>Maybe, trying to create this world inside our world will actually help us understand the world we live in. Maybe…</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Tue, 28 Jun 2011 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2011-06-28-on-life-and-evolution.html</guid>
</item>
<item>
    <title>Clojure Impressions</title>
    <link>http://igstan.ro/posts/2011-05-09-clojure-impressions.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Clojure Impressions</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Clojure Impressions</h1>
    <time pubdate>May 09, 2011</time>
    <p>Following some unintentional peer pressure on Twitter, with people acclaiming the recently published book “Joy of Clojure”, and some others showing their solutions to the Clojure problems on <a href="http://4clojure.com">4clojure.com</a>, I finally decided to try this language a bit. I’ve refrained myself from doing so for almost a year and a half. The main reason was that it didn’t seem to be as elegant as Scheme. There’s something about the look of Clojure programs that reminds me of dirt. I can’t really put my finger on it, but that’s what I feel sometimes. A second reason was the JVM. Just as with many other people, for some time I thought JVM and Java are the same thing. Now I don’t, but I still dislike the time it takes JVM to start up.</p>
<p>The way I approached Clojure was by trying to solve the problems on <a href="http://4clojure.com">4clojure.com</a>. I didn’t read any tutorial beforehand though. I’m familiar with Scheme, and lately I’ve been writing some Haskell code too. So, both the basics of the syntax and the paradigm (functional programming with laziness) were there. However, throughout the whole exercise I made good use of the reference on <a href="http://clojuredocs.org">clojuredocs.org</a>.</p>
<p>Below I’d like to capture my current impression about this language, while it’s still fresh in my mind.</p>
<h2 id="syntax">Syntax</h2>
<p>I like the syntax. Well, not all of it, but the basic syntax because it’s Lisp. And, it may seem strange, but sometimes I kind of wish Clojure made use of more (round) parentheses. I don’t particularly like the square brackets of <code>let</code> or the <code>:else</code> keyword of <code>cond</code>, but I got used to the square brackets of <code>defn</code>. The syntax for calling into Java is also kind of weird.</p>
<h2 id="strings-and-characters">Strings and Characters</h2>
<p>This was my first WTF with Clojure. Mainly because now I expect every respectable programming language to treat strings the way Haskell does, i.e. as a list of characters. I quickly found out that strings in Clojure are… Java strings. Well, to be honest, I don’t fucking care what language they used to implement Clojure. And the fact that they let this thing leak through didn’t look good to me. This is actually a bigger problem with Clojure. It leaks implementation details in multiple places. If you want to manipulate strings or characters, you have to resort to the Java API for strings and characters. If you’ve got an exception in your program, well… you have to wade through the guts of the Clojure’s internals stack trace in order to find the line number you’re interested in. And that’s when that number exists, because sometimes it’s just 0.</p>
<p>I know that strings are actually transformed to sequences in most of the core functions, but you still have to jump some hoops. Here’s what I mean. Let’s upper-case a string, shall we? The obvious answer would be:</p>
<pre class="terminal">user=> (.toUpperCase "foo")
"FOO"
</pre>

<p>And it could be fine, but… ah, why do I have to call a Java method?</p>
<p>Now, let’s pretend I don’t know there’s a <code>.toUpperCase</code> method on <code>String</code>, but I know there’s one such static method on the <code>Character</code> class.</p>
<pre class="terminal">user=> (map Character/toUpperCase "foo")
java.lang.Exception: Unable to find static field: toUpperCase in class ...
</pre>

<p>Oh, Java methods aren’t really first class functions. We’re talking about Java so we shouldn’t be surprised. Next try.</p>
<pre class="terminal">user=> (map #(Character/toUpperCase %) "foo")
(\F \O \O)
</pre>

<p>Huh? Where’s my string? Next try.</p>
<pre class="terminal">user=> (str (map #(Character/toUpperCase %) "foo"))
"clojure.lang.LazySeq@18505"
</pre>

<p>Lazy? Why? Next try.</p>
<pre class="terminal">user=> (apply str (map #(Character/toUpperCase %) "foo"))
"FOO"
</pre>

<p>That’s better, but too much for something that could just as well be:</p>
<pre class="terminal">user=> (map upper-case "foo")
"FOO"
</pre>

<p>So, in short, I don’t like that strings and characters are not citizens of Clojure, but rather visitors from the land of Java.</p>
<h2 id="documentation">Documentation</h2>
<p>Every function in Clojure’s core is documented. It uses the same convention that Python uses. A multiline string at the beginning of the function represents the documentation. Not unexpectedly, there’s a <code>doc</code> function available inside the REPL that takes a function value (not function name) and returns its docs. Pretty much like Python’s <code>help</code> function. However there’s more in Clojure. You have access to every core function’s source code by calling the <code>source</code> function. This is hugely useful because, as we all know, docs aren’t perfect, so it helps to sometimes take a look at the source of the function and try to understand what that docstring is actually trying to say. There’s also <code>find-doc</code> and <code>javadoc</code>. I really like this part of Clojure.</p>
<h2 id="standard-library">Standard Library</h2>
<p>There’s a plethora of functions in clojure.core. Most of them being there to support the ubiquitous sequences of Clojure. If you’re used to Haskell, it may look like there’s something in Haskell and not in Clojure. It may be true, but you should first ask around because it might be there under a different name. For example I found myself wanting a <code>zipWith</code> function:</p>
<pre class="terminal">Prelude> zipWith (+) [1,2,3] [4,5,6]
[5,7,9]
</pre>

<p>I couldn’t find it in the beginning. Later on I discovered that Clojure’s <code>map</code> function actually maps over multiple collections. So there it was, my <code>zipWith</code> function in disguise.</p>
<pre class="terminal">user=> (map + [1 2 3] [4 5 6])
(5 7 9)
</pre>

<p>Actually, it’s more than <code>zipWith</code>, because Clojure is dynamic and takes an infinite number of collections to iterate over, while <code>zipWith</code> takes just two. You’d need <code>zipWith3</code> for three collections, <code>zipWith4</code> for four collections, and so on up to seven. Also, the equivalent for Haskell’s <code>zip</code> is <code>zipmap</code>.</p>
<h2 id="polymorphism-of-conj">Polymorphism of <code>conj</code></h2>
<p>I don’t think I have yet started to love this. <code>conj</code> seems too polymorphic for my taste. It may either prepend an element if the collection is a list, or append it, if the collection is a vector. Not to mention it also works on maps and sets.</p>
<p>I did’t like <code>conj</code> especially when I had to work with functions generating lazy sequences. Whenever I saw <code>conj</code> I had to read carefully to see what kind of collection that <code>conj</code> acts on. Most of the time they’re lists, but sometimes it’s a vector and you end up with a reversed list without knowing why.</p>
<p><code>conj</code> is useful, but I think it should be used with care.</p>
<h2 id="laziness">Laziness</h2>
<p>It was a nice pleasure to see Clojure having support for laziness. There are plenty of algorithms on sequences that are easier to implement when you have lazy sequences.</p>
<p>In Clojure, laziness is something you opt in when you’re writing your function by constructing sequences with <code>lazy-seq</code>. However, because there are so many built-in functions that return lazy sequences most of the time you won’t feel a difference compared to Haskell.</p>
<h2 id="pattern-matching">Pattern Matching</h2>
<p>Another nice surprise. I didn’t use it too much because I’m not used to pattern matching in a Lisp, but it’s powerful and can make the code both more concise and readable.</p>
<h2 id="tail-call-recursion">Tail-Call Recursion</h2>
<p>Just as with laziness, you have to explicitly opt-in for tail-call recursion. It’s the same thing as in any other language that supports tail-calls, you have to make sure that the recursive call is the last thing that your function does. However, in Clojure, you have to use the <code>recur</code> special form instead of the function name. That signals the Clojure compiler that you want tail-call recursion.</p>
<pre class="sourceCode clojure"><code class="sourceCode clojure">(<span class="kw">defn</span><span class="fu"> gcd </span>[a b]
  <span class="st">&quot;Calculates greatest common divisor using Euclid&#39;s algorithm.&quot;</span>
  (<span class="kw">if</span> (zero? b) a
      <span class="co">;; uses `recur` instead of `gcd`</span>
      (<span class="kw">recur</span> b (<span class="kw">mod</span> a b))))</code></pre>
<h2 id="java-interoperability">Java Interoperability</h2>
<p>This one is what made Clojure popular. And it appeals to me too, even if I’m not a Java person. In the past I had to use some Java libraries, like Apache POI for processing Excel files, and back then I scripted them using JavaScript (with Mozilla Rhino). Nowadays, if I were to solve the same problem, I’d probably choose Clojure. Once you hide the Java ugliness behind a sane, Lisp-like, API, things are much better.</p>
<p>But this is something that I also fear. It may happen that some of the monstrosity of Java libraries will percolate through all these layers of abstraction until it hits Clojure. I don’t know, maybe it won’t happen, but I still think it would be a pity.</p>
<h2 id="seq-vs-sequential"><code>seq?</code> vs <code>sequential?</code></h2>
<p>This is something I haven’t yet understand despite my attempts. I have googled the topic and even looked inside the Clojure source code. The two are still foggy subjects in my mind. Mainly because of those leaks I was talking above. For example the docs for <code>sequential?</code> read:</p>
<blockquote>
<p>Returns true if coll implements Sequential</p>
</blockquote>
<p>Ok, and what exactly that means? I took a look at the Sequential interface, and to my surprise it was used as a marker interface, i.e. it specifies no methods. It is used in several places with <code>instanceof</code> checks. Until now, it seems that <code>sequential?</code> will tell you if the order of the elements in a collection matters. For example it returns <code>true</code> for both lists and vector, but not for maps and sets.</p>
<p>The docs for <code>seq?</code> read:</p>
<blockquote>
<p>Return true if x implements ISeq</p>
</blockquote>
<p>Please, not Java interfaces again… Fortunately this time <code>ISeq</code> is not a marker interface, but I shouldn’t have to read the internals of Clojure to figure out what this function does. Anyway, this function answers whether the passed argument is a data structure that supports three main operations on it:</p>
<ul>
<li>first</li>
<li>rest</li>
<li>cons</li>
</ul>
<h2 id="gotchas">Gotchas</h2>
<p>Just one for the moment. <code>contains?</code> works on keys not on values, but beware, sets are like a collection of keys, so:</p>
<pre class="terminal">user=> (contains?  [1 2 3] 3)
false
user=> (contains? #{1 2 3} 3)
true
</pre>


<h2 id="the-end">The End</h2>
<p>These are my first impressions with Clojure. I had a great time solving those problems on <a href="http://4clojure.com">4clojure.com</a> and I think you’ll enjoy them too. Thus far I like Clojure.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Mon, 09 May 2011 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2011-05-09-clojure-impressions.html</guid>
</item>
<item>
    <title>Understanding Monads With JavaScript</title>
    <link>http://igstan.ro/posts/2011-05-02-understanding-monads-with-javascript.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Understanding Monads With JavaScript</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Understanding Monads With JavaScript</h1>
    <time pubdate>May 02, 2011</time>
    <h2 id="update">Update</h2>
<p>Nice people have translated this article into <a href="http://imasters.com.br/linguagens/javascript/compreendendo-monads-com-javascript/">Portuguese</a> and <a href="http://habrahabr.ru/post/238171/">Russian</a>.</p>
<hr />
<p>For the past weeks I’ve been working hard studying monads. I’m still learning Haskell, and to be honest I thought I knew what monads are all about, but when I wanted to write a little Haskell library, just to sharpen up my skills, I realized that while I understood the way monadic <code>bind</code> (<code>&gt;&gt;=</code>) and <code>return</code> work, I had no understanding of where that state comes from. So, most likely I had no understanding at all. As a result of this I thought I rediscover monads myself using JavaScript. The plan was basically the same as that used when I derived the <a href="/posts/2010-12-01-deriving-the-y-combinator-in-7-easy-steps.html">Y Combinator</a>: start from the initial problem (dealing with explicit immutable state in this case), and work my way up to the solution by applying simple code transformations.</p>
<p>Also, I chose JavaScript because it forces you to write some code that Haskell readily hides for you thanks to its terse syntax or different semantics (lambda expressions, operators, and built-in function currying). Lastly, I learn best by comparison, which is why I tried it in CoffeeScript and Scheme too. Here are the GitHub gists for the latter two:</p>
<ul>
<li>CoffeeScript: <a href="https://gist.github.com/936519">https://gist.github.com/936519</a></li>
<li>Scheme: <a href="https://gist.github.com/936695">https://gist.github.com/936695</a></li>
</ul>
<h2 id="constraints">Constraints</h2>
<p>In this article I’ll limit my problem to the state monad. Understanding the state monad is good enough to have an idea what monads are all about. So here are the solution constraints.</p>
<ul>
<li><strong>no mutable state</strong><br /> Haskell makes use of the state monad because it does not allow mutable state.</li>
<li><strong>no explicit state</strong><br /> When you don’t have mutable state, you have to thread residual state around. Typing and reading all those intermediate states is not pleasant. Monads try to hide all this plumbing. You’ll see what I mean in a moment.</li>
<li><strong>no code duplication</strong><br /> This goes hand in hand with the previous point, but I still put it here because in my experience removal of code duplication is a powerful tool to explore new grounds.</li>
</ul>
<h2 id="too-long-wont-read">Too Long; Won’t Read</h2>
<p>This article is a pretty dense one, so I thought I should add some additional material to it. That’s why I recorded a little video with all the steps that are described below. It’s sort of a <abbr title="Too Long; Didn't Read">tl;dr</abbr> version, and it should help visualize the transitions more easily, but most likely the video won’t make too much sense if you won’t read the whole article.</p>
<p>I advise you watch it <a href="http://vimeo.com/23125621">directly on Vimeo</a>, where it’s available in HD.</p>
<div style="text-align:center; margin-bottom:30px;">
  <iframe src="http://player.vimeo.com/video/23125621?title=0&amp;byline=0&amp;portrait=0" width="650" height="406" frameborder="0"></iframe>
</div>



<h2 id="derivation-vehicle">Derivation Vehicle</h2>
<p>I’ll use a stack as my derivation vehicle because it’s an easy to understand data structure, and its usual implementation is done using mutable state. First, here’s how you’d normally use a stack in JavaScript.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> stack = [];

<span class="kw">stack</span>.<span class="fu">push</span>(<span class="dv">4</span>);
<span class="kw">stack</span>.<span class="fu">push</span>(<span class="dv">5</span>);
<span class="kw">stack</span>.<span class="fu">pop</span>(); <span class="co">// 5</span>
<span class="kw">stack</span>.<span class="fu">pop</span>(); <span class="co">// 4</span></code></pre>
<p>JavaScript array objects have the usual methods one would expect from a stack, <code>push</code> and <code>pop</code>. What I don’t like about it is that it mutates state. Well, I don’t it like for the sake of this article, at least.</p>
<p>Each step I’ll describe is a working step. Just open your browser’s console and reload this page. You should see several console groups with the string <code>5 : 4</code> logged inside. However, in the body of the article I’ll only present those parts that differ from the previous steps.</p>
<h2 id="a-stack-with-explicit-handling-of-state">A Stack With Explicit Handling of State</h2>
<p>The obvious solution to avoid mutable state is to construct a new state container every time we need mutation. Here’s how it can look like in JavaScript (note that <code>concat</code> and <code>slice</code> are two <code>Array</code> methods that do not mutate the object they’re called on, instead they create new <code>Array</code> objects):</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> push = <span class="kw">function</span> (element, stack) {
  <span class="kw">var</span> newStack = [element].<span class="fu">concat</span>(stack);

  <span class="kw">return</span> newStack;
};

<span class="kw">var</span> pop = <span class="kw">function</span> (stack) {
  <span class="kw">var</span> value = stack[<span class="dv">0</span>];
  <span class="kw">var</span> newStack = <span class="kw">stack</span>.<span class="fu">slice</span>(<span class="dv">1</span>);

  <span class="kw">return</span> { <span class="dt">value</span>: value, <span class="dt">stack</span>: newStack };
};

<span class="kw">var</span> stack0 = [];

<span class="kw">var</span> stack1 = push(<span class="dv">4</span>, stack0);
<span class="kw">var</span> stack2 = push(<span class="dv">5</span>, stack1);
<span class="kw">var</span> result0 = pop(stack2);        <span class="co">// {value: 5, stack: [4]}</span>
<span class="kw">var</span> result1 = pop(<span class="kw">result0</span>.<span class="fu">stack</span>); <span class="co">// {value: 4, stack: []}</span></code></pre>
<p>As you can see, both <code>push</code> and <code>pop</code> return a residual stack, the resulted state. <code>pop</code> additionally returns the popped value. Each subsequent stack operation uses the previous stack, but this may not be easily observable because of differences in representation of return values. However, code duplication can be emphasized by normalizing return values. We’ll have <code>push</code> return a dummy <code>undefined</code> value.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> push = <span class="kw">function</span> (element, stack) {
  <span class="kw">var</span> value = undefined;
  <span class="kw">var</span> newStack = [element].<span class="fu">concat</span>(stack);

  <span class="kw">return</span> { <span class="dt">value</span>: value, <span class="dt">stack</span>: newStack };
};

<span class="kw">var</span> pop = <span class="kw">function</span> (stack) {
  <span class="kw">var</span> value = stack[<span class="dv">0</span>];
  <span class="kw">var</span> newStack = <span class="kw">stack</span>.<span class="fu">slice</span>(<span class="dv">1</span>);

  <span class="kw">return</span> { <span class="dt">value</span>: value, <span class="dt">stack</span>: newStack };
};

<span class="kw">var</span> stack0 = [];

<span class="kw">var</span> result0 = push(<span class="dv">4</span>, stack0);
<span class="kw">var</span> result1 = push(<span class="dv">5</span>, <span class="kw">result0</span>.<span class="fu">stack</span>);
<span class="kw">var</span> result2 = pop(<span class="kw">result1</span>.<span class="fu">stack</span>); <span class="co">// {value: 5, stack: [4]}</span>
<span class="kw">var</span> result3 = pop(<span class="kw">result2</span>.<span class="fu">stack</span>); <span class="co">// {value: 4, stack: []}</span></code></pre>
<p>That’s the kind of duplication I was talking earlier. Duplication that also means explicit handling of state.</p>
<script>
(function () {
  var push = function (element, stack) {
    var value = undefined;
    var newStack = [element].concat(stack);

    return { value: value, stack: newStack };
  };

  var pop = function (stack) {
    var value = stack[0];
    var newStack = stack.slice(1);

    return { value: value, stack: newStack };
  };

  var stack0 = [];

  var result0 = push(4, stack0);
  var result1 = push(5, result0.stack);
  var result2 = pop(result1.stack);
  var result3 = pop(result2.stack);

  console.group("Step 1: stack with explicit handling of state");
  console.log(result2.value + " : " + result3.value);
  console.groupEnd();
})();
</script>



<h2 id="transforming-to-continuation-passing-style">Transforming to Continuation-Passing Style</h2>
<p>Now, I’ll replace those intermediate result variables with functions and parameters. I want this because I find it easier to abstract over functions and parameters than over simple variables. To do this, I’ll create a small helper function, called <code>bind</code>, which does nothing more than just apply a continuation callback to the stack operation result. In other works, it <em>binds</em> a continuation to a stack operation.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> bind = <span class="kw">function</span> (value, continuation) {
  <span class="kw">return</span> continuation(value);
};

<span class="kw">var</span> stack0 = [];

<span class="kw">var</span> finalResult = bind(push(<span class="dv">4</span>, stack0), <span class="kw">function</span> (result0) {
  <span class="kw">return</span> bind(push(<span class="dv">5</span>, <span class="kw">result0</span>.<span class="fu">stack</span>), <span class="kw">function</span> (result1) {
    <span class="kw">return</span> bind(pop(<span class="kw">result1</span>.<span class="fu">stack</span>), <span class="kw">function</span> (result2) {
      <span class="kw">return</span> bind(pop(<span class="kw">result2</span>.<span class="fu">stack</span>), <span class="kw">function</span> (result3) {
        <span class="kw">var</span> value = <span class="kw">result2</span>.<span class="fu">value</span> + <span class="st">&quot; : &quot;</span> + <span class="kw">result3</span>.<span class="fu">value</span>;
        <span class="kw">return</span> { <span class="dt">value</span>: value, <span class="dt">stack</span>: <span class="kw">result3</span>.<span class="fu">stack</span> };
      });
    });
  });
});</code></pre>
<script>
(function () {
  var push = function (element, stack) {
    var value = undefined;
    var newStack = [element].concat(stack);

    return { value: value, stack: newStack };
  };

  var pop = function (stack) {
    var value = stack[0];
    var newStack = stack.slice(1);

    return { value: value, stack: newStack };
  };

  var bind = function (value, continuation) {
    return continuation(value);
  };

  var stack0 = [];

  var finalResult = bind(push(4, stack0), function (result0) {
    return bind(push(5, result0.stack), function (result1) {
      return bind(pop(result1.stack), function (result2) {
        return bind(pop(result2.stack), function (result3) {
          var value = result2.value + " : " + result3.value;
          return { value: value, stack: result3.stack };
        });
      });
    });
  });

  console.group("Step 2: transforming to continuation-passing style");
  console.log(finalResult);
  console.groupEnd();
})();
</script>

<p>The return value of the whole expression, stored in <code>finalResult</code>, has the same type as the return value of a single <code>push</code> or <code>pop</code> operation. We want to have consistent interfaces.</p>
<h2 id="currying-push-and-pop">Currying <code>push</code> and <code>pop</code></h2>
<p>Next, we want to be able to detach the stack arguments from <code>push</code> and <code>pop</code>. We want this because the intention is to have <code>bind</code> thread them behind the scenes.</p>
<p>For this we’ll apply another lambda calculus trick called function currying. An alternative name could be function application procrastination.</p>
<p>Now, instead of calling <code>push(4, stack0)</code>, we’ll call <code>push(4)(stack0)</code>. In Haskell we wouldn’t even need this step, because its functions are curried by default.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> push = <span class="kw">function</span> (element) {
  <span class="kw">return</span> <span class="kw">function</span> (stack) {
    <span class="kw">var</span> value = undefined;
    <span class="kw">var</span> newStack = [element].<span class="fu">concat</span>(stack);

    <span class="kw">return</span> { <span class="dt">value</span>: value, <span class="dt">stack</span>: newStack };
  };
};

<span class="kw">var</span> pop = <span class="kw">function</span> () {
  <span class="kw">return</span> <span class="kw">function</span> (stack) {
    <span class="kw">var</span> value = stack[<span class="dv">0</span>];
    <span class="kw">var</span> newStack = <span class="kw">stack</span>.<span class="fu">slice</span>(<span class="dv">1</span>);

    <span class="kw">return</span> { <span class="dt">value</span>: value, <span class="dt">stack</span>: newStack };
  };
};

<span class="kw">var</span> stack0 = [];

<span class="kw">var</span> finalResult = bind(push(<span class="dv">4</span>)(stack0), <span class="kw">function</span> (result0) {
  <span class="kw">return</span> bind(push(<span class="dv">5</span>)(<span class="kw">result0</span>.<span class="fu">stack</span>), <span class="kw">function</span> (result1) {
    <span class="kw">return</span> bind(pop()(<span class="kw">result1</span>.<span class="fu">stack</span>), <span class="kw">function</span> (result2) {
      <span class="kw">return</span> bind(pop()(<span class="kw">result2</span>.<span class="fu">stack</span>), <span class="kw">function</span> (result3) {
        <span class="kw">var</span> value = <span class="kw">result2</span>.<span class="fu">value</span> + <span class="st">&quot; : &quot;</span> + <span class="kw">result3</span>.<span class="fu">value</span>;
        <span class="kw">return</span> { <span class="dt">value</span>: value, <span class="dt">stack</span>: <span class="kw">result3</span>.<span class="fu">stack</span> };
      });
    });
  });
});</code></pre>
<script>
(function () {
  var push = function (element) {
    return function (stack) {
      var value = undefined;
      var newStack = [element].concat(stack);

      return { value: value, stack: newStack };
    };
  };

  var pop = function () {
    return function (stack) {
      var value = stack[0];
      var newStack = stack.slice(1);

      return { value: value, stack: newStack };
    };
  };

  var bind = function (value, continuation) {
    return continuation(value);
  };

  var stack0 = [];

  var finalResult = bind(push(4)(stack0), function (result0) {
    return bind(push(5)(result0.stack), function (result1) {
      return bind(pop()(result1.stack), function (result2) {
        return bind(pop()(result2.stack), function (result3) {
          var value = result2.value + " : " + result3.value;
          return { value: value, stack: result3.stack };
        });
      });
    });
  });

  console.group("Step 3: currying `push` and `pop`");
  console.log(finalResult);
  console.groupEnd();
})();
</script>



<h2 id="preparing-bind-to-handle-intermediate-stacks">Preparing <code>bind</code> to Handle Intermediate Stacks</h2>
<p>As I said in the previous section, I’d like <code>bind</code> to handle the passing of the explicit stack arguments. First, let’s have <code>bind</code> accept a stack as its last parameter, but in a curried way, i.e. <code>bind</code> now returns a function which takes a stack. Also, <code>push</code> and <code>pop</code> are now partially applied, i.e. we longer pass them the stack manually. <code>bind</code> will handle this instead.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> bind = <span class="kw">function</span> (stackOperation, continuation) {
  <span class="kw">return</span> <span class="kw">function</span> (stack) {
    <span class="kw">return</span> continuation(stackOperation(stack));
  };
};

<span class="kw">var</span> stack0 = [];

<span class="kw">var</span> finalResult = bind(push(<span class="dv">4</span>), <span class="kw">function</span> (result0) {
  <span class="kw">return</span> bind(push(<span class="dv">5</span>), <span class="kw">function</span> (result1) {
    <span class="kw">return</span> bind(pop(), <span class="kw">function</span> (result2) {
      <span class="kw">return</span> bind(pop(), <span class="kw">function</span> (result3) {
        <span class="kw">var</span> value = <span class="kw">result2</span>.<span class="fu">value</span> + <span class="st">&quot; : &quot;</span> + <span class="kw">result3</span>.<span class="fu">value</span>;
        <span class="kw">return</span> { <span class="dt">value</span>: value, <span class="dt">stack</span>: <span class="kw">result3</span>.<span class="fu">stack</span> };
      })(<span class="kw">result2</span>.<span class="fu">stack</span>);
    })(<span class="kw">result1</span>.<span class="fu">stack</span>);
  })(<span class="kw">result0</span>.<span class="fu">stack</span>);
})(stack0);</code></pre>
<script>
(function () {
  var push = function (element) {
    return function (stack) {
      var value = undefined;
      var newStack = [element].concat(stack);

      return { value: value, stack: newStack };
    };
  };

  var pop = function () {
    return function (stack) {
      var value = stack[0];
      var newStack = stack.slice(1);

      return { value: value, stack: newStack };
    };
  };

  var bind = function (stackOperation, continuation) {
    return function (stack) {
      return continuation(stackOperation(stack));
    };
  };

  var stack0 = [];

  var finalResult = bind(push(4), function (result0) {
    return bind(push(5), function (result1) {
      return bind(pop(), function (result2) {
        return bind(pop(), function (result3) {
          var value = result2.value + " : " + result3.value;
          return { value: value, stack: result3.stack };
        })(result2.stack);
      })(result1.stack);
    })(result0.stack);
  })(stack0);

  console.group("Step 4: preparing `bind` to handle the intermediary stacks");
  console.log(finalResult);
  console.groupEnd();
})();
</script>



<h2 id="removing-trailing-stacks">Removing Trailing Stacks</h2>
<p>We’re now able to hide the intermediary stacks by modifying <code>bind</code> to inspect the return value of a <code>stackOperation</code>, extract the stack and use it as an argument to the return value of the continuation callback, which must be a function that receives a stack. That’s why we also have to wrap the final result (<code>return result2.value + &quot; : &quot; + result3.value</code>) inside an anonymous function that will receive a stack.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> bind = <span class="kw">function</span> (stackOperation, continuation) {
  <span class="kw">return</span> <span class="kw">function</span> (stack) {
    <span class="kw">var</span> result = stackOperation(stack);
    <span class="kw">var</span> newStack = <span class="kw">result</span>.<span class="fu">stack</span>;
    <span class="kw">return</span> continuation(result)(newStack);
  };
};

<span class="kw">var</span> computation = bind(push(<span class="dv">4</span>), <span class="kw">function</span> (result0) {
  <span class="kw">return</span> bind(push(<span class="dv">5</span>), <span class="kw">function</span> (result1) {
    <span class="kw">return</span> bind(pop(), <span class="kw">function</span> (result2) {
      <span class="kw">return</span> bind(pop(), <span class="kw">function</span> (result3) {
        <span class="kw">var</span> value = <span class="kw">result2</span>.<span class="fu">value</span> + <span class="st">&quot; : &quot;</span> + <span class="kw">result3</span>.<span class="fu">value</span>;

        <span class="co">// We need this anonymous function because we changed the protocol</span>
        <span class="co">// of the continuation. Now, each continuation must return a</span>
        <span class="co">// function which accepts a stack.</span>
        <span class="kw">return</span> <span class="kw">function</span> (stack) {
          <span class="kw">return</span> { <span class="dt">value</span>: value, <span class="dt">stack</span>: stack };
        };
      });
    });
  });
});

<span class="kw">var</span> stack0 = [];
<span class="kw">var</span> finalResult = computation(stack0);</code></pre>
<script>
(function () {
  var push = function (element) {
    return function (stack) {
      var value = undefined;
      var newStack = [element].concat(stack);

      return { value: value, stack: newStack };
    };
  };

  var pop = function () {
    return function (stack) {
      var value = stack[0];
      var newStack = stack.slice(1);

      return { value: value, stack: newStack };
    };
  };

  var bind = function (stackOperation, continuation) {
    return function (stack) {
      var result = stackOperation(stack);
      var newStack = result.stack;
      return continuation(result)(newStack);
    };
  };

  var computation = bind(push(4), function (result0) {
    return bind(push(5), function (result1) {
      return bind(pop(), function (result2) {
        return bind(pop(), function (result3) {
          var value = result2.value + " : " + result3.value;

          // We need this anonymous function because we changed the protocol
          // of the continuation. Now, each continuation must return a
          // function which accepts a stack.
          return function (stack) {
            return { value: value, stack: stack };
          };
        });
      });
    });
  });

  var stack0 = [];
  var finalResult = computation(stack0);

  console.group("Step 5: remove trailing stacks");
  console.log(finalResult);
  console.groupEnd();
})();
</script>


<h2 id="hiding-the-final-residual-stack">Hiding the Final Residual Stack</h2>
<p>In the previous step, we hid away several intermediate stacks, but exposed a new one in the function that wraps the final result value. We can hide this trace of a stack by writing another helper function that I’ll call <code>result</code>. Additionally, this will also hide the internal representation of the state we’re keeping, i.e. a struct with two fields, <code>value</code> and <code>stack</code>.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> result = <span class="kw">function</span> (value) {
  <span class="kw">return</span> <span class="kw">function</span> (stack) {
    <span class="kw">return</span> { <span class="dt">value</span>: value, <span class="dt">stack</span>: stack };
  };
};

<span class="kw">var</span> computation = bind(push(<span class="dv">4</span>), <span class="kw">function</span> (result0) {
  <span class="kw">return</span> bind(push(<span class="dv">5</span>), <span class="kw">function</span> (result1) {
    <span class="kw">return</span> bind(pop(), <span class="kw">function</span> (result2) {
      <span class="kw">return</span> bind(pop(), <span class="kw">function</span> (result3) {

        <span class="kw">return</span> result(<span class="kw">result2</span>.<span class="fu">value</span> + <span class="st">&quot; : &quot;</span> + <span class="kw">result3</span>.<span class="fu">value</span>);

      });
    });
  });
});

<span class="kw">var</span> stack0 = [];
<span class="kw">var</span> finalResult = computation(stack0);</code></pre>
<p>This is exactly what the <code>return</code> functions does in Haskell. It wraps the computation result inside a monad. In our case it wraps the result in a closure which accepts a stack. But that’s basically what the state monad is, a function that accepts its state. Another way to view <code>result</code>/<code>return</code> is like a factory function that creates a new stateful context around the value we provide it with.</p>
<script>
(function () {
  var push = function (element) {
    return function (stack) {
      var value = undefined;
      var newStack = [element].concat(stack);

      return { value: value, stack: newStack };
    };
  };

  var pop = function () {
    return function (stack) {
      var value = stack[0];
      var newStack = stack.slice(1);

      return { value: value, stack: newStack };
    };
  };

  var bind = function (stackOperation, continuation) {
    return function (stack) {
      var result = stackOperation(stack)
        return continuation(result)(result.stack);
    };
  };

  var result = function (value) {
    return function (stack) {
      return { value: value, stack: stack };
    };
  };

  var computation = bind(push(4), function (result0) {
    return bind(push(5), function (result1) {
      return bind(pop(), function (result2) {
        return bind(pop(), function (result3) {

          return result(result2.value + " : " + result3.value);

        });
      });
    });
  });

  var stack0 = [];
  var finalResult = computation(stack0);

  console.group("Step 6: hiding the final residual stack");
  console.log(finalResult);
  console.groupEnd();
})();
</script>



<h2 id="keeping-state-internal">Keeping State Internal</h2>
<p>We don’t want our continuation callbacks to have to traverse or even know about the struct returned by <code>push</code> or <code>pop</code>, which actually represents the internals of the monad. So, we’ll modify <code>bind</code> to pass just the minimum required data to the callback.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> bind = <span class="kw">function</span> (stackOperation, continuation) {
  <span class="kw">return</span> <span class="kw">function</span> (stack) {
    <span class="kw">var</span> result = stackOperation(stack);
    <span class="kw">return</span> continuation(<span class="kw">result</span>.<span class="fu">value</span>)(<span class="kw">result</span>.<span class="fu">stack</span>);
  };
};

<span class="kw">var</span> computation = bind(push(<span class="dv">4</span>), <span class="kw">function</span> () {
  <span class="kw">return</span> bind(push(<span class="dv">5</span>), <span class="kw">function</span> () {
    <span class="kw">return</span> bind(pop(), <span class="kw">function</span> (result1) {
      <span class="kw">return</span> bind(pop(), <span class="kw">function</span> (result2) {

        <span class="kw">return</span> result(result1 + <span class="st">&quot; : &quot;</span> + result2);

      });
    });
  });
});

<span class="kw">var</span> stack0 = [];
<span class="kw">var</span> finalResult = computation(stack0);</code></pre>
<script>
(function () {
  var push = function (element) {
    return function (stack) {
      var value = undefined;
      var newStack = [element].concat(stack);

      return { value: value, stack: newStack };
    };
  };

  var pop = function () {
    return function (stack) {
      var value = stack[0];
      var newStack = stack.slice(1);

      return { value: value, stack: newStack };
    };
  };

  var bind = function (stackOperation, continuation) {
    return function (stack) {
      var result = stackOperation(stack);
      return continuation(result.value)(result.stack);
    };
  };

  var result = function (value) {
    return function (stack) {
      return { value: value, stack: stack };
    };
  };

  var computation = bind(push(4), function () {
    return bind(push(5), function () {
      return bind(pop(), function (result1) {
        return bind(pop(), function (result2) {
          return result(result1 + " : " + result2);
        });
      });
    });
  });

  var stack0 = [];
  var finalResult = computation(stack0);

  console.group("Step 7: keeping state internal");
  console.log(finalResult);
  console.groupEnd();
})();
</script>


<h2 id="evaluating-the-stack-computation">Evaluating The Stack Computation</h2>
<p>Once we’re able to compose stack operations this way, we’ll also want to run these computations and do something with the result. This is generally called evaluation of the monad. In Haskell, the state monad provides three functions for evaluating the state monad: <code>runState</code>, <code>evalState</code>, and <code>execState</code>.</p>
<p>For the purpose of this article though, I’ll replace the “State” suffix with “Stack”.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">// Returns both the result and the final state.</span>
<span class="kw">var</span> runStack = <span class="kw">function</span> (stackOperation, initialStack) {
  <span class="kw">return</span> stackOperation(initialStack);
};

<span class="co">// Returns only the computed result.</span>
<span class="kw">var</span> evalStack = <span class="kw">function</span> (stackOperation, initialStack) {
  <span class="kw">return</span> stackOperation(initialStack).<span class="fu">value</span>;
};

<span class="co">// Returns only the final state.</span>
<span class="kw">var</span> execStack = <span class="kw">function</span> (stackOperation, initialStack) {
  <span class="kw">return</span> stackOperation(initialStack).<span class="fu">stack</span>;
};

<span class="kw">var</span> stack0 = [];

<span class="kw">console</span>.<span class="fu">log</span>(runStack(computation, stack0));
<span class="co">// { value=&quot;5 : 4&quot;, stack=[]}</span>

<span class="kw">console</span>.<span class="fu">log</span>(evalStack(computation, stack0));
<span class="co">// 5 : 4</span>

<span class="kw">console</span>.<span class="fu">log</span>(execStack(computation, stack0));
<span class="co">// []</span></code></pre>
<p>If all we’re interested in is the final computed value, then <code>evalStack</code> is what we need. It will trigger the whole monadic computation, drop the final resulted state and return the computed value. Using this function we can extract a value out of its monadic context.</p>
<p>If you’ve ever heard that you can’t escape a monad, then let me tell that this is true just in a small number of cases, like the IO monad for example. But that’s another story. The point is that you can get out of the state monad.</p>
<script>
(function () {
  var push = function (element) {
    return function (stack) {
      var value = undefined;
      var newStack = [element].concat(stack);

      return { value: value, stack: newStack };
    };
  };

  var pop = function () {
    return function (stack) {
      var value = stack[0];
      var newStack = stack.slice(1);

      return { value: value, stack: newStack };
    };
  };

  var bind = function (stackOperation, continuation) {
    return function (stack) {
      var result = stackOperation(stack);
      return continuation(result.value)(result.stack);
    };
  };

  var result = function (value) {
    return function (stack) {
      return { value: value, stack: stack };
    };
  };

  var runStack = function (stackOperation, initialStack) {
    return stackOperation(initialStack);
  };

  var evalStack = function (stackOperation, initialStack) {
    return stackOperation(initialStack).value;
  };

  var execStack = function (stackOperation, initialStack) {
    return stackOperation(initialStack).stack;
  };

  var computation = bind(push(4), function () {
    return bind(push(5), function () {
      return bind(pop(), function (result1) {
        return bind(pop(), function (result2) {
          return result(result1 + " : " + result2);
        });
      });
    });
  });

  var stack0 = [];

  console.group("Step 8: evaluating the stack computation");
  console.log("runState", runStack(computation, stack0));
  console.log("evalState", evalStack(computation, stack0));
  console.log("execState", execStack(computation, stack0));
  console.groupEnd();
})();
</script>



<h2 id="done">Done</h2>
<p>If you’re still with me, then let me tell you that this is how the state monad could look like in JavaScript. It probably doesn’t look that readable, compared to a similar Haskell version, but it’s the most I can get out of JavaScript today.</p>
<p>A monad is a pretty abstract concept because it specifies little about what you have to write. Mainly, it says that you need to design a function which will take some arguments (the state in the case of the state monad), and two additional functions: <code>result</code> and <code>bind</code>. The former will act as a factory for the function you just designed. The latter will be responsible for exposing just enough details about your monad to the outside world, and also perform some boring stuff like passing state around. Exposing is done by means of a continuation function that will take the value that the monad computes. Everything that is internal to the monad will be kept internal. Just like in object-oriented programming. And it’s even possible to have monadic getters/setters for the those internals.</p>
<p>Just for the record, here’s how the <code>computation</code> function would look like in Haskell.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">computation <span class="fu">=</span> <span class="kw">do</span> push <span class="dv">4</span>
                 push <span class="dv">5</span>
                 a <span class="ot">&lt;-</span> pop
                 b <span class="ot">&lt;-</span> pop
                 <span class="fu">return</span> <span class="fu">$</span> (<span class="fu">show</span> a) <span class="fu">++</span> <span class="st">&quot; : &quot;</span> <span class="fu">++</span> (<span class="fu">show</span> b)</code></pre>
<p>The main reason the Haskell version looks better is because Haskell has built-in syntactic support for monads in the form of the <code>do</code> notation. <code>do</code> notation is just sugar for the following version, which still looks better than the JavaScript one. Haskell, having support for operator definitions and terse lambda expressions allows for a more readable, in my opinion, implementation of monads.</p>
<pre class="sourceCode haskell"><code class="sourceCode haskell">computation <span class="fu">=</span> push <span class="dv">4</span> <span class="fu">&gt;&gt;=</span> \_ <span class="ot">-&gt;</span>
              push <span class="dv">5</span> <span class="fu">&gt;&gt;=</span> \_ <span class="ot">-&gt;</span>
              pop    <span class="fu">&gt;&gt;=</span> \a <span class="ot">-&gt;</span>
              pop    <span class="fu">&gt;&gt;=</span> \b <span class="ot">-&gt;</span>
              <span class="fu">return</span> <span class="fu">$</span> (<span class="fu">show</span> a) <span class="fu">++</span> <span class="st">&quot; : &quot;</span> <span class="fu">++</span> (<span class="fu">show</span> b)</code></pre>
<p>What I called <code>bind</code> in JavaScript is <code>&gt;&gt;=</code> in Haskell, and what I called <code>result</code> in JavaScript is <code>return</code> in Haskell. Yes, <code>return</code> in Haskell is a function, not a keyword. Other times, <code>return</code> is named <code>unit</code>. Brian Marick called <code>&gt;&gt;=</code> a decider in his <a href="#references">videos about monads in Clojure</a>. The patcher was of course <code>return</code>.</p>
<h2 id="some-javascript-sugar">Some JavaScript Sugar</h2>
<p>It turns out there’s a better way to do monadic computations in JavaScript using a little utility function called <code>sequence</code>. Thanks to JavaScript’s dynamic nature, <code>sequence</code> can take a variable number of arguments that represent the monadic actions it must perform in sequence, save for the final argument which is a callback that contains the computation over the result of the monadic actions. The callback is called with all the non-<code>undefined</code> results of the monadic actions.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> sequence = <span class="kw">function</span> (<span class="co">/* monadicActions..., continuation */</span>) {
  <span class="kw">var</span> args           = [].<span class="fu">slice</span>.<span class="fu">call</span>(arguments);
  <span class="kw">var</span> monadicActions = <span class="kw">args</span>.<span class="fu">slice</span>(<span class="dv">0</span>, -<span class="dv">1</span>);
  <span class="kw">var</span> continuation   = <span class="kw">args</span>.<span class="fu">slice</span>(-<span class="dv">1</span>)[<span class="dv">0</span>];

  <span class="kw">return</span> <span class="kw">function</span> (stack) {
    <span class="kw">var</span> initialState = { <span class="dt">values</span>: [], <span class="dt">stack</span>: stack };

    <span class="kw">var</span> state = <span class="kw">monadicActions</span>.<span class="fu">reduce</span>(<span class="kw">function</span> (state, action) {
      <span class="kw">var</span> result = action(<span class="kw">state</span>.<span class="fu">stack</span>);
      <span class="kw">var</span> values = <span class="kw">state.values</span>.<span class="fu">concat</span>(<span class="kw">result</span>.<span class="fu">value</span>);
      <span class="kw">var</span> stack  = <span class="kw">result</span>.<span class="fu">stack</span>;

      <span class="kw">return</span> { <span class="dt">values</span>: values, <span class="dt">stack</span>: stack };
    }, initialState);

    <span class="kw">var</span> values = <span class="kw">state.values</span>.<span class="fu">filter</span>(<span class="kw">function</span> (value) {
      <span class="kw">return</span> value !== undefined;
    });

    <span class="kw">return</span> <span class="kw">continuation</span>.<span class="fu">apply</span>(<span class="kw">this</span>, values)(<span class="kw">state</span>.<span class="fu">stack</span>);
  };
};

<span class="kw">var</span> computation = sequence(
  push(<span class="dv">4</span>), <span class="co">// &lt;- programmable commas :)</span>
  push(<span class="dv">5</span>),
  pop(),
  pop(),

  <span class="kw">function</span> (pop1, pop2) {
    <span class="kw">return</span> result(pop1 + <span class="st">&quot; : &quot;</span> + pop2);
  }
);

<span class="kw">var</span> initialStack = [];
<span class="kw">var</span> result = computation(initialStack); <span class="co">// &quot;5 : 4&quot;</span></code></pre>
<p>The authors of <a href="http://book.realworldhaskell.org/">Real World Haskell</a> compared monads to a <a href="http://book.realworldhaskell.org/read/monads.html#id642960">programmable semicolon</a>. In this case, I can say we have programmable commas, because that’s what I used when calling <code>sequence</code> to separate monadic actions.</p>
<script>
(function () {
  var push = function (element) {
    return function (stack) {
      var value = undefined;
      var newStack = [element].concat(stack);

      return { value: value, stack: newStack };
    };
  };

  var pop = function () {
    return function (stack) {
      var value = stack[0];
      var newStack = stack.slice(1);

      return { value: value, stack: newStack };
    };
  };

  var bind = function (stackAction, continuation) {
    return function (stack) {
      var result = stackAction(stack);
      return continuation(result.value)(result.stack);
    };
  };

  var result = function (value) {
    return function (stack) {
      return { value: value, stack: stack };
    };
  };

  var sequence = function (/* monadicActions..., continuation */) {
    var args           = [].slice.call(arguments);
    var monadicActions = args.slice(0, -1);
    var continuation   = args.slice(-1)[0];

    return function (stack) {
      var initialState = { values: [], stack: stack };

      var state = monadicActions.reduce(function (state, action) {
        var result = action(state.stack);
        var values = state.values.concat(result.value);
        var stack  = result.stack;

        return { values: values, stack: stack };
      }, initialState);

      var values = state.values.filter(function (value) {
        return value !== undefined;
      });

      return continuation.apply(this, values)(state.stack);
    };
  };

  var computation = sequence(
    push(4),
    push(5),
    pop(),
    pop(),

    function (pop1, pop2) {
      return result(pop1 + " : " + pop2);
    }
  );

  var initialStack = [];

  console.group("The `sequence` utility");
  console.log(computation(initialStack));
  console.groupEnd();
})();
</script>



<h2 id="monads-as-suspended-computations">Monads As Suspended Computations</h2>
<p>You’ll often see monads being called computations. In the beginning I didn’t understand why. You might say because they compute stuff, but… nobody says “monads compute something”, they actually say “monads are computations”. I finally understood (or I think I did) what that means after I finished an early draft of this article. All that chaining of monadic actions and values does not actually compute anything until you tell it to. It’s all a big chain of partially applied functions, which represent a suspended computation that will finally be triggered by calling it with the initial state. Again, here’s this snippet.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> computation = sequence(
  push(<span class="dv">4</span>),
  push(<span class="dv">5</span>),
  pop(),
  pop(),

  <span class="kw">function</span> (pop1, pop2) {
    <span class="kw">return</span> result(pop1 + <span class="st">&quot; : &quot;</span> + pop2);
  }
);</code></pre>
<p>Does it compute anything when it is evaluated? No. You have to trigger the computation with <code>runStack</code>, <code>evalStack</code>, or <code>execStack</code>.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> initialStack = [];
evalStack(computation, initialStack);</code></pre>
<p>It looks like the <code>push</code> and <code>pop</code> functions act on some global value, whereas they in fact are always awaiting for that value to come. It’s almost like in OOP where <code>this</code> is the context of the computation. In our case though, <code>this</code> is implemented by means of currying and partial application, it also points to a new context in each expression. And, if in OO context is said to be implicit, then by using monads you make it even more implicit (if there even is such a thing).</p>
<p>The advantage of monads (and functional programming in general) is that you get highly composable building blocks. And it’s all because of function currying. Each time two monadic actions are chained, a new function is created which awaits to be run.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> computation1 = sequence(
  push(<span class="dv">4</span>),
  push(<span class="dv">5</span>),
  pop(),
  pop(),

  <span class="kw">function</span> (pop1, pop2) {
    <span class="kw">return</span> result(pop1 + <span class="st">&quot; : &quot;</span> + pop2);
  }
);

<span class="kw">var</span> computation2 = sequence(
  push(<span class="dv">2</span>),
  push(<span class="dv">3</span>),
  pop(),
  pop(),

  <span class="kw">function</span> (pop1, pop2) {
    <span class="kw">return</span> result(pop1 + <span class="st">&quot; : &quot;</span> + pop2);
  }
);

<span class="kw">var</span> composed = sequence(
  computation1,
  computation2,

  <span class="kw">function</span> (a, b) {
    <span class="kw">return</span> result(a + <span class="st">&quot; : &quot;</span> + b);
  }
);

<span class="kw">console</span>.<span class="fu">log</span>( evalStack(composed, []) ); <span class="co">// &quot;5 : 4 : 3 : 2&quot;</span></code></pre>
<script>
(function () {
  var push = function (element) {
    return function (stack) {
      var value = undefined;
      var newStack = [element].concat(stack);

      return { value: value, stack: newStack };
    };
  };

  var pop = function () {
    return function (stack) {
      var value = stack[0];
      var newStack = stack.slice(1);

      return { value: value, stack: newStack };
    };
  };

  var bind = function (stackAction, continuation) {
    return function (stack) {
      var result = stackAction(stack);
      return continuation(result.value)(result.stack);
    };
  };

  var result = function (value) {
    return function (stack) {
      return { value: value, stack: stack };
    };
  };

  var evalStack = function (stackOperation, initialStack) {
    return stackOperation(initialStack).value;
  };

  var sequence = function (/* monadicActions, final */) {
    var args           = [].slice.call(arguments);
    var monadicActions = args.slice(0, -1);
    var continuation  = args.slice(-1)[0];

    return function (stack) {
      var initialState = { values: [], stack: stack };

      var state = monadicActions.reduce(function (state, action) {
        var result = action(state.stack);
        var values = state.values.concat(result.value);
        var stack  = result.stack;

        return { values: values, stack: stack };
      }, initialState);

      var values = state.values.filter(function (value) {
        return value !== undefined;
      });

      return continuation.apply(this, values)(state.stack);
    };
  };

  var computation1 = sequence(
    push(4),
    push(5),
    pop(),
    pop(),

    function (pop1, pop2) {
      return result(pop1 + " : " + pop2);
    }
  );

  var computation2 = sequence(
    push(2),
    push(3),
    pop(),
    pop(),

    function (pop1, pop2) {
      return result(pop1 + " : " + pop2);
    }
  );

  var composed = sequence(
    computation1,
    computation2,

    function (a, b) {
      return result(a + " : " + b);
    }
  );

  console.group("Composability");
  console.log( evalStack(composed, []) );
  console.groupEnd();
})();
</script>

<p>This may seem useless for performing stack operations, but when designing a library of monadic parser combinators for example, this gets very handy. It allows the author of the library to provide just a handful of “primitive” functions on his Parser monad, and then, the user of the library is able to mix and match those primitives as he sees fit, ultimately ending up with an embedded domain specific language (<abbr title="Embedded Domain Specific Language">EDSL</abbr>).</p>
<h2 id="the-end">The End</h2>
<p>Well, I hope you found this article useful. Writing it definitely helped me having a better understanding of monads.</p>
<h2 id="references">References</h2>
<ul>
<li>Books
<ul>
<li><a href="http://www.cs.nott.ac.uk/~gmh/book.html">Programming in Haskell</a></li>
<li><a href="http://learnyouahaskell.com/">Learn You a Haskell For Great Good!</a></li>
<li><a href="http://book.realworldhaskell.org/">Real World Haskell</a></li>
</ul></li>
<li>Articles and Papers
<ul>
<li><a href="http://www.ccs.neu.edu/home/dherman/research/tutorials/monads-for-schemers.txt">A Schemer’s Introduction to Monads</a></li>
<li><a href="http://www.cs.nott.ac.uk/~gmh/bib.html#pearl">Monadic Parsing in Haskell</a></li>
<li><a href="http://www.cs.nott.ac.uk/~gmh/bib.html#monparsing">Monadic Parser Combinators</a></li>
<li><a href="http://www.valuedlessons.com/2008/01/monads-in-python-with-nice-syntax.html">Monads in Python</a></li>
<li><a href="http://web.cecs.pdx.edu/~antoy/Courses/TPFLP/lectures/MONADS/Noel/research/monads.html">What the hell are Monads?</a></li>
</ul></li>
<li>Videos
<ul>
<li><a href="http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Dr-Ralf-Lmmel-AFP-The-Quick-Essence-of-Functional-Programming">The Quick Essence of Functional Programming</a></li>
<li><a href="http://vimeo.com/20717301">Monad Tutorial in Clojure, Part 1</a></li>
<li><a href="http://vimeo.com/20798376">Monad Tutorial in Clojure, Part 2</a></li>
<li><a href="http://vimeo.com/20963938">Monad Tutorial in Clojure, Part 3</a></li>
<li><a href="http://vimeo.com/21307543">Monad Tutorial in Clojure, Part 4</a></li>
</ul></li>
</ul>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Mon, 02 May 2011 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2011-05-02-understanding-monads-with-javascript.html</guid>
</item>
<item>
    <title>How to Associate TextMate With CoffeeScript Files</title>
    <link>http://igstan.ro/posts/2011-04-21-how-to-associate-textmate-with-coffeescript-files.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>How to Associate TextMate With CoffeeScript Files</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>How to Associate TextMate With CoffeeScript Files</h1>
    <time pubdate>April 21, 2011</time>
    <p>First, tell OS X to use TextMate.app when you try to open <code>.coffee</code> files. The command below will do just that.</p>
<pre class="sourceCode bash"><code class="sourceCode bash">$ defaults <span class="kw">write</span> com.apple.LaunchServices LSHandlers -array-add <span class="kw">\</span>
<span class="st">&quot;&lt;dict&gt;</span>
<span class="st">    &lt;key&gt;LSHandlerContentTag&lt;/key&gt;</span>
<span class="st">    &lt;string&gt;coffee&lt;/string&gt;</span>
<span class="st">    &lt;key&gt;LSHandlerContentTagClass&lt;/key&gt;</span>
<span class="st">    &lt;string&gt;public.filename-extension&lt;/string&gt;</span>
<span class="st">    &lt;key&gt;LSHandlerRoleAll&lt;/key&gt;</span>
<span class="st">    &lt;string&gt;com.macromates.textmate&lt;/string&gt;</span>
<span class="st">&lt;/dict&gt;&quot;</span></code></pre>
<p>To associate TextMate’s generic document icon with <code>.coffee</code> files first go to <code>/Applications/TextMate.app/Contents</code> and open <code>Info.plist</code>. At the bottom of the file there’s a section that looks like this:</p>
<pre><code>{   CFBundleTypeName = &quot;Source&quot;;        /* generic source code types */
    CFBundleTypeExtensions = (
        coffee, g, vss, d, e, gri, inf, mel, build, re,
        textmate, fxscript, lgt
    );
    CFBundleTypeIconFile = TMDocument;
    CFBundleTypeRole = Editor;
}</code></pre>
<p>Put <code>coffee</code> inside the CFBundleTypeExtensions listing (as you can see above). Now rebuild the LaunchServices database:</p>
<pre class="sourceCode bash"><code class="sourceCode bash">$ <span class="kw">ln</span> -s /System/Library/Frameworks/CoreServices.framework/Versions/Current/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister /usr/local/bin/lsregister
$ lsregister -kill -r -domain <span class="kw">local</span> -domain <span class="ot">system</span> -domain <span class="ot">user</span></code></pre>
<p>That should be all.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Thu, 21 Apr 2011 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2011-04-21-how-to-associate-textmate-with-coffeescript-files.html</guid>
</item>
<item>
    <title>Deriving the Y Combinator in 7 Easy Steps</title>
    <link>http://igstan.ro/posts/2010-12-01-deriving-the-y-combinator-in-7-easy-steps.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Deriving the Y Combinator in 7 Easy Steps</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Deriving the Y Combinator in 7 Easy Steps</h1>
    <time pubdate>December 01, 2010</time>
    <p>The <a href="http://en.wikipedia.org/wiki/Fixed_point_combinator">Y Combinator</a> is a method of implementing recursion in a programming language that does not support it natively (actually, it’s used more for exercising programming brains). The requirement, though, is that language to support anonymous functions.</p>
<p>I chose JavaScript for deriving the Y Combinator, starting from the definition of a recursive factorial function, using a step-by-step transformation over the initial function.</p>
<h2 id="update">Update</h2>
<p>There’s now a <a href="http://cnblogs.com/windydays/archive/2012/04/09/2439519.html">Chinese translation</a> of this article as well as a <a href="http://citizen428.net/blog/2010/12/14/clojure-deriving-the-y-combinator-in-7-stolen-steps">Clojure port</a>.</p>
<h2 id="step-1">Step 1</h2>
<p>The initial implementation, using JavaScript’s built-in recursion mechanism.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> fact = <span class="kw">function</span> (n) {
    <span class="kw">if</span> (n &lt; <span class="dv">2</span>) <span class="kw">return</span> <span class="dv">1</span>;
    <span class="kw">return</span> n * fact(n - <span class="dv">1</span>);
};</code></pre>
<h2 id="step-2">Step 2</h2>
<p>What would be the simplest thing to do to obtain basic recursion? We could just define a function which receives itself as an argument and calls that argument with the same argument. That’s an infinite loop of course, and would cause a stack overflow.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript">(<span class="kw">function</span> (f) {
    f(f);
})(<span class="kw">function</span> (f) {
    f(f);
});</code></pre>
<p>Let’s use the above pattern for our factorial function. There is however a small difference. The factorial function receives an argument which we don’t know yet, so what we want is to return a function which takes that argument. That function can then be used to compute factorial numbers. Also, this is what makes our implementation to not result into an infinite loop.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> fact = (<span class="kw">function</span> (f) {
    <span class="kw">return</span> <span class="kw">function</span> (n) {
        <span class="co">// termination condition</span>
        <span class="kw">if</span> (n &lt; <span class="dv">2</span>) <span class="kw">return</span> <span class="dv">1</span>;

        <span class="co">// because f returns a function, we have a double function call.</span>
        <span class="kw">return</span> n * f(f)(n - <span class="dv">1</span>);
    };
})(<span class="kw">function</span> (f) {
    <span class="kw">return</span> <span class="kw">function</span> (n) {
        <span class="co">// termination condition</span>
        <span class="kw">if</span> (n &lt; <span class="dv">2</span>) <span class="kw">return</span> <span class="dv">1</span>;

        <span class="co">// because f returns a function, we have a double function call.</span>
        <span class="kw">return</span> n * f(f)(n - <span class="dv">1</span>);
    };
});</code></pre>
<h2 id="step-3">Step 3</h2>
<p>At this point we have some ugly duplication in there. Let’s hide it away into a helper function called <code>recur</code>.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> recur = <span class="kw">function</span> (f) {
    <span class="kw">return</span> f(f);
};

<span class="kw">var</span> fact = recur(<span class="kw">function</span> (f) {
    <span class="kw">return</span> <span class="kw">function</span> (n) {
        <span class="kw">if</span> (n &lt; <span class="dv">2</span>) <span class="kw">return</span> <span class="dv">1</span>;

        <span class="co">// because f returns a function, we have a double function call.</span>
        <span class="kw">return</span> n * f(f)(n - <span class="dv">1</span>);
    };
});</code></pre>
<h2 id="step-4">Step 4</h2>
<p>The problem with the above version is that double function call. We want to eliminate it so that the implementation of this factorial is similar with the recursive version. How can we do that?</p>
<p>We can use a helper function that takes a numeric argument and performs the double call. The trick is though to keep this helper function in the same environment where <code>f</code> is visible, so that <code>g</code> can actually call <code>f</code>.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> recur = <span class="kw">function</span> (f) {
    <span class="kw">return</span> f(f);
};

<span class="kw">var</span> fact = recur(<span class="kw">function</span> (f) {
    <span class="kw">var</span> g = <span class="kw">function</span> (n) {
        <span class="kw">return</span> f(f)(n);
    };

    <span class="kw">return</span> <span class="kw">function</span> (n) {
        <span class="kw">if</span> (n &lt; <span class="dv">2</span>) <span class="kw">return</span> <span class="dv">1</span>;

        <span class="co">// no more double call, g is a function which takes a numeric arg</span>
        <span class="kw">return</span> n * g(n - <span class="dv">1</span>);
    };
});</code></pre>
<h2 id="step-5">Step 5</h2>
<p>The above works nice, but the definition contains so much clutter code. We can hide it away inside yet another helper function, keeping almost just the definition of factorial.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> recur = <span class="kw">function</span> (f) {
    <span class="kw">return</span> f(f);
};

<span class="kw">var</span> wrap = <span class="kw">function</span> (h) {
    <span class="kw">return</span> recur(<span class="kw">function</span> (f) {
        <span class="kw">var</span> g = <span class="kw">function</span> (n) {
            <span class="kw">return</span> f(f)(n);
        };

        <span class="kw">return</span> h(g);
    });
};

<span class="kw">var</span> fact = wrap(<span class="kw">function</span> (g) {
    <span class="kw">return</span> <span class="kw">function</span> (n) {
        <span class="kw">if</span> (n &lt; <span class="dv">2</span>) <span class="kw">return</span> <span class="dv">1</span>;
        <span class="kw">return</span> n * g(n - <span class="dv">1</span>);
    };
});</code></pre>
<h2 id="step-6">Step 6</h2>
<p>Let’s inline the definition of <code>g</code> inside <code>wrap</code> because we only call it once.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> recur = <span class="kw">function</span> (f) {
    <span class="kw">return</span> f(f);
};

<span class="kw">var</span> wrap = <span class="kw">function</span> (h) {
    <span class="kw">return</span> recur(<span class="kw">function</span> (f) {
        <span class="kw">return</span> h(<span class="kw">function</span> (n) {
            <span class="kw">return</span> f(f)(n);
        });
    });
};

<span class="kw">var</span> fact = wrap(<span class="kw">function</span> (g) {
    <span class="kw">return</span> <span class="kw">function</span> (n) {
        <span class="kw">if</span> (n &lt; <span class="dv">2</span>) <span class="kw">return</span> <span class="dv">1</span>;
        <span class="kw">return</span> n * g(n - <span class="dv">1</span>);
    };
});</code></pre>
<h2 id="step-7">Step 7</h2>
<p>Now, if we also inline the definition of <code>recur</code> function inside <code>wrap</code> we end up with the famous Y Combinator.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> Y = <span class="kw">function</span> (h) {
    <span class="kw">return</span> (<span class="kw">function</span> (f) {
        <span class="kw">return</span> f(f);
    })(<span class="kw">function</span> (f) {
        <span class="kw">return</span> h(<span class="kw">function</span> (n) {
            <span class="kw">return</span> f(f)(n);
        });
    });
};

<span class="kw">var</span> fact = Y(<span class="kw">function</span> (g) {
    <span class="kw">return</span> <span class="kw">function</span> (n) {
        <span class="kw">if</span> (n &lt; <span class="dv">2</span>) <span class="kw">return</span> <span class="dv">1</span>;
        <span class="kw">return</span> n * g(n - <span class="dv">1</span>);
    };
});</code></pre>
<h2 id="the-end">The End</h2>
<p>I hope you enjoyed it!</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Wed, 01 Dec 2010 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2010-12-01-deriving-the-y-combinator-in-7-easy-steps.html</guid>
</item>
<item>
    <title>How to install Memcached functions for MySQL</title>
    <link>http://igstan.ro/posts/2010-11-25-how-to-install-memcached-functions-for-mysql.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>How to install Memcached functions for MySQL</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>How to install Memcached functions for MySQL</h1>
    <time pubdate>November 25, 2010</time>
    <p>Download <a href="https://launchpad.net/libmemcached/+download?start=10">libmemcached 0.35</a> (any version greater than this won’t work) and <a href="https://launchpad.net/memcached-udfs/+download">Memcached functions for MySQL</a> (I’ve used version 1.1).</p>
<p>Extract libmemcached and execute the following inside the extracted directory:</p>
<pre class="sourceCode bash"><code class="sourceCode bash">./configure
<span class="kw">make</span>
<span class="kw">sudo</span> <span class="kw">make</span> <span class="kw">install</span></code></pre>
<p>Extract the Memcached functions archive and execute the following inside the extracted directory:</p>
<pre class="sourceCode bash"><code class="sourceCode bash">./configure
<span class="kw">make</span>
<span class="kw">sudo</span> <span class="kw">make</span> <span class="kw">install</span></code></pre>
<p>Execute the following query inside a MySQL client and copy the returned value:</p>
<pre class="sourceCode sqlmysql"><code class="sourceCode sqlmysql"><span class="kw">SHOW</span> VARIABLES <span class="kw">LIKE</span> <span class="st">&#39;plugin_dir&#39;</span>;</code></pre>
<p>Copy the compiled Memcached libraries to the MySQL plugins directory:</p>
<pre class="sourceCode bash"><code class="sourceCode bash"><span class="kw">sudo</span> <span class="kw">cp</span> /usr/local/lib/libmemcached_functions_mysql* <span class="kw">&lt;</span>VALUE_FROM_ABOVE_QUERY<span class="kw">&gt;</span></code></pre>
<p>Restart the MySQL server, then go to Memcached functions dir and then the “sql” directory. Log into a mysql client in that dir:</p>
<pre class="sourceCode bash"><code class="sourceCode bash">$ mysql -uroot
mysql<span class="kw">&gt;</span> <span class="kw">source</span> ./install_functions.sql</code></pre>
<p>You’re done. Hopefully.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Thu, 25 Nov 2010 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2010-11-25-how-to-install-memcached-functions-for-mysql.html</guid>
</item>
<item>
    <title>PLAI - Rudimentary Interpreters</title>
    <link>http://igstan.ro/posts/2010-08-28-plai-rudimentary-interpreters.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>PLAI - Rudimentary Interpreters</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>PLAI - Rudimentary Interpreters</h1>
    <time pubdate>August 28, 2010</time>
    <p>I’ve just finished the second section of <abbr title="Programming Languages: Application and Interpretation">PLAI</abbr>, Rudimentary Interpreters.</p>
<p>It revolves around a basic interpreter for arithmetic expressions. The idea was presented from chapter I actually. The difference is that chapter I introduces the syntax for this languages, which is more or less Scheme with curly brackets instead of braces. For example, <code>{+ 1 2}</code> represents the addition operation between the numbers 1 and 2. The second chapter though, deals with the semantics of the language; introduces concepts such as identifiers, scope and functions. All in a progressive manner, building new concepts on top of existing ones.</p>
<p>A little digression. PLAI uses a dialect of Scheme as its languages, and while I like Scheme, this language that they use, called PLAI Scheme, is actually quite ugly to my eyes. The reason is that it’s some sort of typed Scheme, in that it has algebraic data types and means of destructuring such data into its variants. In fact, it looks a lot like Haskell, so what I did was to write all the supporting code in Haskell. I started with PLAI Scheme in chapter one, but chapter two was all Haskell. The little disadvantage is that in Haskell I don’t have a <code>read</code> function that takes valid Scheme code and returns a corresponding Scheme data structure. So I had to write the parser myself, but it was no big deal for two reasons. First of all, the syntax for this arithmetic language is quite simple, and secondly, Haskell has really powerful libraries for parsing. For convenience I’ve used Parsec, as I already have some experience with it, but there lots of other parsing libraries (I’ve heard some of them are even better than Parsec). To end this digression, all the Haskell code I wrote for this chapter is available in my <a href="http://github.com/igstan/plai">Github repo</a>. I hope I’ll write another blog post with details about its implementation.</p>
<p>Now, back to the book.</p>
<p>The chapter starts by exploring the concept of identifiers and ways of supporting them in a language by means of substitution. These identifiers resemble normal variables that we all know, except for one thing, they can’t be reassigned a new values. So they’re actually constants, not variables. It then goes on describing what happens when there are overlapping identifiers names, whether it’s a good thing and how to implement it correctly. But it’s not a book that gives you the correct solution from the first shot. It makes you write a program with mistakes, then provides some examples that won’t work with the respective program, at which point the whole theory behind the concepts begins. The reason is very simple, the author wants the readers to judge based on a concrete program instead of some abstract concepts.</p>
<p>I won’t go into details about substitution, as it is a pretty complex subject and would provide no information that it’s not in the book. There’s one thing that I want to mention though. One section of chapter three asks whether names are necessary for identifiers. It appears that someone called Nicolaas de Bruijn said they’re not, and instead, he used numbers. This appears to be employed in compiler construction. Maybe I’ll talk in detail about substitution in a future post.</p>
<p>After substitution, the language is enriched with functions. These are quite simple conceptually, as they take a single argument and return a value that is always numeric, but it’s a good start for observing the issues that arise when combining substitution and functions.</p>
<p>After substitution and functions, the author introduces deferred substitution as a means of improving the performance of the interpreter. Instead of passing through the whole program for each identifier that dictates a substitution, the interpreter is now storing these identifiers and their values in a data structure that is queried on a per need basis, i.e., whenever a new scope is found that uses a free identifier.</p>
<p>The last part of this second section of the book deals with first-class functions, i.e., functions that ca be used as any other value in the language. They can be returned from functions, or passed to functions. Also, in the moment functions as first-class values meet deferred substitution, the concept of closure emerges.</p>
<p>In short, that’s what section two of PLAI touches. If you want more details, then start reading the book. I had a lot of fun implementing this little language in Haskell. Although small, it encompasses a lot of advanced programming concepts unavailable in other languages (PHP for example, which is what I do for a living).</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Sat, 28 Aug 2010 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2010-08-28-plai-rudimentary-interpreters.html</guid>
</item>
<item>
    <title>PLAI - Chapter I</title>
    <link>http://igstan.ro/posts/2010-08-16-plai-chapter-I.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>PLAI - Chapter I</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>PLAI - Chapter I</h1>
    <time pubdate>August 16, 2010</time>
    <p>Yesterday I’ve begun reading <a href="http://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/">Programming Languages: Application and Interpretation</a> (abbreviated <abbr title="Programming Languages: Application and Interpretation">PLAI</abbr>), written by Shriram Krishnamurthi. The book is available for free in PDF format.</p>
<p>The main reason for starting it is because I’ve noticed, about a year ago, that I have a passion for programming languages. I like to learn new programming languages, programming concepts or ways to make such languages more expressive. The final goal would be to implement myself a programming language. This goal, however, is not set for the near future. First of all, I want to work hard in the trenches with multiple languages, and learn as much as I can about languages that have gone away, or maybe that have influenced other ones. In order to invent, I need an inventory.</p>
<p>For the next month or so, I plan to read the above book. It is used as a text book at Brown University, and seemingly in some other universities. The thing that got me about it is the titles of the chapters. I’ve heard about most of those concepts in my short experience with several languages, and maybe even worked with several of them, but I certainly want to know more about them (like ways of implementing them, advantages and disadvantages). Things like laziness, recursion, (immutable) state, continuations, type inference and metaprogramming are guaranteed to give me thrills at this point in my life. They may sound like buzzwords, and they may actually be in this moment of functional programming resurrection, but… as I have little knowledge about them (that means, I can’t yet explain them that well to you, I only have instinctive understanding) it seems normal to attract me so much.</p>
<p>Yesterday I’ve read the first chapter, the Prelude, which is basically an introduction to programming language modelling and some theory about parsers.</p>
<p>The main thing that should be retained from this chapter would be that each programming language (I’d say programming platform though, because of the libraries part) consists of four categories:</p>
<ul>
<li>syntax</li>
<li>behavior associated with syntax: semantics</li>
<li>libraries</li>
<li>idioms</li>
</ul>
<p>Also, as a note for those interested in reading the book themselves. I’m using <a href="http://racket-lang.org/">DrRacket</a> to work through the examples, but the syntax isn’t standard Scheme, so I had to choose the “Pretty Big” language.</p>
<p>Now, I’m going to start reading the next chapter: Rudimentary Interpreters.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Mon, 16 Aug 2010 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2010-08-16-plai-chapter-I.html</guid>
</item>
<item>
    <title>Git's environment filter</title>
    <link>http://igstan.ro/posts/2010-03-05-gits-environment-filter.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Git's environment filter</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Git's environment filter</h1>
    <time pubdate>March 05, 2010</time>
    <p>This is a thing I keep on forgetting although I’ve done it several times. So, I’m writing a blog post hoping it will help me memorize this.</p>
<p>So… how do you rewrite Git’s history, specifically the environment variables. With <code>git filter-branch</code> of course. I frequently need it in order to change the author and committer email addresses (either from personal to work or the other way around).</p>
<pre class="sourceCode bash"><code class="sourceCode bash">git filter-branch --env-filter <span class="st">&#39;export GIT_AUTHOR_EMAIL=&quot;email@address.com&quot;&#39;</span> HEAD
git filter-branch --env-filter <span class="st">&#39;export GIT_COMMITTER_EMAIL=&quot;email@address.com&quot;&#39;</span> HEAD</code></pre>
<p>Don’t forget that there are two email addresses, OK? The author’s and committer’s one. Oh, and no spaces around the equal sign.</p>
<p>For a more complicated situation see <a href="http://serverfault.com/questions/12373/how-do-i-edit-gits-history-to-correct-an-incorrect-email-address-name">this answer on serverfault.com</a>.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Fri, 05 Mar 2010 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2010-03-05-gits-environment-filter.html</guid>
</item>
<item>
    <title>CSS for Firefox only</title>
    <link>http://igstan.ro/posts/2009-06-05-css-for-firefox-only.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>CSS for Firefox only</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>CSS for Firefox only</h1>
    <time pubdate>June 05, 2009</time>
    <p>So, how do you write <abbr title="Cascading Style Sheets">CSS</abbr> code that will be understood only by Firefox?</p>
<p>Same <a href="http://stackoverflow.com/questions/952861/targeting-only-firefox-with-css">question</a> was asked by someone on <a href="http://stackoverflow.com/">stackoverflow.com</a>. My first attempt was to use <a href="https://developer.mozilla.org/en/XBL/XBL%5F1.0%5FReference">XBL</a> and Mozilla’s proprietary <code>-moz-binding</code> CSS extension in order to run some JavaScript that will eventually load the intended CSS rules. This solution was inspired by <a href="http://dean.edwards.name/moz-behaviors/">Dean Edwards’ moz-behaviors library</a> and it looks like this:</p>
<p>firefox.html</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="dt">&lt;!DOCTYPE </span>html<span class="dt">&gt;</span>

<span class="kw">&lt;html&gt;</span>
<span class="kw">&lt;head&gt;</span>
<span class="kw">&lt;style</span><span class="ot"> type=</span><span class="st">&quot;text/css&quot;</span><span class="kw">&gt;</span>
body <span class="kw">{</span>
  <span class="kw">-moz-binding:</span> <span class="dt">url(</span>firefox<span class="dt">.</span>xml#load-mozilla-css<span class="dt">)</span><span class="kw">;</span>
<span class="kw">}</span>
<span class="kw">&lt;/style&gt;</span>
<span class="kw">&lt;/head&gt;</span>
<span class="kw">&lt;body&gt;</span>

  <span class="kw">&lt;h1&gt;</span>This should be red in Firefox<span class="kw">&lt;/h1&gt;</span>

<span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>
<p>firefox.xml</p>
<pre class="sourceCode xml"><code class="sourceCode xml"><span class="kw">&lt;?xml</span> version=&quot;1.0&quot;<span class="kw">?&gt;</span>

<span class="kw">&lt;bindings</span><span class="ot"> xmlns=</span><span class="st">&quot;http://www.mozilla.org/xbl&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;binding</span><span class="ot"> id=</span><span class="st">&quot;load-mozilla-css&quot;</span><span class="kw">&gt;</span>
        <span class="kw">&lt;implementation&gt;</span>
            <span class="kw">&lt;constructor&gt;</span>
            <span class="bn">&lt;![CDATA[</span>
            var link = document.createElement(&quot;link&quot;);
            link.setAttribute(&quot;rel&quot;, &quot;stylesheet&quot;);
            link.setAttribute(&quot;type&quot;, &quot;text/css&quot;);
            link.setAttribute(&quot;href&quot;, &quot;ff.css&quot;);

            document.getElementsByTagName(&quot;head&quot;)[0]
                    .appendChild(link);
            <span class="bn">]]&gt;</span>
            <span class="kw">&lt;/constructor&gt;</span>
        <span class="kw">&lt;/implementation&gt;</span>
    <span class="kw">&lt;/binding&gt;</span>
<span class="kw">&lt;/bindings&gt;</span></code></pre>
<p>firefox.css</p>
<pre class="sourceCode css"><code class="sourceCode css">h1 <span class="kw">{</span>
  <span class="kw">color:</span> <span class="dt">red</span><span class="kw">;</span>
<span class="kw">}</span></code></pre>
<p>But I felt that there should be a better solution. So I kept digging on <a href="https://developer.mozilla.org/en-US/"><abbr title="Mozilla Developer Center">MDC</abbr></a>. After a couple of clicks I discovered the easiest solution out there for targeting just the Firefox browser in our CSS. It uses a Mozilla specific at-rule, called <a href="https://developer.mozilla.org/en/CSS/@-moz-document"><code>@-moz-document</code></a>, and it’s actually intended for user styling.</p>
<h2 id="heres-the-final-solution">Here’s the final solution</h2>
<pre class="sourceCode html"><code class="sourceCode html"><span class="dt">&lt;!DOCTYPE </span>html<span class="dt">&gt;</span>

<span class="kw">&lt;html&gt;</span>
<span class="kw">&lt;head&gt;</span>
<span class="kw">&lt;style</span><span class="ot"> type=</span><span class="st">&quot;text/css&quot;</span><span class="kw">&gt;</span>
@-moz-document url-prefix() <span class="kw">{</span>
  <span class="er">h1</span> <span class="er">{</span>
    <span class="kw">color:</span> <span class="dt">red</span><span class="kw">;</span>
  <span class="kw">}</span>
}
<span class="kw">&lt;/style&gt;</span>
<span class="kw">&lt;/head&gt;</span>
<span class="kw">&lt;body&gt;</span>

  <span class="kw">&lt;h1&gt;</span>This should be red in FF<span class="kw">&lt;/h1&gt;</span>

<span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>
<h2 id="a-word-of-caution">A word of caution</h2>
<p>We all know how many hours Internet Explorer conditional comments have saved us, but I believe Firefox is a much, much better browser, so please think twice before using the above trick. I’m pretty sure there must be some other way. We don’t want to maintain three different stylesheets, for <abbr title="Internet Explorer">IE</abbr>, <abbr title="Firefox">FF</abbr> and the rest of the browsers out there.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Fri, 05 Jun 2009 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2009-06-05-css-for-firefox-only.html</guid>
</item>
<item>
    <title>JScript deviations from ECMAScript 3</title>
    <link>http://igstan.ro/posts/2009-04-28-jscript-deviations-from-ecmascript-3.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>JScript deviations from ECMAScript 3</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>JScript deviations from ECMAScript 3</h1>
    <time pubdate>April 28, 2009</time>
    <p>Just found a great resource of “things” that are specific to JScript and are not conforming to the ECMAScript 3 standard. Found it on a <a href="http://blogs.msdn.com/jscript/archive/2007/10/29/ecmascript-3-and-beyond.aspx">MSDN blog post from 2007</a>. Enjoy, 87 pages of standards deviations (aka bugs)! <a href="http://wiki.ecmascript.org/lib/exe/fetch.php?id=resources%3Aresources&amp;cache=cache&amp;media=resources:jscriptdeviationsfromes3.pdf">Here’s the PDF</a>.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Tue, 28 Apr 2009 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2009-04-28-jscript-deviations-from-ecmascript-3.html</guid>
</item>
<item>
    <title>Lambdas and closures in PHP 5.3</title>
    <link>http://igstan.ro/posts/2009-04-03-lambdas-and-closures-in-php-5.3.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Lambdas and closures in PHP 5.3</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Lambdas and closures in PHP 5.3</h1>
    <time pubdate>April 03, 2009</time>
    <p><a href="/posts/2009-04-01-what-is-new-in-php-5.3.html">Beginning with PHP 5.3</a> we’ll be able to write anonymous functions and build closures around them - almost the same way we do it in JavaScript. I’d like to introduce these to those of you unaware of these new possibilities in this little blog post.</p>
<h2 id="defining-a-lambda">Defining a lambda</h2>
<p>The most simple way to define a lambda can be find below. It’s exactly the same way JavaScript handles it. One has to assing a function to a variable.</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="kw">$lambda</span> = <span class="kw">function</span><span class="ot">()</span> {
    <span class="kw">return</span> <span class="st">&#39;Hello World&#39;</span><span class="ot">;</span>
}<span class="ot">;</span> <span class="co">// &lt;- this semicolon is mandatory, unlike JavaScript</span>

<span class="fu">echo</span> <span class="kw">$lambda</span><span class="ot">();</span></code></pre>
<h2 id="creating-closures">Creating closures</h2>
<p>However, if we want closures, we have to do something more and this because the way scope is designed in PHP where functions don’t get easy access to variables declared outside them. If we want that with a normal (old style) function, we need to import them using the <code>global</code> keyword. Following the same idea, in order to capture a variable into a closure we need to <code>use</code> it:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="kw">$word</span> = <span class="st">&#39; World&#39;</span><span class="ot">;</span>
<span class="kw">$lambda</span> = <span class="kw">function</span><span class="ot">()</span> <span class="kw">use</span><span class="ot">(</span><span class="kw">$word</span><span class="ot">)</span> {
    <span class="kw">return</span> <span class="st">&#39;Hello&#39;</span> . <span class="kw">$word</span><span class="ot">;</span>
}<span class="ot">;</span>

<span class="fu">echo</span> <span class="kw">$lambda</span><span class="ot">();</span></code></pre>
<h2 id="mutable-closures">Mutable closures</h2>
<p>Now, our anonymous functions has access to <code>$word</code>. But <em>there’s a gotcha</em> right here. It has read only access to <code>$word</code>. We may try to modify <code>$word</code> inside our function, but those changes won’t be visible outside it. So, here we are, introducing the third thing we need to know about lambdas and closures in PHP. In order to be able to modify a closed variable, we need to import it using the reference operator:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="kw">$word</span> = <span class="st">&#39; World&#39;</span><span class="ot">;</span>
<span class="kw">$lambda</span> = <span class="kw">function</span><span class="ot">()</span> <span class="kw">use</span><span class="ot">(</span>&amp; <span class="kw">$word</span><span class="ot">)</span> {
    <span class="kw">$result</span> = <span class="st">&#39;Hello&#39;</span> . <span class="kw">$word</span><span class="ot">;</span>
    <span class="kw">$word</span> = <span class="st">&#39;Bye World&#39;</span><span class="ot">;</span>
    <span class="kw">return</span> <span class="kw">$result</span><span class="ot">;</span>
}<span class="ot">;</span>

<span class="fu">echo</span> <span class="kw">$lambda</span><span class="ot">();</span>
<span class="fu">echo</span> <span class="kw">$word</span><span class="ot">;</span></code></pre>
<p>This time, <code>$word</code> can and will be modified. The variable inside the closure is mutable.</p>
<h2 id="some-history-about-the-future">Some history about the future</h2>
<p>Although, as of yet, a stable version of PHP 5.3 is not yet out, I should mention that in the process of bringing lambdas and closures to the language there was a particular property of these in that they were able to automagically import the <code>$this</code> pointer if the function was defined inside a class. Not long after, some people thought about writing PHP in the prototypal style of JavaScript, thus there were some discussion that lead the PHP internals to temporarily remove the magic import feature. The main reason was that they had to push the final version out sooner and any new feature would have meant delays. Nevertheless, this feature has been postponed for PHP 6 in which we may get some niceties that should allow us to more easily write code in a monkey patching/prototypal style.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Fri, 03 Apr 2009 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2009-04-03-lambdas-and-closures-in-php-5.3.html</guid>
</item>
<item>
    <title>What's new in PHP 5.3</title>
    <link>http://igstan.ro/posts/2009-04-01-what-is-new-in-php-5.3.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>What's new in PHP 5.3</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>What's new in PHP 5.3</h1>
    <time pubdate>April 01, 2009</time>
    <p>A few weeks ago, <a href="http://www.php.net/archive/2009.php#id2009-03-24-1">PHP 5.3 RC1 has been released</a> and I expect the final version to be out in no more than a month. I’m watching its development since the beginning of 2008 and am really eager to see it in production. The reason for this impatience is that it brings really cool features to the language and I’d like to enumerate some of them in order of my preferences. Initially I also wanted to briefly describe them, but apparently there was to much to talk about in just one post, therefore each feature in the list below will, eventually, point to a more detailed post about the respective feature. So here’s what I like best:</p>
<ol style="list-style-type: decimal">
<li><a href="/posts/2009-04-03-lambdas-and-closures-in-php-5.3.html">Lambdas and closures</a></li>
<li>Callable classes</li>
<li>Namespaces</li>
<li>The Phar extension</li>
<li>Late static binding</li>
</ol>
<p>There are some other features beside the above mentioned, but these are easier to present so I’ll shortly describe them here:</p>
<h2 id="callstatic"><code>__callStatic</code></h2>
<p>This is just like the __call we all know except it is designed to work when calling methods in a static context:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="kw">class</span> Test
{
    <span class="kw">public</span> <span class="kw">static</span> <span class="kw">function</span> __callStatic<span class="ot">(</span><span class="kw">$method</span><span class="ot">,</span> <span class="kw">$args</span><span class="ot">)</span>
    {
        <span class="kw">return</span> <span class="fu">array</span><span class="ot">(</span><span class="kw">$method</span><span class="ot">,</span> <span class="kw">$args</span><span class="ot">);</span>
    }
}

<span class="fu">var_dump</span><span class="ot">(</span>Test::dummyMethod<span class="ot">(</span><span class="st">&#39;with dummy argument&#39;</span><span class="ot">));</span></code></pre>
<h2 id="nowdoc-strings">Nowdoc strings</h2>
<p>We all know <a href="http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc">heredoc</a> strings and the fact they are parsed by the PHP engine for variable interpolation. They’re also good when we have large strings with both single and double quotes, because it saves us from escaping them. Some PHP internals thought though, that the overhead produced for variable interpolation is to big, so they came up with <a href="http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc">nowdoc</a> strings. This is just like heredoc save for the variable interpolation. Here’s an example:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="kw">$here_doc</span> = <span class="kw">&lt;&lt;&lt;STR</span>
<span class="st">Some random string with </span><span class="kw">$variable</span><span class="st"> interpolation...</span>
<span class="st">STR;</span>

<span class="kw">$now_doc</span><span class="st"> = &lt;&lt;&lt;&#39;STR&#39;</span>
<span class="st">Some random string without </span><span class="kw">$variable</span><span class="st"> interpolation...</span>
<span class="st">STR;</span></code></pre>
<h2 id="ternary-shortcut">Ternary shortcut (<code>?:</code>)</h2>
<p>This is just like the old ternary operator except that we can leave out the middle statement. <a href="http://php.net/ternary#language.operators.comparison.ternary">The rule is</a> that, if the left-hand side expression evaluates to true, its result is returned, otherwise it will return the result of the result of right-hand side expression:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="fu">var_dump</span><span class="ot">(</span><span class="st">&#39;&#39;</span> <span class="ot">?:</span> <span class="st">&#39;there was an empty string&#39;</span><span class="ot">);</span>
<span class="fu">var_dump</span><span class="ot">(</span><span class="st">&#39;I am not empty&#39;</span> <span class="ot">?:</span> <span class="st">&#39;there was an empty string&#39;</span><span class="ot">);</span></code></pre>
<h2 id="limited-goto">Limited <code>goto</code></h2>
<p>Honestly, I don’t yet understand why this construct is limited because I have never worked with gotos. All I know is that we cannot use goto statements inside loops, this will cause a fatal error to be thrown. Anyway, here’s a <a href="http://www.php.net/manual/en/control-structures.goto.php">basic example taken straight from the manual</a>:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

goto a<span class="ot">;</span>
<span class="fu">echo</span> <span class="st">&#39;Foo&#39;</span><span class="ot">;</span>

a:
<span class="fu">echo</span> <span class="st">&#39;Bar&#39;</span><span class="ot">;</span></code></pre>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Wed, 01 Apr 2009 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2009-04-01-what-is-new-in-php-5.3.html</guid>
</item>
<item>
    <title>Komodo Edit dark theme</title>
    <link>http://igstan.ro/posts/2009-03-28-komodo-edit-dark-theme.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Komodo Edit dark theme</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Komodo Edit dark theme</h1>
    <time pubdate>March 28, 2009</time>
    <p>For some time now, I developed some computer related eye fatigue, which kinda sucks and I believe this is due (in part) to the white background of my text editor(s). That’s why I decided to try a dark theme in Komodo Edit. The one shipped with the editor is a bit ugly, I wanted something more like <a href="http://jyte.com/cl/twilight-is-the-best-textmate-theme">Twilight for Textmate</a> and any Google search for Komodo themes returned pretty much nothing. So, here’s my creation, inspired by all those dark themes out there, especially Twilight.</p>
<p style="text-align: center;">
  
<a href="/files/images/komodo-theme-php-syntax.png"
     title="Click to view a larger version"> <img src="/files/images/resized/komodo-theme-php-syntax.png"
         alt="Screenshot for PHP syntax"> </a>
</p>

<p>If you like it, you can grab the <a href="https://github.com/igstan/komodo-themes/raw/master/Twilight.ksf">theme file</a> from my <a href="https://github.com/igstan/komodo-themes">GitHub repo</a>.</p>
<p>It only supports PHP and JavaScript syntax for the moment. More to come when I’ll have some time. Update: There’s Python and XML support right now.</p>
<p>After you download it, put the “.ksf” file in your Komodo Edit application data folder, more precisely the schemes directory. On my Windows machine this is: <code>C:\Documents and Settings\{user}\Application Data\ActiveState\KomodoEdit\4.3\schemes</code>.</p>
<p>Enjoy!</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Sat, 28 Mar 2009 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2009-03-28-komodo-edit-dark-theme.html</guid>
</item>
<item>
    <title>XHTML no matter what</title>
    <link>http://igstan.ro/posts/2009-03-20-xhtml-no-matter-what.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>XHTML no matter what</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>XHTML no matter what</h1>
    <time pubdate>March 20, 2009</time>
    <p><a href="http://metropotam.ro/">metropotam.ro</a> changed their layout. Here’s what XHTML obsession means (look after <abbr title="Internet Explorer">IE</abbr> conditional comments).</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;base</span><span class="ot"> href=</span><span class="st">&quot;http://metropotam.ro/&quot;</span> <span class="kw">/&gt;</span><span class="co">&lt;!--[if IE]&gt;&lt;/base&gt;&lt;![endif]--&gt;</span></code></pre>
<p>I simply cannot see the reason for such a useless hack. Too bad they forgot to do the same thing for <code>script</code> tags. But I see the reason for the one below (again, look after <abbr title="Internet Explorer">IE</abbr> conditional comments).</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;li</span><span class="ot"> class=</span><span class="st">&quot;selected&quot;</span><span class="kw">&gt;</span>
  <span class="co">&lt;!--[if lte IE 6]&gt;&lt;table&gt;&lt;tr&gt;&lt;td&gt;&lt;![endif]--&gt;</span>
  <span class="kw">&lt;ul&gt;</span>
  ...
  <span class="kw">&lt;/ul&gt;</span>
  <span class="co">&lt;!--[if lte IE 6]&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;/a&gt;&lt;![endif]--&gt;</span>
<span class="kw">&lt;/li&gt;</span></code></pre>
<p>But then again. What’s this?</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;li&gt;&lt;a</span><span class="ot"> href=</span><span class="st">&quot;...&quot;</span><span class="kw">&gt;&lt;strong&gt;</span>Unde iesim<span class="kw">&lt;/strong&gt;</span><span class="co">&lt;!--[if gte IE 7]&gt;&lt;!--&gt;</span><span class="kw">&lt;/a&gt;</span><span class="co">&lt;!--&lt;![endif]--&gt;</span></code></pre>
<p>Regardless of the above nitpicking though, I like the new layout.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Fri, 20 Mar 2009 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2009-03-20-xhtml-no-matter-what.html</guid>
</item>
<item>
    <title>PHP's ErrorException class</title>
    <link>http://igstan.ro/posts/2009-03-18-phps-errorexception-class.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>PHP's ErrorException class</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>PHP's ErrorException class</h1>
    <time pubdate>March 18, 2009</time>
    <p>Did you know <abbr title="PHP HyperText Preprocessor">PHP</abbr> has an <a href="http://www.php.net/manual/en/class.errorexception.php"><code>ErrorException</code></a> class</a> that solves the problem of throwing exceptions from an <a href="http://www.php.net/manual/en/function.set-error-handler.php">error handler function</a>?</p>
<p>What problem?</p>
<p>Well, if you throw a normal <code>Exception</code> from such a handler, the file name and line number of the <code>Exception</code> will be set to match the file and line where the <code>Exception</code> was actually thrown and not the place where the error happened. There was no way to extend an Exception class and provide the correct information as <code>Exception</code>’s <code>$file</code> and <code>$line</code> properties are private and there are no setters for them, only getters.</p>
<p><code>ErrorException</code> solves this problem by overriding the <code>Exception</code> constructor, allowing us to pass up to five arguments. From these five arguments, four have the same meaning as the four arguments passed to the error handler function: <code>$errno</code>, <code>$errstr</code>, <code>$errfile</code>, <code>$errline</code>. By passing along these arguments to the <code>ErrorException</code> constructor we get a more meaningful exception from our error handler.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Wed, 18 Mar 2009 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2009-03-18-phps-errorexception-class.html</guid>
</item>
<item>
    <title>Change default sort order in Mozilla Thunderbird</title>
    <link>http://igstan.ro/posts/2009-02-16-change-default-sort-order-in-mozilla-thunderbird.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Change default sort order in Mozilla Thunderbird</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Change default sort order in Mozilla Thunderbird</h1>
    <time pubdate>February 16, 2009</time>
    <p>I like email and feed messages ordered by date ascending in my Thunderbird, but its default settings are date descending. So I changed it like this:</p>
<ul>
<li>Go to: Tools -&gt; Options</li>
<li>Click “Config Editor…” button</li>
<li>Search for “sort”</li>
<li>Change value of <strong>mailnews.default_sort_order</strong> from <strong>1</strong> to <strong>2</strong></li>
</ul>
<p>In case you had no idea whether Thunderbird has an “about:config” capability like Firefox, now you know.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Mon, 16 Feb 2009 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2009-02-16-change-default-sort-order-in-mozilla-thunderbird.html</guid>
</item>
<item>
    <title>MySQL transliteration function</title>
    <link>http://igstan.ro/posts/2009-02-13-mysql-transliteration-function.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>MySQL transliteration function</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>MySQL transliteration function</h1>
    <time pubdate>February 13, 2009</time>
    <p>In my latest project at work I had to obtain, by means of an <abbr title="Structured Query Language">SQL</abbr> query, <a href="http://en.wikipedia.org/wiki/Transliteration">transliterated</a> values of certain data fields in our database. And when I say transliteration I don’t mean to transform characters from all over the world into latin characters. What I wanted was to strip <a href="http://en.wikipedia.org/wiki/Diacritic">diacritics</a> out of latin based characters, like: ș, ț, ă, î or â.</p>
<p>Initially I thought this should be an easy job as database, table and column charset values were all set to <code>utf8_general_ci</code> and I knew MySQL does well at comparing basic latin characters against derived ones. Well, it wasn’t. Although the following query returns <code>true</code> (or <code>1</code>), there’s no way of querying MySQL for a transliterated value, i.e. from the right hand side string to obtain the left hand side string.</p>
<pre class="sourceCode sql"><code class="sourceCode sql"><span class="kw">SELECT</span> <span class="st">&#39;staia&#39;</span> = <span class="st">&#39;șțăîâ&#39;</span>;</code></pre>
<p>So what I did was to define a function in which to take advantage of the comparison feature in order to obtain transliteration. What I came up with might end up on <a href="http://thedailywtf.com/">thedailywtf.com</a> but despite its apparent stupidity it does its job very well. So here’s the function:</p>
<p><strong>UPDATE</strong>: I’ve incorporated <a href="#comment-183108903">Gabriel Humeniuc’s fixes</a> for preserving the character case, fixed a bug in the MySQL <code>CONCAT</code> function which ignores whitespace characters, and added a special case for the Polish letter “ł”. However the most up-to-date version of this procedure will always be on GitHub: <a href="https://github.com/igstan/sql-utils/blob/master/transliterate.sql">https://github.com/igstan/sql-utils/blob/master/transliterate.sql</a>.</p>
<pre class="sourceCode sql"><code class="sourceCode sql"><span class="co">-- Copyright (c) 2012, Ionut Gabriel Stan. All rights reserved.</span>
<span class="co">--</span>
<span class="co">-- Redistribution and use in source and binary forms, with or without modification,</span>
<span class="co">-- are permitted provided that the following conditions are met:</span>
<span class="co">--</span>
<span class="co">-- * Redistributions of source code must retain the above copyright notice,</span>
<span class="co">-- this list of conditions and the following disclaimer.</span>
<span class="co">--</span>
<span class="co">-- * Redistributions in binary form must reproduce the above copyright notice,</span>
<span class="co">-- this list of conditions and the following disclaimer in the documentation</span>
<span class="co">-- and/or other materials provided with the distribution.</span>
<span class="co">--</span>
<span class="co">-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &quot;AS IS&quot; AND</span>
<span class="co">-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED</span>
<span class="co">-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE</span>
<span class="co">-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR</span>
<span class="co">-- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES</span>
<span class="co">-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;</span>
<span class="co">-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON</span>
<span class="co">-- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT</span>
<span class="co">-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS</span>
<span class="co">-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</span>

DELIMITER $

<span class="kw">DROP</span> <span class="kw">FUNCTION</span> <span class="kw">IF</span> <span class="kw">EXISTS</span> `transliterate` $
<span class="kw">CREATE</span> <span class="kw">FUNCTION</span> `transliterate` (original <span class="dt">VARCHAR</span>(<span class="dv">512</span>)) RETURNS <span class="dt">VARCHAR</span>(<span class="dv">512</span>)
<span class="kw">BEGIN</span>

  <span class="kw">DECLARE</span> translit <span class="dt">VARCHAR</span>(<span class="dv">512</span>) <span class="kw">DEFAULT</span> <span class="st">&#39;&#39;</span>;
  <span class="kw">DECLARE</span> len      <span class="dt">INT</span>(<span class="dv">3</span>)       <span class="kw">DEFAULT</span> <span class="dv">0</span>;
  <span class="kw">DECLARE</span> pos      <span class="dt">INT</span>(<span class="dv">3</span>)       <span class="kw">DEFAULT</span> <span class="dv">1</span>;
  <span class="kw">DECLARE</span> letter   <span class="dt">CHAR</span>(<span class="dv">1</span>);
  <span class="kw">DECLARE</span> is_lower BIT;

  <span class="kw">SET</span> len = CHAR_LENGTH(original);

  WHILE (pos &lt;= len) DO
    <span class="kw">SET</span> letter   = SUBSTRING(original, pos, <span class="dv">1</span>);
    <span class="kw">SET</span> is_lower = <span class="kw">IF</span>(LCASE(letter) COLLATE utf8_bin = letter COLLATE utf8_bin, <span class="dv">1</span>, <span class="dv">0</span>);

    <span class="kw">CASE</span> <span class="kw">TRUE</span>
      <span class="kw">WHEN</span> letter = <span class="st">&#39;a&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;a&#39;</span>, <span class="st">&#39;A&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;b&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;b&#39;</span>, <span class="st">&#39;B&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;c&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;c&#39;</span>, <span class="st">&#39;C&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;d&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;d&#39;</span>, <span class="st">&#39;D&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;e&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;e&#39;</span>, <span class="st">&#39;E&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;f&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;f&#39;</span>, <span class="st">&#39;F&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;g&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;g&#39;</span>, <span class="st">&#39;G&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;h&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;h&#39;</span>, <span class="st">&#39;H&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;i&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;i&#39;</span>, <span class="st">&#39;I&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;j&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;j&#39;</span>, <span class="st">&#39;J&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;k&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;k&#39;</span>, <span class="st">&#39;K&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;l&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;l&#39;</span>, <span class="st">&#39;L&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;ł&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;l&#39;</span>, <span class="st">&#39;L&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;m&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;m&#39;</span>, <span class="st">&#39;M&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;n&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;n&#39;</span>, <span class="st">&#39;N&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;o&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;o&#39;</span>, <span class="st">&#39;O&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;p&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;p&#39;</span>, <span class="st">&#39;P&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;q&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;q&#39;</span>, <span class="st">&#39;Q&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;r&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;r&#39;</span>, <span class="st">&#39;R&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;s&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;s&#39;</span>, <span class="st">&#39;S&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;t&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;t&#39;</span>, <span class="st">&#39;T&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;u&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;u&#39;</span>, <span class="st">&#39;U&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;v&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;v&#39;</span>, <span class="st">&#39;V&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;w&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;w&#39;</span>, <span class="st">&#39;W&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;x&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;x&#39;</span>, <span class="st">&#39;X&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;y&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;y&#39;</span>, <span class="st">&#39;Y&#39;</span>);
      <span class="kw">WHEN</span> letter = <span class="st">&#39;z&#39;</span> <span class="kw">THEN</span> <span class="kw">SET</span> letter = <span class="kw">IF</span>(is_lower, <span class="st">&#39;z&#39;</span>, <span class="st">&#39;Z&#39;</span>);
      <span class="kw">ELSE</span>
        <span class="kw">SET</span> letter = letter;
    <span class="kw">END</span> <span class="kw">CASE</span>;

    <span class="co">-- CONCAT seems to ignore the whitespace character. As a workaround we use</span>
    <span class="co">-- CONCAT_WS with a whitespace separator when the letter is a whitespace.</span>
    <span class="kw">SET</span> translit = CONCAT_WS(<span class="kw">IF</span>(letter = <span class="st">&#39; &#39;</span>, <span class="st">&#39; &#39;</span>, <span class="st">&#39;&#39;</span>), translit, letter);
    <span class="kw">SET</span> pos = pos + <span class="dv">1</span>;
  <span class="kw">END</span> WHILE;

  <span class="kw">RETURN</span> translit;

<span class="kw">END</span> $

DELIMITER ;</code></pre>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Fri, 13 Feb 2009 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2009-02-13-mysql-transliteration-function.html</guid>
</item>
<item>
    <title>Ajax file upload with pure JavaScript</title>
    <link>http://igstan.ro/posts/2009-01-11-ajax-file-upload-with-pure-javascript.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Ajax file upload with pure JavaScript</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Ajax file upload with pure JavaScript</h1>
    <time pubdate>January 11, 2009</time>
    <div class="warning">
Warning! Outdated article.
</div>

<h2 id="update">Update</h2>
<p>The API I wrote about in this article has been removed from recent versions of Firefox. Instead, you can now use a <a href="https://developer.mozilla.org/en/DOM/FileReader"><code>FileReader</code></a> object to read files on the client, and a <a href="https://developer.mozilla.org/en/XMLHttpRequest/FormData"><code>FormData</code></a> object to serialize such file values and POST them using asynchronous requests. These two objects are also available in Chrome and Safari, possible other browsers too. However, I’ll keep the old article here for posterity. Here goes.</p>
<h2 id="old-article">Old Article</h2>
<p>I don’t know about you, but there’s one little thing I’ve always hated about Ajax. The impossibility of file uploading. I still remember the ugly day when I discovered the terrible truth. There was no chance on earth you could send a file using an <code>XMLHttpRequest</code>, thus workarounds appeared. Google made use of a hidden iframe to imitate such an asynchronous call for their Gmail service, and later on, Flash based uploaders appeared. Things are though going forward.</p>
<p>Firefox 3 introduced a new <abbr title="Application Programming Interface">API</abbr>, that few people know about, which allows JavaScript to read local files selected by an user from a form file-upload dialog. A copy of Firefox 3 with default settings offers full access to this new programming interface. So we’ll embrace the challenge and write a little JavaScript uploader on top of this new <abbr title="Application Programming Interface">API</abbr>.</p>
<p>However, if you’re not into reading this long article, just go ahead and look at the complete source code in my <a href="https://github.com/igstan/ajax-file-upload">GitHub repo</a>.</p>
<h2 id="goal">Goal</h2>
<p>In this tutorial we’ll write a little application that is able to read and upload local files to a remote web server using an asynchronous <abbr title="HyperText Transfer Protocol">HTTP</abbr> request. The whole application consists of three parts:</p>
<ul>
<li>the client side comprised of JavaScript, <abbr title="HyperText Markup Language">HTML</abbr> and a little <abbr title="Cascading Style Sheets">CSS</abbr></li>
<li>the server side script, written in PHP</li>
<li>the communication channel in between them, old good <abbr title="HyperText Transfer Protocol">HTTP</abbr></li>
</ul>
<p>We’ll start with the JavaScript side, as I’m sure you’re eager to find about the new file access <abbr title="Application Programming Interface">API</abbr>, then we’ll review the <code>XMLHttpRequest</code> object as available in Firefox version 3 (it got enhanced with a new method). After the client-side part follows explanations for the server-side script, written in PHP, continued with a little summary over the <abbr title="HyperText Transfer Protocol">HTTP</abbr> protocol concerning data transmission and <abbr title="HyperText Markup Language">HTML</abbr> forms. Finally, we’ll put all these together to build a powerful asynchronous file uploader.</p>
<h2 id="the-firefox-file-upload-api">The Firefox file upload <abbr title="Application Programming Interface">API</abbr></h2>
<p>When Firefox 3 has been launched in June this year, we heard a lot about the improvements it brought to the web development field by further implementing existing standards and technologies like <abbr title="HyperText Markup Language">HTML</abbr>, <abbr title="Cascading Style Sheets">CSS</abbr> and JavaScript. One thing I have never seen mentioned was the interface for reading local files, provided the file is chosen by the user through an <abbr title="HyperText Markup Language">HTML</abbr> file input element. For example, a simple Google search for getAsBinary, one of the new methods in the <abbr title="Application Programming Interface">API</abbr>, will give you few results, even when counting the false positives (such a false positive is related to ColdFusion which has a similar method name, and results comprising information about it are preponderant). That surprises me a lot as, in my opinion, it is a huge step forward in building more powerful web applications. Actually, there is <a href="http://soakedandsoaped.com/articles/read/firefox-3-native-ajax-file-upload">someone</a> that wrote about it in May 2008. Alas the news hasn’t spread. With this new <abbr title="Application Programming Interface">API</abbr>, each input element (not only file input elements), is given a property called files. This property is our gateway to reading local files. When the type attribute of the input element isn’t file, the value of the files property is null. On the other hand, for input elements whose type attribute is file, the files property is of type <code>FileList</code> and resembles a <code>NodeList</code> object returned by, let’s say, <code>document.getElementsByTagName()</code>. You may access it as if it were an <code>Array</code> and has the following properties and methods:</p>
<ul>
<li><code>length</code></li>
<li><code>item(index)</code></li>
</ul>
<p>Each element in the files property is a File element that exposes the following properties and methods:</p>
<ul>
<li><code>fileName</code></li>
<li><code>fileSize</code></li>
<li><code>getAsBinary()</code></li>
<li><code>getAsText(encoding)</code></li>
<li><code>getAsDataURL()</code></li>
</ul>
<p>Those two lists above are all there is to know about the <abbr title="Application Programming Interface">API</abbr> for reading local files. There is nothing more about it. No security restrictions, no special configurations. As I’m sure the files property itself poses no problem in understanding its interface let’s review the contained file objects with a little script. You may want to download <a href="https://addons.mozilla.org/en-US/firefox/addon/1843">Firebug</a> in order to get a thorough understanding of the following exploration. Here’s the code that we’ll use:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="dt">&lt;!DOCTYPE </span>html<span class="dt">&gt;</span>

<span class="kw">&lt;html&gt;</span>
<span class="kw">&lt;head&gt;</span>
<span class="kw">&lt;title&gt;</span>JavaScript file upload<span class="kw">&lt;/title&gt;</span>
<span class="kw">&lt;meta</span><span class="ot"> http-equiv=</span><span class="st">&quot;content-type&quot;</span><span class="ot"> content=</span><span class="st">&quot;text/html; charset=UTF-8&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> type=</span><span class="st">&quot;text/javascript&quot;</span><span class="kw">&gt;</span>
<span class="kw">var</span> upload = <span class="kw">function</span>() {
    <span class="kw">var</span> photo = <span class="kw">document</span>.<span class="fu">getElementById</span>(<span class="st">&quot;photo&quot;</span>);
    <span class="kw">return</span> <span class="kw">false</span>;
};
<span class="kw">&lt;/script&gt;</span>
<span class="kw">&lt;/head&gt;</span>
<span class="kw">&lt;body&gt;</span>

<span class="kw">&lt;form</span><span class="ot"> action=</span><span class="st">&quot;/&quot;</span><span class="ot"> method=</span><span class="st">&quot;post&quot;</span><span class="ot"> onsubmit=</span><span class="st">&quot;return upload();&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;fieldset&gt;</span>
    <span class="kw">&lt;legend&gt;</span>Upload photo<span class="kw">&lt;/legend&gt;</span>
    <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;file&quot;</span><span class="ot"> name=</span><span class="st">&quot;photo&quot;</span><span class="ot"> id=</span><span class="st">&quot;photo&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;submit&quot;</span><span class="ot"> value=</span><span class="st">&quot;Upload&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;/fieldset&gt;</span>
<span class="kw">&lt;/form&gt;</span>

<span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>
<p>The <code>fileName</code> property gives us the name of the picked up file, but not the absolute path on the filesystem, just the basename. Modify the above source code above so that the JavaScript part now becomes:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> upload = <span class="kw">function</span>() {
    <span class="kw">var</span> photo = <span class="kw">document</span>.<span class="fu">getElementById</span>(<span class="st">&quot;photo&quot;</span>);
    <span class="co">// the file is the first element in the files property</span>
    <span class="kw">var</span> file = <span class="kw">photo</span>.<span class="fu">files</span>[<span class="dv">0</span>];

    <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;File name: &quot;</span> + <span class="kw">file</span>.<span class="fu">fileName</span>);
    <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;File name: &quot;</span> + <span class="kw">file</span>.<span class="fu">fileSize</span>);

    <span class="kw">return</span> <span class="kw">false</span>;
};</code></pre>
<p>The <code>getAsBinary()</code> method will read the contents of the file and return them in binary representation. If you select a binary file, an image for example, you should see some weird characters, question marks or even rectangles in the alert, this is how Firefox represents the bytes contained in the file. For a text file it will simply output its text.</p>
<p>The <code>getAsText(encoding)</code> method will return the contents as a string of bytes encoded depending on the encoding parameter. This is by default UTF-8, but the encoding parameter it’s not really optional. You still have to pass some value. An empty string will do it just fine:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> upload = <span class="kw">function</span>() {
    <span class="kw">var</span> photo = <span class="kw">document</span>.<span class="fu">getElementById</span>(<span class="st">&quot;photo&quot;</span>);
    <span class="co">// the file is the first element in the files property</span>
    <span class="kw">var</span> file = <span class="kw">photo</span>.<span class="fu">files</span>[<span class="dv">0</span>];

    <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;File name: &quot;</span> + <span class="kw">file</span>.<span class="fu">fileName</span>);
    <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;File size: &quot;</span> + <span class="kw">file</span>.<span class="fu">fileSize</span>);
    <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Binary content: &quot;</span> + <span class="kw">file</span>.<span class="fu">getAsBinary</span>());
    <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Text content: &quot;</span> + <span class="kw">file</span>.<span class="fu">getAsText</span>(<span class="st">&quot;&quot;</span>));
    <span class="co">// or</span>
    <span class="co">// console.log(&quot;Text content: &quot; + file.getAsText(&quot;utf8&quot;));</span>

    <span class="kw">return</span> <span class="kw">false</span>;
};</code></pre>
<p>Finally, the <code>getAsDataURL()</code> method, a very interesting and very useful one, will return the file contents in a format ideally suited for, let’s say, the src attribute of an <code>IMG</code> tag. Of course, this will work as we’re in Firefox right now, so let’s add a <code>IMG</code> tag to the <abbr title="HyperText Markup Language">HTML</abbr> source and the appropriate JavaScript code to make this work:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="dt">&lt;!DOCTYPE </span>html<span class="dt">&gt;</span>

<span class="kw">&lt;html&gt;</span>
<span class="kw">&lt;head&gt;</span>
<span class="kw">&lt;title&gt;</span>JavaScript file upload<span class="kw">&lt;/title&gt;</span>
<span class="kw">&lt;meta</span><span class="ot"> http-equiv=</span><span class="st">&quot;content-type&quot;</span><span class="ot"> content=</span><span class="st">&quot;text/html; charset=UTF-8&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> type=</span><span class="st">&quot;text/javascript&quot;</span><span class="kw">&gt;</span>
<span class="kw">var</span> upload = <span class="kw">function</span>() {
    <span class="kw">var</span> photo = <span class="kw">document</span>.<span class="fu">getElementById</span>(<span class="st">&quot;photo&quot;</span>);
    <span class="kw">var</span> file = <span class="kw">photo</span>.<span class="fu">files</span>[<span class="dv">0</span>];

    <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;File</span> <span class="st">name</span>: <span class="st">&quot;</span> + <span class="kw">file</span>.<span class="fu">fileName</span>);
    <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;File</span> <span class="st">size</span>: <span class="st">&quot;</span> + <span class="kw">file</span>.<span class="fu">fileSize</span>);
    <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Binary</span> <span class="st">content</span>: <span class="st">&quot;</span> + <span class="kw">file</span>.<span class="fu">getAsBinary</span>());
    <span class="kw">console</span>.<span class="fu">log</span>(<span class="st">&quot;Text</span> <span class="st">content</span>: <span class="st">&quot;</span> + <span class="kw">file</span>.<span class="fu">getAsText</span>(<span class="st">&quot;&quot;</span>));

    <span class="kw">var</span> preview = <span class="kw">document</span>.<span class="fu">getElementById</span>(<span class="st">&quot;preview&quot;</span>);
    <span class="kw">preview</span>.<span class="fu">src</span> = <span class="kw">file</span>.<span class="fu">getAsDataURL</span>();

    <span class="kw">return</span> <span class="kw">false</span>;
};
<span class="kw">&lt;/script&gt;</span>
<span class="kw">&lt;/head&gt;</span>
<span class="kw">&lt;body&gt;</span>

<span class="kw">&lt;form</span><span class="ot"> action=</span><span class="st">&quot;/&quot;</span><span class="ot"> method=</span><span class="st">&quot;post&quot;</span><span class="ot"> onsubmit=</span><span class="st">&quot;return upload();&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;fieldset&gt;</span>
    <span class="kw">&lt;legend&gt;</span>Upload photo<span class="kw">&lt;/legend&gt;</span>
    <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;file&quot;</span><span class="ot"> name=</span><span class="st">&quot;photo&quot;</span><span class="ot"> id=</span><span class="st">&quot;photo&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;submit&quot;</span><span class="ot"> value=</span><span class="st">&quot;Upload&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;hr&gt;</span>
    <span class="kw">&lt;img</span><span class="ot"> src=</span><span class="st">&quot;&quot;</span><span class="ot"> alt=</span><span class="st">&quot;Image preview&quot;</span><span class="ot"> id=</span><span class="st">&quot;preview&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;/fieldset&gt;</span>
<span class="kw">&lt;/form&gt;</span>

<span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>
<p>More information about the new <abbr title="Application Programming Interface">API</abbr> can be found on their dedicated pages on Mozilla Developer Center:</p>
<ul>
<li><a href="https://developer.mozilla.org/en/nsIDOMFileList">https://developer.mozilla.org/en/nsIDOMFileList</a></li>
<li><a href="https://developer.mozilla.org/en/nsIDOMFile">https://developer.mozilla.org/en/nsIDOMFile</a></li>
</ul>
<h3 id="some-extra-information">Some extra information</h3>
<p>You may wonder why an array of files for just one input element. It turns out that <a href="http://www.faqs.org/rfcs/rfc1867.html"><abbr title="Request for Comments">RFC</abbr> 1867</a>, concerning form-based file uploads, specifies that a file input element allows its size attribute to receive a complex value:</p>
<blockquote>
<p>The <code>SIZE</code> attribute might be specified using <code>SIZE=width,height</code>, where width is some default for file name width, while height is the expected size showing the list of selected files. For example, this would be useful for forms designers who expect to get several files and who would like to show a multiline file input field in the browser (with a “browse” button beside it, hopefully). It would be useful to show a one line text field when no height is specified (when the forms designer expects one file, only) and to show a multiline text area with scrollbars when the height is greater than 1 (when the forms designer expects multiple files).</p>
</blockquote>
<p>None of the browsers I tested this in seems to obey the <abbr title="Request for Comments">RFC</abbr>, nevertheless this should be the reason for which the files property is an array-like object.</p>
<h2 id="the-xmlhttprequest-object">The XMLHttpRequest object</h2>
<p>Now that we’re able to read local files, we need a way to get this data, over the network, to the server. As we’re aiming for an asynchronous data transmission, an <code>XMLHttpRequest</code> object should do the job just fine. Unfortunately, its <code>send()</code> method isn’t that reliable in sending binary data. For this reason, along with the local file access interface, Firefox 3 brought a new method to the <code>XMLHttpRequest</code> object: <code>sendAsBinary(data)</code>. Just as the <code>send()</code> method, the new one takes a single argument, a string, which is converted to a string of single-byte characters by truncation (removing the high-order byte of each character), according to the <a href="https://developer.mozilla.org/en/XMLHttpRequest#sendAsBinary%28%29">documentation</a>. The difference, a very important one, is that, as long as <code>send()</code> knows how to process an <abbr title="Uniform Resource Locator">URL</abbr> query string, <code>sendAsBinary()</code> expects a totally different format in order to be useful for the server-side end of the application, but we’ll talk about this a little bit later. Let’s just write a little JavaScript skeleton, that we’ll use when assembling together all the pieces of the application:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="dt">send</span>: <span class="kw">function</span> () {
    <span class="kw">var</span> boundary = <span class="kw">this</span>.<span class="fu">generateBoundary</span>();
    <span class="kw">var</span> xhr = <span class="kw">new</span> XMLHttpRequest;

    <span class="kw">xhr</span>.<span class="fu">open</span>(<span class="st">&quot;POST&quot;</span>, <span class="kw">this</span>.<span class="fu">form</span>.<span class="fu">action</span>, <span class="kw">true</span>);
    <span class="kw">xhr</span>.<span class="fu">onreadystatechange</span> = <span class="kw">function</span>() {
        <span class="kw">if</span> (<span class="kw">xhr</span>.<span class="fu">readyState</span> === <span class="dv">4</span>) {
            alert(<span class="kw">xhr</span>.<span class="fu">responseText</span>);
        }
    };
    <span class="kw">var</span> contentType = <span class="st">&quot;multipart/form-data; boundary=&quot;</span> + boundary;
    <span class="kw">xhr</span>.<span class="fu">setRequestHeader</span>(<span class="st">&quot;Content-Type&quot;</span>, contentType);

    <span class="kw">for</span> (<span class="kw">var</span> header <span class="kw">in</span> <span class="kw">this</span>.<span class="fu">headers</span>) {
        <span class="kw">xhr</span>.<span class="fu">setRequestHeader</span>(header, headers[header]);
    }

    <span class="co">// here&#39;s our data variable that we talked about earlier</span>
    <span class="kw">var</span> data = <span class="kw">this</span>.<span class="fu">buildMessage</span>(<span class="kw">this</span>.<span class="fu">elements</span>, boundary);

    <span class="co">// finally send the request as binary data</span>
    <span class="kw">xhr</span>.<span class="fu">sendAsBinary</span>(data);
}</code></pre>
<p>As you see, there’s an undefined variable in the above snippet, data, which remains to be defined after we review the mechanism behind files upload over <abbr title="HyperText Transfer Protocol">HTTP</abbr>. For the moment though, I want to talk about the server-side part, as it will guide us in choosing the appropriate strategy for sending binary information.</p>
<h2 id="the-server-side-script">The server-side script</h2>
<p>PHP, as well as several web frameworks made on top of other languages, offers different access points for reading POST data containing uploaded files and POST data containing just simple values. In PHP there are two predefined arrays giving you access to simple POST data, the <code>$_POST</code> array, and another one for accessing files sent to the server, the <code>$_FILES</code> array. It is thus wise to build a client-side script able to send information that PHP would read as from a classical request issued with an <abbr title="HyperText Markup Language">HTML</abbr> form: our uploaded files would appear as elements inside the <code>$_FILES</code> array and additional values as elements inside the <code>$_POST</code> array. Under these circumstances we can write the PHP script to test that our JavaScript client is performing well:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="fu">print_r</span><span class="ot">(</span><span class="kw">$_FILES</span><span class="ot">);</span>
<span class="fu">print_r</span><span class="ot">(</span><span class="kw">$_POST</span><span class="ot">);</span></code></pre>
<p>That’s all we need on the server. Although simple this we’ll give us valuable feedback about the sent data. The PHP script should list our uploaded files inside the <code>$_FILES</code> array and any additional form data (like text <code>INPUT</code> or <code>SELECT</code> element) inside the <code>$_POST</code> array.</p>
<h2 id="form-data-over-http-theory">Form data over <abbr title="HyperText Transfer Protocol">HTTP</abbr> theory</h2>
<p>As we saw, PHP treats POST-ed files differently than ordinary form field values, so it’s only natural to ask ourselves what’s the “clue” that helps PHP tell apart one from the other.</p>
<p>First of all, every <abbr title="HyperText Markup Language">HTML</abbr> form element out there has an optional attribute called <em>enctype</em>, with a default value of <code>application/x-www-form-urlencoded</code>. This is actually a <abbr title="Multipurpose Internet Mail Extensions">MIME</abbr> type value specifying the encoding to be used by the web browser when sending form data. It also guides the web server script in decoding that data as the encoding is sent by the browser to the server in the form of an <abbr title="HyperText Transfer Protocol">HTTP</abbr> header, called <code>Content-Type</code>. For a default enctype value, form data is sent as <abbr title="American Standard Code for Information Interchange">ASCII</abbr> characters, <abbr title="Uniform Resource Locator">URL</abbr> encoded when necessary. On the other hand, when uploading files, we need to change the enconding to <code>multipart/form-data</code>. Cloning this basic form functionality inside our JavaScript client is what we should do. Let’s modify the earlier script so that it sends such a <code>multipart/form-data</code> header:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> xhr = <span class="kw">new</span> XMLHttpRequest;
<span class="kw">xhr</span>.<span class="fu">onreadystatechange</span> = <span class="kw">function</span>() {
    <span class="kw">if</span> (<span class="kw">xhr</span>.<span class="fu">readyState</span> === <span class="dv">4</span>) {
        alert(<span class="kw">xhr</span>.<span class="fu">responseText</span>);
    }
};
<span class="kw">xhr</span>.<span class="fu">setRequestHeader</span>(<span class="st">&quot;Content-Type&quot;</span>, <span class="st">&quot;multipart/form-data&quot;</span>);
<span class="kw">xhr</span>.<span class="fu">sendAsBinary</span>(data);</code></pre>
<p><abbr title="Request for Comments">RFC</abbr> 1867, regarding form-based file uploads, dictates that an extra parameter is required for the <code>Content-Type</code> header when its value is <code>multipart/form-data</code>. It is called boundary and its presence it’s very logical. The multipart word inside the header means the sent request is formed of multiple parts (obviously), so there must be something to separate those parts. This thing is the boundary parameter which value must be a string of characters that shouldn’t be found inside any of the form values we send, otherwise the request will get garbled. Once again, let’s modify the script to reflect this requirement.</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> xhr = <span class="kw">new</span> XMLHttpRequest;
<span class="kw">xhr</span>.<span class="fu">onreadystatechange</span> = <span class="kw">function</span>() {
    <span class="kw">if</span> (<span class="kw">xhr</span>.<span class="fu">readyState</span> === <span class="dv">4</span>) {
        alert(<span class="kw">xhr</span>.<span class="fu">responseText</span>);
    }
};

<span class="co">/*</span>
<span class="co"> * The value of the boundary doesn&#39;t matter as long as no other structure in</span>
<span class="co"> * the request contains such a sequence of characters. We chose, nevertheless,</span>
<span class="co"> * a pseudo-random value based on the current timestamp of the browser.</span>
<span class="co"> */</span>
<span class="kw">var</span> boundary = <span class="st">&quot;AJAX--------------&quot;</span> + (<span class="kw">new</span> <span class="kw">Date</span>).<span class="fu">getTime</span>();
<span class="kw">var</span> contentType = <span class="st">&quot;multipart/form-data; boundary=&quot;</span> + boundary;
<span class="kw">xhr</span>.<span class="fu">setRequestHeader</span>(<span class="st">&quot;Content-Type&quot;</span>, contentType);
<span class="kw">xhr</span>.<span class="fu">sendAsBinary</span>(data);</code></pre>
<p>Next, let’s talk about the structure of the parts comprised in the request. Each of these is like a little request on its own. Each has its own headers structure and body.</p>
<p>The mandatory header, every part must have, is called <code>Content-Disposition</code> and its value should be form-data followed by an additional parameter called name, which represents the name of the form input that holds the data. In case of parts holding uploaded files, a second parameter must also be present, called filename. This is the name of the file as it was on the user’s computer. Not the absolute path, just the basename (for example, monkey.png). Parameter values are enclosed inside double quotes. A little example:</p>
<pre><code>Content-Disposition: form-data; name=&quot;photo&quot;; filename=&quot;monkey.png&quot;</code></pre>
<p>In the case of files, a second header must is also needed. It is called <code>Content-Type</code> and specifies the <abbr title="Multipurpose Internet Mail Extensions">MIME</abbr> type of the file. This may be deduced by reading the file extension or the source of the file. Anyway, a general value of <code>application/octet-stream</code> is perfectly acceptable:</p>
<pre><code>Content-Disposition: form-data; name=&quot;photo&quot;; filename=&quot;monkey.png&quot;
Content-Type: image/png</code></pre>
<p>As per the <a href="http://www.faqs.org/rfcs/rfc822.html">standards</a>, every such header should end with two characters, a carriage return and a new line: <code>CR</code> and <code>LF</code>. The last header doubles this sequence (i.e. it ends with <code>CRLFCRLF</code>).</p>
<p>Following the headers is the body which consists of the form field value. I’ll illustrate with a simple text file upload, although it could be any type of file. The text inside the file is “my random notes about web programming”:</p>
<pre><code>Content-Disposition: form-data; name=&quot;notes&quot;; filename=&quot;my_notes.txt&quot;
Content-Type: text/plain

my random notes about web programming</code></pre>
<p>Finally I’ll give you a final example with both the <abbr title="HyperText Markup Language">HTML</abbr> markup of the form as well as a fictional request from that form:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="kw">&lt;form</span><span class="ot"> action=</span><span class="st">&quot;upload.php&quot;</span><span class="ot"> method=</span><span class="st">&quot;post&quot;</span><span class="ot"> enctype=</span><span class="st">&quot;multipart/form-data&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;fieldset&gt;</span>
    <span class="kw">&lt;legend&gt;</span>Upload photo<span class="kw">&lt;/legend&gt;</span>
    <span class="kw">&lt;label</span><span class="ot"> for=</span><span class="st">&quot;image_name&quot;</span><span class="kw">&gt;</span>Image name:<span class="kw">&lt;/label&gt;</span>
    <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;text&quot;</span><span class="ot"> name=</span><span class="st">&quot;image_name&quot;</span><span class="ot"> id=</span><span class="st">&quot;image_name&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;select</span><span class="ot"> name=</span><span class="st">&quot;image_type&quot;</span><span class="kw">&gt;</span>
      <span class="kw">&lt;option&gt;</span>Family<span class="kw">&lt;/option&gt;</span>
      <span class="kw">&lt;option&gt;</span>Work<span class="kw">&lt;/option&gt;</span>
      <span class="kw">&lt;option&gt;</span>Vacation<span class="kw">&lt;/option&gt;</span>
    <span class="kw">&lt;/select&gt;</span>
    <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;file&quot;</span><span class="ot"> name=</span><span class="st">&quot;photo&quot;</span><span class="ot"> id=</span><span class="st">&quot;photo&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;submit&quot;</span><span class="ot"> value=</span><span class="st">&quot;Upload&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;/fieldset&gt;</span>
<span class="kw">&lt;/form&gt;</span></code></pre>
<p>The issued request could be:</p>
<pre><code>Content-Type: multipart/form-data; boundary=RANDOM_STRING_BOUNDARY
--RANDOM_STRING_BOUNDARY
Content-Disposition: form-data; name=&quot;image_name&quot;

Monkey
--RANDOM_STRING_BOUNDARY
Content-Disposition: form-data; name=&quot;image_type&quot;

Vacation
--RANDOM_STRING_BOUNDARY
Content-Disposition: form-data; name=&quot;photo&quot;; filename=&quot;monkey.png&quot;
Content-Type: image/png

[ here would be the png file in binary form ]
--RANDOM_STRING_BOUNDARY--</code></pre>
<p>In case you didn’t noticed, the boundary, when used in between the parts is prepended with two hyphens and the last one appended with also two hyphens. Don’t forget about this, it’s an ugly source of bugs.</p>
<h2 id="encapsulating-the-javascript-logic">Encapsulating the JavaScript logic</h2>
<p>At this point we know all the parts to successfully build a pure JavaScript file uploader, which we’re going to implement as an object. Here’s the basic structure of the constructor and its prototype:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">/**</span>
<span class="co"> * @param DOMNode form</span>
<span class="co"> */</span>
<span class="kw">var</span> Uploader = <span class="kw">function</span>(form) {
    <span class="kw">this</span>.<span class="fu">form</span> = form;
};

<span class="kw">Uploader</span>.<span class="fu">prototype</span> = {
    <span class="co">/**</span>
<span class="co">     * @param Object HTTP headers to send to the server, the key is the</span>
<span class="co">     * header name, the value is the header value</span>
<span class="co">     */</span>
    <span class="dt">headers </span>: {},

    <span class="co">/**</span>
<span class="co">     * @return Array of DOMNode elements</span>
<span class="co">     */</span>
    get elements() {},

    <span class="co">/**</span>
<span class="co">     * @return String A random string</span>
<span class="co">     */</span>
    <span class="dt">generateBoundary</span>: <span class="kw">function</span>() {},

    <span class="co">/**</span>
<span class="co">     * Constructs the message as discussed in the section about form</span>
<span class="co">     * data transmission over HTTP</span>
<span class="co">     *</span>
<span class="co">     * @param Array elements</span>
<span class="co">     * @param String boundary</span>
<span class="co">     * @return String</span>
<span class="co">     */</span>
    <span class="dt">buildMessage </span>: <span class="kw">function</span>(elements, boundary) {},

    <span class="co">/**</span>
<span class="co">     * @return null</span>
<span class="co">     */</span>
    <span class="dt">send </span>: <span class="kw">function</span>() {}
};</code></pre>
<p>In case you didn’t understand the <code>elements()</code> construct, this is called a getter and is supported by the latest versions of Firefox, Opera, Safari and Chrome. A setter form is also provided. You can find more about these on <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Creating_New_Objects/Defining_Getters_and_Setters">Mozilla Developer Center</a>.</p>
<p>We should fill the above methods, so let’s start with the <code>send()</code> method because we already wrote much of it in a previous sections of the tutorial:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">/**</span>
<span class="co"> * @return null</span>
<span class="co"> */</span>
<span class="dt">send </span>: <span class="kw">function</span>() {
    <span class="kw">var</span> boundary = <span class="kw">this</span>.<span class="fu">generateBoundary</span>();
    <span class="kw">var</span> xhr = <span class="kw">new</span> XMLHttpRequest;

    <span class="kw">xhr</span>.<span class="fu">open</span>(<span class="st">&quot;POST&quot;</span>, <span class="kw">this</span>.<span class="fu">form</span>.<span class="fu">action</span>, <span class="kw">true</span>);
    <span class="kw">xhr</span>.<span class="fu">onreadystatechange</span> = <span class="kw">function</span>() {
        <span class="kw">if</span> (<span class="kw">xhr</span>.<span class="fu">readyState</span> === <span class="dv">4</span>) {
            alert(<span class="kw">xhr</span>.<span class="fu">responseText</span>);
        }
    };
    <span class="kw">var</span> contentType = <span class="st">&quot;multipart/form-data; boundary=&quot;</span> + boundary;
    <span class="kw">xhr</span>.<span class="fu">setRequestHeader</span>(<span class="st">&quot;Content-Type&quot;</span>, contentType);

    <span class="kw">for</span> (<span class="kw">var</span> header <span class="kw">in</span> <span class="kw">this</span>.<span class="fu">headers</span>) {
        <span class="kw">xhr</span>.<span class="fu">setRequestHeader</span>(header, headers[header]);
    }

    <span class="co">// here&#39;s our data variable that we talked about earlier</span>
    <span class="kw">var</span> data = <span class="kw">this</span>.<span class="fu">buildMessage</span>(<span class="kw">this</span>.<span class="fu">elements</span>, boundary);

    <span class="co">// finally send the request as binary data</span>
    <span class="kw">xhr</span>.<span class="fu">sendAsBinary</span>(data);
}</code></pre>
<p>In addition to what we had earlier we have now introduced an iteration that allows us to send additional headers without modifying the prototype itself. We have also defined the variable we talked about earlier, data, which holds the source of the <abbr title="HyperText Transfer Protocol">HTTP</abbr> request. It holds the value returned by a call to a method whose only purpose is to build an <abbr title="HyperText Transfer Protocol">HTTP</abbr> compliant request for file uploads. Here’s its source:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">/**</span>
<span class="co"> * @param Array elements</span>
<span class="co"> * @param String boundary</span>
<span class="co"> * @return String</span>
<span class="co"> */</span>
<span class="dt">buildMessage </span>: <span class="kw">function</span>(elements, boundary) {
    <span class="kw">var</span> CRLF = <span class="st">&quot;</span><span class="ch">\r\n</span><span class="st">&quot;</span>;
    <span class="kw">var</span> parts = [];

    <span class="kw">elements</span>.<span class="fu">forEach</span>(<span class="kw">function</span>(element, index, all) {
        <span class="kw">var</span> part = <span class="st">&quot;&quot;</span>;
        <span class="kw">var</span> type = <span class="st">&quot;TEXT&quot;</span>;

        <span class="kw">if</span> (<span class="kw">element.nodeName</span>.<span class="fu">toUpperCase</span>() === <span class="st">&quot;INPUT&quot;</span>) {
            type = <span class="kw">element</span>.<span class="fu">getAttribute</span>(<span class="st">&quot;type&quot;</span>).<span class="fu">toUpperCase</span>();
        }

        <span class="kw">if</span> (type === <span class="st">&quot;FILE&quot;</span> &amp;&amp; <span class="kw">element.files</span>.<span class="fu">length</span> &gt; <span class="dv">0</span>) {
            <span class="kw">var</span> fieldName = <span class="kw">element</span>.<span class="fu">name</span>;
            <span class="kw">var</span> fileName = <span class="kw">element</span>.<span class="fu">files</span>[<span class="dv">0</span>].<span class="fu">fileName</span>;

            <span class="co">/*</span>
<span class="co">             * Content-Disposition header contains name of the field</span>
<span class="co">             * used to upload the file and also the name of the file as</span>
<span class="co">             * it was on the user&#39;s computer.</span>
<span class="co">             */</span>
            part += <span class="ch">&#39;Content-Disposition: form-data; &#39;</span>;
            part += <span class="ch">&#39;name=&quot;&#39;</span> + fieldName + <span class="ch">&#39;&quot;; &#39;</span>;
            part += <span class="ch">&#39;filename=&quot;&#39;</span>+ fileName + <span class="ch">&#39;&quot;&#39;</span> + CRLF;

            <span class="co">/*</span>
<span class="co">             * Content-Type header contains the mime-type of the file</span>
<span class="co">             * to send. Although we could build a map of mime-types</span>
<span class="co">             * that match certain file extensions, we&#39;ll take the easy</span>
<span class="co">             * approach and send a general binary header:</span>
<span class="co">             * application/octet-stream</span>
<span class="co">             */</span>
            part += <span class="st">&quot;Content-Type: application/octet-stream&quot;</span>;
            part += CRLF + CRLF; <span class="co">// marks end of the headers part</span>

            <span class="co">/*</span>
<span class="co">             * File contents read as binary data, obviously</span>
<span class="co">             */</span>
            part += <span class="kw">element</span>.<span class="fu">files</span>[<span class="dv">0</span>].<span class="fu">getAsBinary</span>() + CRLF;
       } <span class="kw">else</span> {
            <span class="co">/*</span>
<span class="co">             * In case of non-files fields, Content-Disposition</span>
<span class="co">             * contains only the name of the field holding the data.</span>
<span class="co">             */</span>
            part += <span class="ch">&#39;Content-Disposition: form-data; &#39;</span>;
            part += <span class="ch">&#39;name=&quot;&#39;</span> + <span class="kw">element</span>.<span class="fu">name</span> + <span class="ch">&#39;&quot;&#39;</span> + CRLF + CRLF;

            <span class="co">/*</span>
<span class="co">             * Field value</span>
<span class="co">             */</span>
            part += <span class="kw">element</span>.<span class="fu">value</span> + CRLF;
       }

       <span class="kw">parts</span>.<span class="fu">push</span>(part);
    });

    <span class="kw">var</span> request = <span class="st">&quot;--&quot;</span> + boundary + CRLF;
        request+= <span class="kw">parts</span>.<span class="fu">join</span>(<span class="st">&quot;--&quot;</span> + boundary + CRLF);
        request+= <span class="st">&quot;--&quot;</span> + boundary + <span class="st">&quot;--&quot;</span> + CRLF;

    <span class="kw">return</span> request;
}</code></pre>
<p>Although it looks complex, it has a fair amount of comments so that you won’t have hard times understanding what it does. It simply iterates over an array of <abbr title="HyperText Markup Language">HTML</abbr> elements and for each such an element constructs a different message depending whether the element is a file upload input or not. It pushes this message into an internal array, which is finally joined using the boundary sent as an argument inside the <code>send()</code> method.</p>
<p>Here follows the source of the <code>elements()</code> getter, used in <code>send()</code>:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">/**</span>
<span class="co"> * @return Array</span>
<span class="co"> */</span>
get elements() {
    <span class="kw">var</span> fields = [];

    <span class="co">// gather INPUT elements</span>
    <span class="kw">var</span> inputs = <span class="kw">this</span>.<span class="fu">form</span>.<span class="fu">getElementsByTagName</span>(<span class="st">&quot;INPUT&quot;</span>);
    <span class="kw">for</span> (<span class="kw">var</span> l=<span class="kw">inputs</span>.<span class="fu">length</span>, i=<span class="dv">0</span>; i
        <span class="kw">fields</span>.<span class="fu">push</span>(inputs[i]);
    }

    <span class="co">// gather SELECT elements</span>
    <span class="kw">var</span> selects = <span class="kw">this</span>.<span class="fu">form</span>.<span class="fu">getElementsByTagName</span>(<span class="st">&quot;SELECT&quot;</span>);
    <span class="kw">for</span> (<span class="kw">var</span> l=<span class="kw">selects</span>.<span class="fu">length</span>, i=<span class="dv">0</span>; i
        <span class="kw">fields</span>.<span class="fu">push</span>(selects[i]);
    }

    <span class="kw">return</span> fields;
}</code></pre>
<p>The snippet above grabs all the <code>INPUT</code> and <code>SELECT</code> elements inside the <code>FORM</code> element associated with the <code>Uploader</code> object. These elements are eventually returned into a unified array. There are, however no checks on these elements, like filtering disabled controls. Furthermore, the <abbr title="Request for Comments">RFC</abbr> specifies that a client should send form data in the same order it was rendered in the user agent. For keeping the examples as short as I could, the method above doesn’t take care of that, but the code inside the accompanying archive does.</p>
<p>The final piece of code left for presentation is the <code>generateBoundary()</code> method which must return a string unique in the body of our request. For our simple example though, the method below should be just fine:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="co">/**</span>
<span class="co"> * @return String</span>
<span class="co"> */</span>
<span class="dt">generateBoundary</span>: <span class="kw">function</span>() {
    <span class="kw">return</span> <span class="st">&quot;AJAX-----------------------&quot;</span> + (<span class="kw">new</span> <span class="kw">Date</span>).<span class="fu">getTime</span>();
}</code></pre>
<p>The code inside is building a string based on the current timestamp to which some other characters are prepended. I’m using the uppercased word “AJAX” and some dashes, but this prefix isn’t mandatory, the only condition that must be met is that the result of <code>generateBoudary()</code> should not appear anywhere else in out request except for the boundary placeholders.</p>
<p>Finally, the headers property of our object remains like it was in the skeleton. It is there so that you can append additional headers to the request, for example:</p>
<pre class="sourceCode javascript"><code class="sourceCode javascript"><span class="kw">var</span> upl = <span class="kw">new</span> Uploader(form);
<span class="kw">upl</span>.<span class="fu">headers</span>[<span class="st">&quot;X-Requested-With&quot;</span>] = <span class="st">&quot;XMLHttpRequest&quot;</span>;</code></pre>
<p>Save the source of the Uploader object in a file called “uploader.js”, we’ll use it in a few moments.</p>
<h2 id="putting-it-all-together">Putting it all together</h2>
<p>Let’s now write the final <abbr title="HyperText Markup Language">HTML</abbr> source and save it inside a file called “index.html”. Aside the markup, the code below introduces some event listeners for the “Upload” and “Preview” button:</p>
<pre class="sourceCode html"><code class="sourceCode html"><span class="dt">&lt;!DOCTYPE </span>html<span class="dt">&gt;</span>

<span class="kw">&lt;html&gt;</span>
<span class="kw">&lt;head&gt;</span>
<span class="kw">&lt;title&gt;&lt;/title&gt;</span>
<span class="kw">&lt;meta</span><span class="ot"> http-equiv=</span><span class="st">&quot;content-type&quot;</span><span class="ot"> content=</span><span class="st">&quot;text/html; charset=UTF-8&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;meta</span><span class="ot"> http-equiv=</span><span class="st">&quot;imagetoolbar&quot;</span><span class="ot"> content=</span><span class="st">&quot;false&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;meta</span><span class="ot"> http-equiv=</span><span class="st">&quot;imagetoolbar&quot;</span><span class="ot"> content=</span><span class="st">&quot;no&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;link</span><span class="ot"> rel=</span><span class="st">&quot;stylesheet&quot;</span><span class="ot"> type=</span><span class="st">&quot;text/css&quot;</span><span class="ot"> href=</span><span class="st">&quot;css/default.css&quot;</span><span class="kw">&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> type=</span><span class="st">&quot;text/javascript&quot;</span><span class="ot"> src=</span><span class="st">&quot;uploader.js&quot;</span><span class="kw">&gt;&lt;/script&gt;</span>
<span class="kw">&lt;script</span><span class="ot"> type=</span><span class="st">&quot;text/javascript&quot;</span><span class="kw">&gt;</span>
<span class="kw">window</span>.<span class="fu">addEventListener</span>(<span class="st">&quot;load&quot;</span>, <span class="kw">function</span>() {
    <span class="kw">var</span> input = <span class="kw">document</span>.<span class="fu">getElementById</span>(<span class="st">&quot;photo&quot;</span>);
    <span class="kw">var</span> img = <span class="kw">document</span>.<span class="fu">getElementById</span>(<span class="st">&quot;img&quot;</span>);
    <span class="kw">var</span> previewBtn = <span class="kw">document</span>.<span class="fu">getElementById</span>(<span class="st">&quot;preview&quot;</span>);
    <span class="kw">previewBtn</span>.<span class="fu">addEventListener</span>(<span class="st">&quot;click&quot;</span>, <span class="kw">function</span>() {
        <span class="kw">img</span>.<span class="fu">src</span> = <span class="kw">input</span>.<span class="fu">files</span>[<span class="dv">0</span>].<span class="fu">getAsDataURL</span>();
    }, <span class="kw">false</span>);

    <span class="kw">var</span> form = <span class="kw">document</span>.<span class="fu">getElementsByTagName</span>(<span class="st">&quot;form&quot;</span>)[<span class="dv">0</span>];
    <span class="kw">var</span> uploader = <span class="kw">new</span> Uploader(form);
    <span class="kw">var</span> uploadBtn = <span class="kw">document</span>.<span class="fu">getElementById</span>(<span class="st">&quot;upload&quot;</span>);

    <span class="kw">uploadBtn</span>.<span class="fu">addEventListener</span>(<span class="st">&quot;click&quot;</span>, <span class="kw">function</span>() {
        <span class="kw">uploader</span>.<span class="fu">send</span>();
    }, <span class="kw">false</span>);

}, <span class="kw">false</span>);
<span class="kw">&lt;/script&gt;</span>
<span class="kw">&lt;/head&gt;</span>
<span class="kw">&lt;body&gt;</span>

<span class="kw">&lt;form</span><span class="ot"> action=</span><span class="st">&quot;upload.php&quot;</span><span class="ot"> method=</span><span class="st">&quot;post&quot;</span>
<span class="ot">      enctype=</span><span class="st">&quot;multipart/form-data&quot;</span>
<span class="ot">      onsubmit=</span><span class="st">&quot;return false;&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;fieldset&gt;</span>
    <span class="kw">&lt;legend&gt;</span>Upload photo<span class="kw">&lt;/legend&gt;</span>
    <span class="kw">&lt;label</span><span class="ot"> for=</span><span class="st">&quot;image_name&quot;</span><span class="kw">&gt;</span>Image name:<span class="kw">&lt;/label&gt;</span>
    <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;text&quot;</span><span class="ot"> name=</span><span class="st">&quot;image_name&quot;</span><span class="ot"> id=</span><span class="st">&quot;image_name&quot;</span><span class="kw">&gt;</span> |
    <span class="kw">&lt;label</span><span class="ot"> for=</span><span class="st">&quot;image_type&quot;</span><span class="kw">&gt;</span>Image type:<span class="kw">&lt;/label&gt;</span>
    <span class="kw">&lt;select</span><span class="ot"> name=</span><span class="st">&quot;image_type&quot;</span><span class="ot"> id=</span><span class="st">&quot;image_type&quot;</span><span class="kw">&gt;</span>
      <span class="kw">&lt;option&gt;</span>JPEG<span class="kw">&lt;/option&gt;</span>
      <span class="kw">&lt;option&gt;</span>PNG<span class="kw">&lt;/option&gt;</span>
      <span class="kw">&lt;option&gt;</span>GIF<span class="kw">&lt;/option&gt;</span>
    <span class="kw">&lt;/select&gt;</span> |
    <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;file&quot;</span><span class="ot"> name=</span><span class="st">&quot;photo&quot;</span><span class="ot"> id=</span><span class="st">&quot;photo&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;submit&quot;</span><span class="ot"> value=</span><span class="st">&quot;Upload&quot;</span><span class="ot"> id=</span><span class="st">&quot;upload&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;input</span><span class="ot"> type=</span><span class="st">&quot;submit&quot;</span><span class="ot"> value=</span><span class="st">&quot;Preview&quot;</span><span class="ot"> id=</span><span class="st">&quot;preview&quot;</span><span class="kw">&gt;</span>
    <span class="kw">&lt;hr&gt;</span>
    <span class="kw">&lt;img</span><span class="ot"> src=</span><span class="st">&quot;&quot;</span><span class="ot"> alt=</span><span class="st">&quot;image preview&quot;</span><span class="ot"> id=</span><span class="st">&quot;img&quot;</span><span class="kw">&gt;</span>
  <span class="kw">&lt;/fieldset&gt;</span>
<span class="kw">&lt;/form&gt;</span>

<span class="kw">&lt;/body&gt;</span>
<span class="kw">&lt;/html&gt;</span></code></pre>
<p>Now create another file, save it as upload.php, and write inside it the code we presented in the server-side section of the tutorial:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="fu">print_r</span><span class="ot">(</span><span class="kw">$_FILES</span><span class="ot">);</span>
<span class="fu">print_r</span><span class="ot">(</span><span class="kw">$_POST</span><span class="ot">);</span></code></pre>
<p>That’s all. You may now test the application, which will hopefully work from the first run. Don’t forget to install Firebug to inspect what’s happening behind the scenes.</p>
<h2 id="conclusion">Conclusion</h2>
<p>There’s probably a lot to be discussed around this new feature Mozilla introduced along with Firefox 3. Some may wonder if it is worth using it. Well, as ever, it depends on what you want to accomplish. You may employ fall back techniques (like the iframe workaround) in order to have support for other browsers, if that is your concern. If you want a fancy <abbr title="User Interface">UI</abbr> though, a Flash based uploader may be better. But don’t forget, the new <abbr title="Application Programming Interface">API</abbr> is not all about uploading. You may now read local files and process them right there in the browser. You may resize images, parse <abbr title="eXtensible Markup Language">XML</abbr> or do whatever your imagination limits are. In my opinion this is a huge step forward for web development and I’d really like other browser vendors to implement this <abbr title="Application Programming Interface">API</abbr> as <a href="http://www.w3.org/TR/file-upload/">the standards</a> seem to be abandoned. Rich Internet applications would be far more powerful and their responsiveness further increased.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Sun, 11 Jan 2009 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2009-01-11-ajax-file-upload-with-pure-javascript.html</guid>
</item>
<item>
    <title>My first contribution to an open source project</title>
    <link>http://igstan.ro/posts/2009-01-05-my-first-contribution-to-an-open-source-project.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>My first contribution to an open source project</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>My first contribution to an open source project</h1>
    <time pubdate>January 05, 2009</time>
    <p>Two weeks ago, while writing some unit tests for one of my projects I wanted to use an <a href="http://www.phpunit.de/manual/current/en/appendixes.configuration.html#appendixes.configuration.phpunit">XML configuration file</a> in order to bootstrap the <a href="http://www.phpunit.de/">PHPUnit testing framework</a>. As you may know, in PHPUnit you may organize your unit tests in test suites, and also give them names. So, for better organizing my tests, I wanted five directories holding five different test suites which I thought could be easily configured inside the phpunit.xml file. Well, apparently there was support for only one test suite and a <a href="http://www.phpunit.de/ticket/623">ticket opened</a> for such an addition to the framework. As a result I hacked a little bit the source code and came up with a <a href="http://www.phpunit.de/ticket/623#comment:2">simple patch</a> (really, there is nothing fancy about it) so that now the config file accepts multiple test suites.</p>
<p>Thanks to <a href="http://sebastian-bergmann.de/">Sebastian Bergmann</a> the <a href="http://www.phpunit.de/changeset/4423">patch got accepted</a> and it will be available with PHPUnit 3.4</p>
<p>For many (web) developers out there this might be something really, really trivial and they’re right, but this is my first contribution to an open source project and I’m happy about it. Some time ago, reading blog post of <a href="http://andreimaxim.ro/">Andrei Maxim</a> (a fellow web developer) I got inspired and said to myself that I should too contribute some code to an open source project (he wanted a commit though, not a patch). Well, this was my first step. More to come… I hope.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Mon, 05 Jan 2009 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2009-01-05-my-first-contribution-to-an-open-source-project.html</guid>
</item>
<item>
    <title>How not to use dates in PHP</title>
    <link>http://igstan.ro/posts/2008-12-20-how-not-to-use-dates-in-php.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>How not to use dates in PHP</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>How not to use dates in PHP</h1>
    <time pubdate>December 20, 2008</time>
    <p>How many times did you find yourself using basic arithmetic operations to make a range of UNIX timestamps, given that you know the ends of the interval? I’m talking about something like this:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="fu">date_default_timezone_set</span><span class="ot">(</span><span class="st">&#39;Europe/Bucharest&#39;</span><span class="ot">);</span>

<span class="kw">$start</span> = <span class="fu">strtotime</span><span class="ot">(</span><span class="st">&#39;01 October 2008&#39;</span><span class="ot">);</span>
<span class="kw">$end</span>   = <span class="fu">strtotime</span><span class="ot">(</span><span class="st">&#39;01 November 2008&#39;</span><span class="ot">);</span>

<span class="kw">$next</span> = <span class="kw">$start</span><span class="ot">;</span>
<span class="kw">while</span> <span class="ot">(</span><span class="kw">$next</span> &lt;= <span class="kw">$end</span><span class="ot">)</span> {
    <span class="fu">echo</span> <span class="fu">date</span><span class="ot">(</span><span class="st">&#39;Y M d&#39;</span><span class="ot">,</span> <span class="kw">$next</span><span class="ot">)</span> <span class="ot">,</span><span class="st">&#39;&lt;br&gt;&#39;</span><span class="ot">;</span>
    <span class="kw">$next</span> += <span class="dv">60</span>*<span class="dv">60</span>*<span class="dv">24</span><span class="ot">;</span>
}</code></pre>
<p>If you run the above little script you might be surprised to see that October 26th appears twice, one after the other.</p>
<p>If you’re not aware of Daylight Saving Time you may have hard times understanding what’s happening behind the scenes and solving the problem. In the above snippet I started the script by specifying that PHP’s all date/time functions should use Bucharest’s timezone. That means that my date() call in the for loop would know that October 26th, 2008 is officially marked as the end of Daylight Saving Time for Bucharest (as well as whole Europe). In that day 04:00 <abbr title="Ante Meridian">AM</abbr> became 03:00 <abbr title="Ante Meridian">AM</abbr>, “rewinding” time one hour and passing from <abbr title="Eastern Europe Summer Time">EEST</abbr> to <abbr title="Eastern Europe Time">EET</abbr>.</p>
<p>So how can only one hour duplicate a day? Well, by observing <abbr title="Daylight Saving Time">DST</abbr>, one day in year gets one hour longer, while another day gets one hour shorter. October 26th, 2008 is the day that got one hour longer, counting a total of 25 hours, while our script is adding 24 hours for each iteration. That’s why, when the counter is supposed to return a UNIX timestamp for October 27th, 2008 it actually returns the timestamp for October 26, 2008 23:00:00, because now it’s one hour behind <abbr title="Daylight Saving Time">DST</abbr>. Here’s a modified script to show exactly this transition:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="fu">date_default_timezone_set</span><span class="ot">(</span><span class="st">&#39;Europe/Bucharest&#39;</span><span class="ot">);</span>

<span class="kw">$start</span> = <span class="fu">strtotime</span><span class="ot">(</span><span class="st">&#39;01 October 2008&#39;</span><span class="ot">);</span>
<span class="kw">$end</span>   = <span class="fu">strtotime</span><span class="ot">(</span><span class="st">&#39;01 November 2008&#39;</span><span class="ot">);</span>

<span class="kw">$next</span> = <span class="kw">$start</span><span class="ot">;</span>
<span class="kw">while</span> <span class="ot">(</span><span class="kw">$next</span> &lt;= <span class="kw">$end</span><span class="ot">)</span> {
    <span class="fu">echo</span> <span class="kw">$next</span> <span class="ot">,</span><span class="st">&#39; &#39;</span><span class="ot">;</span>
    <span class="fu">echo</span> <span class="fu">date</span><span class="ot">(</span><span class="st">&#39;Y M d H:i:s&#39;</span><span class="ot">,</span> <span class="kw">$next</span><span class="ot">)</span> <span class="ot">,</span><span class="st">&#39;&lt;br&gt;&#39;</span><span class="ot">;</span>
    <span class="kw">$next</span> += <span class="dv">60</span>*<span class="dv">60</span>*<span class="dv">24</span><span class="ot">;</span>
}

<span class="fu">echo</span> <span class="st">&#39;&lt;hr&gt;&#39;</span><span class="ot">;</span>
<span class="kw">$hours_in_26</span> = <span class="ot">(</span><span class="fu">strtotime</span><span class="ot">(</span><span class="st">&#39;27 October 2008&#39;</span><span class="ot">)</span> - <span class="fu">strtotime</span><span class="ot">(</span><span class="st">&#39;26 October 2008&#39;</span><span class="ot">));</span>
<span class="kw">$hours_in_26</span> = <span class="kw">$hours_in_26</span> / <span class="dv">60</span> / <span class="dv">60</span><span class="ot">;</span>
<span class="fu">echo</span> <span class="st">&quot;October 26th, has </span><span class="kw">$hours_in_26</span><span class="st"> hours when observing DST.&quot;</span><span class="ot">;</span></code></pre>
<p>I’ve also made a little diagram to highlight the problem. On the left hand side is the way <code>date()</code> function works when we’ve set a timezone value. On the right hand side is the way our script works, by treating all days as having only 24 hours. The green rectangle is that one hour difference between our script and <code>date()</code>. The red hours is when <abbr title="Daylight Saving Time">DST</abbr> ends.</p>
<p style="text-align: center;">
    
<img src="/files/images/dst.png"
         alt="DST aware versus non DST aware"
         title="DST aware versus non DST aware">
</p>

<p>Now that we know the problem we should fix it and the most simple solution is to change the timezone. Instead of Europe/Bucharest I could have been used <abbr title="Greenwich Mean Time">GMT</abbr> and the above script had been worke well:</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="fu">date_default_timezone_set</span><span class="ot">(</span><span class="st">&#39;GMT&#39;</span><span class="ot">);</span></code></pre>
<p>Unfortunately, using <abbr title="Greenwich Mean Time">GMT</abbr> is not always an option, as you want to display users valid dates for their territories, that is, you want localization (L10N). The other solution, which is better, is to not rely on arithmetic for such calculations. You’re better off using <code>mktime()</code> which, as any other date/time function, is <abbr title="Daylight Saving Time">DST</abbr> aware.</p>
<pre class="sourceCode php"><code class="sourceCode php"><span class="kw">&lt;?php</span>

<span class="fu">date_default_timezone_set</span><span class="ot">(</span><span class="st">&#39;Europe/Bucharest&#39;</span><span class="ot">);</span>

<span class="kw">$start</span> = <span class="fu">strtotime</span><span class="ot">(</span><span class="st">&#39;01 October 2008&#39;</span><span class="ot">);</span>
<span class="kw">$end</span>   = <span class="fu">strtotime</span><span class="ot">(</span><span class="st">&#39;01 November 2008&#39;</span><span class="ot">);</span>

<span class="kw">$next</span> = <span class="kw">$start</span><span class="ot">;</span>
<span class="kw">while</span> <span class="ot">(</span><span class="kw">$next</span> &lt;= <span class="kw">$end</span><span class="ot">)</span> {
    <span class="fu">echo</span> <span class="fu">date</span><span class="ot">(</span><span class="st">&#39;Y M d H:i:s&#39;</span><span class="ot">,</span> <span class="kw">$next</span><span class="ot">)</span> <span class="ot">,</span><span class="st">&#39;&lt;br&gt;&#39;</span><span class="ot">;</span>

    <span class="fu">list</span><span class="ot">(</span><span class="kw">$month</span><span class="ot">,</span> <span class="kw">$day</span><span class="ot">,</span> <span class="kw">$year</span><span class="ot">)</span> = <span class="fu">explode</span><span class="ot">(</span><span class="st">&#39;-&#39;</span><span class="ot">,</span> <span class="fu">date</span><span class="ot">(</span><span class="st">&#39;n-j-Y&#39;</span><span class="ot">,</span> <span class="kw">$next</span><span class="ot">));</span>
    <span class="kw">$next</span> = <span class="fu">mktime</span><span class="ot">(</span><span class="dv">0</span><span class="ot">,</span> <span class="dv">0</span><span class="ot">,</span> <span class="dv">0</span><span class="ot">,</span> <span class="kw">$month</span><span class="ot">,</span> <span class="kw">$day</span> + <span class="dv">1</span><span class="ot">,</span> <span class="kw">$year</span><span class="ot">);</span>
}</code></pre>
<p>By the way, changing the timezone identifier to “Asia/Jerusalem” would double October 5th, 2008 in the first version of the script. You may find more about these on <a href="http://timeanddate.com/">timeanddate.com</a>.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Sat, 20 Dec 2008 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2008-12-20-how-not-to-use-dates-in-php.html</guid>
</item>
<item>
    <title>MVC example from real, biological life</title>
    <link>http://igstan.ro/posts/2008-10-20-mvc-example-from-real-biological-life.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>MVC example from real, biological life</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>MVC example from real, biological life</h1>
    <time pubdate>October 20, 2008</time>
    <p>Lately I’ve been thinking a lot about software design patterns and software architecture in an attempt of being a better software developer (or just being one). Anyway, too much talk, I want to get to the subject because I think it’s very nice.</p>
<p>You’ve probably heard of the <a href="http://en.wikipedia.org/wiki/Model_view_controller">Model-View-Controller pattern</a> which is a big hype nowadays thanks to the Ruby on Rails web framework. It’s all about separating data access (Model) from data presentation (View) and that’s all. You may wonder where’s the third part, the Controller. It’s in between gluing the two parts together. The controller, while an important aspect of the <abbr title="Model-View-Controller">MVC</abbr> paradigm, is not as important as the idea of separation data and presentation.</p>
<p>You’ve also probably read a lot of examples about MVC, involving web application that suddenly have to switch from a certain database vendor to another or output data in multiple formats, like <abbr title="HyperText Markup Language">HTML</abbr>, <abbr title="JavaScript Object Notation">JSON</abbr>, <abbr title="Portable Document Format">PDF</abbr>, <abbr title="Et cetera">etc.</abbr> Well, here’s a little <abbr title="Model-View-Controller">MVC</abbr> example that actually lies within your own body.</p>
<p>It’s the very human act of expressing ideas, either written or spoken.</p>
<p>When someone is expressing her ideas in speech she uses an <abbr title="Model-View-Controller">MVC</abbr> system where data is the idea itself (what she thinks) that sits in the Model (our conscience and perception of the surrounding world), the View is the language in which the ideas are presented and the Controller is the sum of biological and associated neuronic structures that let us map these ideas to comprehensible and logical sounds (in a normal human being).</p>
<p>It’s true that I exaggerated a little about the limits between the parts of this system and that these are very blurry line that separate them… nevertheless is the idea that matters. If it weren’t for this <abbr title="Model-View-Controller">MVC</abbr> system inside us, speaking foreign languages would be impossible.</p>
<p><abbr title="Post Scriptum">P.S.</abbr> Who?! Me? A nerd?! <br> <abbr title="Post, Post Scriptum">P.S.S.</abbr> I’m not implying that my English view is perfect</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Mon, 20 Oct 2008 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2008-10-20-mvc-example-from-real-biological-life.html</guid>
</item>
<item>
    <title>How to install Python libraries on Windows</title>
    <link>http://igstan.ro/posts/2008-09-04-how-to-install-python-libraries-on-windows.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>How to install Python libraries on Windows</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>How to install Python libraries on Windows</h1>
    <time pubdate>September 04, 2008</time>
    <p>Whenever you have to install another Python library on a Windows <abbr title="Operating System">OS</abbr> is good to do it like this from the command line:</p>
<pre><code>cd path/to/library/dir
python setup.py bdist --format=wininst</code></pre>
<p>This will pack all the source into an installer that can be found under “path/to/library/dir/dist”.</p>
<p>Using this method you will later be able to go to “Control Panel” -&gt; “Add or Remove Programs” and uninstall such a library from there.</p>
<p>For other platforms and options see <a href="http://docs.python.org/dist/built-dist.html">Python documentation on creating built distributions</a>.</p>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Thu, 04 Sep 2008 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2008-09-04-how-to-install-python-libraries-on-windows.html</guid>
</item>
<item>
    <title>Assessing Google Chrome</title>
    <link>http://igstan.ro/posts/2008-09-02-assessing-google-chrome.html</link>
    <description><![CDATA[<!DOCTYPE html>

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Assessing Google Chrome</title>
<link rel="stylesheet" type="text/css" href="/css/mobile.css">
<!--[if !IEMobile & lt IE 9]>
    <link rel="stylesheet" type="text/css" href="/css/main.css">
<![endif]-->
<!--[if IE]><![if gte IE 9]><![endif]-->
    <link rel="stylesheet" type="text/css" href="/css/main.css" media="screen and (min-width: 480px)">
<!--[if IE]><![endif]><![endif]-->
<!--[if IE]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="alternate" type="application/rss+xml" href="http://feeds.feedburner.com/igstan" title="All Posts - RSS Feed">
</head>
<body>

<a href="/" class="logo" title="Go to homepage">
    <img src="/css/graphics/list-atom.png" alt="List Atom">
</a>

<div class="container"><article>
    <h1>Assessing Google Chrome</h1>
    <time pubdate>September 02, 2008</time>
    <p>I have already discovered some bugs and managed to crash two tabs in under 3 minutes when I interrupted for writing this post. There are also some features I miss from Firefox. Details…</p>
<h2 id="bugs">Bugs</h2>
<ol style="list-style-type: decimal">
<li>It erroneously fills some form fields from a forum I often visit overriding the input’s value attribute (at least that’s what I was able to see with the built in, à la firebug, inspector, which is good news by the way.)</li>
<li>The whole browser freezed when opening a link from the above mentioned forum that pointed to my weblog home page. I succeded to take back control when killing one process from the Windows task manager, which aparently made two tabs, not one (I killed one process, not tow), to show the sad face of failure.</li>
<li>Opening a 155 page <abbr title="Portable Document Format">PDF</abbr> document made iresponsive the whole browser, not just the respective tab as said in the comic book and reduced 4 tab-processes to only one process in the Windows task manager which took the whole browser down when killing it.</li>
<li>After reboot the <abbr title="Portable Document Format">PDF</abbr> page still isn’t rendered as it should and any interaction with it slows down (to freezing) the whole browser. (At least this blog entry was preserved in the textarea).</li>
<li>There appear to be some bugs with the character encoding support. In Romanian we have special characters like “ăîâșț” that aren’t rendered as they should nor when the enconding is ISO-8859-2 (which I know should be OK for Romanian), nor when I change it to UTF-8. Anyways, the website isn’t sending a charset in the <abbr title="HyperText Transfer Protocol">HTTP</abbr> headers (according to LiveHTTPHeaders), on other web sites it is OK.</li>
</ol>
<h2 id="missing-features">Missing features</h2>
<ol style="list-style-type: decimal">
<li>Can’t scroll pages while middle-clicking :-( That’s awful for me, a reason not to use a browser.</li>
<li>Iframes used for rich text editing don’t have spell checking, whereas textarea elements do.</li>
<li>I can’t turn off spell checking on textarea elements.</li>
<li>Maybe not a missing features but I couldn’t find it. Where can I choose another engine from my opensearch engines that were imported from Firefox after the installation? (later on) it may be redundant as all the opensearch providers are available for querying inside the address bar.</li>
<li>I’d really like to disable the close buttons on every opened tab.</li>
<li>When opening many tabs (&gt; 20) there’s no way to know what site is in which tab, except for the favicon (if there is one) that is being displayed. That is because a tab’s width is in inverse ratio with the number of tabs. I tend to like more the scrolling feature of Firefox in such a case (but maybe I’m just spoiled by Firefox). Anyway, they load fine dispite the large number.</li>
<li>It comes with built-in support for Adobe Flash and Adobe PDF but not Quick Time.</li>
<li>At this moment I have 7 folders of bookmarks imported from Firefox. When clicking one, there’s a submenu that popups and the bookmars contained can be seen, well, now I expect that hovering another folder will open it automatically without click on it again but it doesn’t happen like this, you have to click it again. I think on a Windows <abbr title="Operating System">OS</abbr> this is common practice for user interface (not to be forced to click again).</li>
<li>I don’t have a history list by the back/forward buttons.</li>
<li>An RSS/Atom reader like in Firefox.</li>
<li>No “Zoom page” tool, only zoom text with <kbd>CTRL</kbd>+<kbd>+</kbd>, <kbd>CTRL</kbd>+<kbd>-</kbd> and <kbd>CTRL</kbd>+<kbd>0</kbd> just like in Firefox.</li>
<li>I can’t middle click the back/forward button to open a previous page in new tab.</li>
</ol>
<h2 id="good-thingsfeatures">Good things/features</h2>
<ol style="list-style-type: decimal">
<li>The HTML inspector (mentioned above) and <abbr title="JavaScript">JS</abbr> debugger and console.</li>
<li>Searching through the installation files I discovered some js scripts that deal with the local data store and seemed to be integrated with the Inspector but I couldn’t lauch it from the browser.</li>
<li>The source turn links into real links so that I can quickly go to the <abbr title="Cascading Style Sheets">CSS</abbr> and <abbr title="JavaScript">JS</abbr> files of a website.</li>
<li>Mozilla Prism’s idea of web pages that could be saved as desktop apps is now to be found in Google Chrome. You can save a shortcut to Gmail, for example, on the desktop, quick launch bar and start menu. Details</li>
<li>It has “View Frame Source” when right clicking on an iframe element.</li>
<li>I like the search capabilities in the address bar (I always wished it in Firefox).</li>
<li>The “bookmark this page” from the address bar is like Firefox’s, except it misses tagging.</li>
<li>Incognito mode.</li>
<li>Speed of loading for some of the pages I visited.</li>
<li>Incremental search + it shows how many results it has found until that point + highlighting of matching keywords + <kbd>F3</kbd> does work to jump to next result + … the place of the search box :).</li>
<li><kbd>CTRL</kbd>+<kbd>J</kbd> opens downloads tab (just like in Firefox).</li>
<li>Detaching tabs in standalone windows.</li>
<li>X/Y resizable textarea element, but the resizer image has a non-transparent upper-left corner.</li>
</ol>
<h2 id="wtfs">WTFs</h2>
<ol style="list-style-type: decimal">
<li>The installation place. On my system (Windows XP Professional 32bit) it was in <code>C:\Documents and Settings\username\Local Settings\Application Data\Google\Chrome\Application\chrome.exe</code>, along with Gears and… GoogleUpdate.</li>
</ol>
    <p class="related">
        <span class="igstan-twitter-button">
            <a style="position:fixed" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="igstan">Tweet</a>
        </span>

        List <a href="/posts.html">all posts</a>, go to <a href="/">homepage</a>
        or subscribe to the <a href="http://feeds.feedburner.com/igstan" class="feed">RSS feed</a>
    </p>
</article>

<div id="disqus_thread"></div>
<script type="text/javascript">
(function() {
    var node = document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0];

    // load disqus comments
    var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
    dsq.src = 'http://igstan.disqus.com/embed.js';
    node.appendChild(dsq);

    // load twitter button
    var twit = document.createElement('script'); twit.type = 'text/javascript'; twit.async = true;
    twit.src = 'http://platform.twitter.com/widgets.js';
    node.appendChild(twit);
})();
</script>
</div>

<footer class="copyright">
    <small>&copy; 2008 — 2015 Ionuț G. Stan</small>
</footer>

<script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-6642500-3']);
    _gaq.push(['_trackPageview']);

    (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();
</script>

</body>
</html>
]]></description>
    <pubDate>Tue, 02 Sep 2008 00:00:00 UT</pubDate>
    <guid>http://igstan.ro/posts/2008-09-02-assessing-google-chrome.html</guid>
</item>

    </channel> 
</rss>
