<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Smellegant Code</title>
	<atom:link href="http://smellegantcode.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://smellegantcode.wordpress.com</link>
	<description>&#34;No profit grows where is no pleasure taken&#34;</description>
	<lastBuildDate>Sun, 29 Jan 2012 22:42:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='smellegantcode.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Smellegant Code</title>
		<link>http://smellegantcode.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://smellegantcode.wordpress.com/osd.xml" title="Smellegant Code" />
	<atom:link rel='hub' href='http://smellegantcode.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Async/await iterator &#8211; updated for Visual Studio 11 Preview</title>
		<link>http://smellegantcode.wordpress.com/2012/01/29/asyncawait-iterator-updated-for-visual-studio-11-preview/</link>
		<comments>http://smellegantcode.wordpress.com/2012/01/29/asyncawait-iterator-updated-for-visual-studio-11-preview/#comments</comments>
		<pubDate>Sun, 29 Jan 2012 13:21:32 +0000</pubDate>
		<dc:creator>earwicker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 5.0]]></category>

		<guid isPermaLink="false">http://smellegantcode.wordpress.com/?p=642</guid>
		<description><![CDATA[A long overdue install of the Visual Studio 11 Preview, and the changes to the asynchronous language features since 2010 (my, how time flies) are enough to break the code I blogged over a year ago. The first problem is a few of the methods of an &#8220;awaiter&#8221; (what in C++ we&#8217;d call the awaiter [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=642&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A long overdue install of the <a href="http://msdn.microsoft.com/en-us/vstudio/hh127353">Visual Studio 11 Preview</a>, and the changes to the asynchronous language features since 2010 (my, how time flies) are enough to break <a href="http://smellegantcode.wordpress.com/2010/12/14/unification-of-async-await-and-yield-return/">the code I blogged over a year ago</a>.</p>
<p>The first problem is a few of the methods of an &#8220;awaiter&#8221; (what in C++ we&#8217;d call the awaiter <em>concept</em>) have been renamed, and there&#8217;s now a property called <code>IsCompleted</code>, and that&#8217;s fine and dandy.</p>
<p>But when I tried exercising the code I hit a more thorny problem, which is that my test program would terminate somewhat randomly when an exception was rethrown from a background thread. For a program that I thought was single threaded, that&#8217;s pretty bad!</p>
<p>I don&#8217;t have my install of the original CTP, so I&#8217;m not sure about this, but I think a fairly major change was made since then: there&#8217;s now a difference between an <code>async</code> method that returns <code>void</code> and an <code>async</code> method that returns <code>Task</code> (as opposed to <code>Task&lt;T&gt;</code>).</p>
<p>Contrary to what might be assumed, the relationship between <code>Task</code> and <code>Task&lt;T&gt;</code> is not the same as that between <code>IEnumerable</code> and <code>IEnumerable&lt;T&gt;</code>. That is, <code>Task</code> is not some old pre-generics version of the same idea. Instead, it was specially created to represent a task that doesn&#8217;t return any value at all; that is, something like <code>void</code>, but asynchronous.</p>
<p>I believe (though I&#8217;m not certain) that in the original CTP, a <code>void async</code> method would actually return a <code>Task</code>, so as to ensure that its lifetime could be managed externally even though it wouldn&#8217;t produce a value. But in the latest version that is not the case: the <code>Task</code> associated with an <code>void async</code> method is just not available, and the compiler generated version of the method really does return <code>void</code>. Which means in turn that you can&#8217;t use <code>await</code> on such methods.</p>
<p>You can still explicitly declare your <code>async</code> method to return <code>Task</code>, so nothing has been lost. And this certainly makes everything more clear and consistent to callers: methods really do return what they are declared to return, as usual. <strong>But it also changes the behaviour of exceptions.</strong></p>
<p>In all case, if an exception tries to escape out of your <code>async</code> method, there is a catch-all handler in the compiler-generated state machine which will catch it, so it can be rethrown in an appropriate context. But the choice of context depends totally on whether the method returns <code>void</code> or <code>Task</code>. The policy is determined by <code>AsyncVoidMethodBuilder</code> or <code>AsyncTaskMethodBuilder</code> respectively. With the help of Resharper, we can see that the latter gives the caught exception to the <code>Task</code>, via <code>task.TrySetException</code>. So then the decision to rethrow (or not) is entirely up to whoever has a hold of the <code>Task</code>. They can check the <code>Exception</code> property whenever.</p>
<p>But in the <code>void</code> case, it&#8217;s totally different. The <code>Task</code> never gets passed the exception. What would be the point? We can&#8217;t get at the <code>Task</code>. The exception is unobservable; to avoid that loss of information, an arrangement is made to rethrow the exception at the next available opportunity, by creating a delegate that will rethrow it and then posting that delegate to the &#8220;context&#8221;.</p>
<p>The &#8220;context&#8221; is a somewhat vague concept; the architecture uses three different representations, depending on the scenario. But in the case of a simple console-based test program, the exception-rethrowing delegate is simply passed to the thread pool, and so it brings down the whole process at a random time (though reasonably soon). In a GUI program the exception would be thrown on the main GUI thread. You can supply your own context by setting a per-thread instance of <a href="http://msdn.microsoft.com/en-us/library/system.threading.synchronizationcontext.aspx">SynchronizationContext</a>, in which you can override the <code>Post</code> method. It doesn&#8217;t let you get at the exception, but it does give you a delegate that, if you executed it, would throw the exception, which you can then catch!</p>
<p>The upshot? An exception that leaves an <code>async void</code> is definitely a sign of a bug somewhere. Although of course this does not automatically mean you should add your own catch-all! <a href="http://smellegantcode.wordpress.com/2010/06/24/exceptions-part-2-why-do-we-need-to-catch-them/">Sometimes crashing the process is the least-worst option</a>. There is no single correct way to deal with bugs &#8211; it&#8217;s a question of economics and so is not an exact science.</p>
<p>So in short, <code>async void</code> is a niche thing. In most situations you almost certainly want <code>async Task</code> with no type argument. And my example of implementing the equivalent of <code>yield return</code> definitely needs updating.</p>
<p>Firstly I stash the <code>Task</code> in a field. Second, after executing the continuation I check the <code>Task.Exception</code> property to see if anything bad happened that needs rethrowing:</p>
<p><pre class="brush: csharp;">
if (_task.Exception != null)
{
    // Unpeel the AggregateException wrapping
    Exception inner = _task.Exception;
    while (inner is AggregateException)
        inner = inner.InnerException;

    throw inner;
}
</pre></p>
<p>Aside from that it works much the same way as before, though I&#8217;ve added a lot of comments and organised it a little differently to hopefully make the behaviour clearer. I&#8217;ve also had to add an implementation of the new awaiter property:</p>
<p><pre class="brush: csharp;">
public bool IsCompleted
{
    get { return false; }
}
</pre></p>
<p>Well, that was easy. Returning <code>true</code> would be a very bad idea in this example, as we can discover with more Resharper digging. The compiler-generated state machine examines that property, and if it is true then it doesn&#8217;t bother to yield control back to the thread. So we don&#8217;t get the interleaved execution behaviour that we&#8217;re relying on.</p>
<p>Here&#8217;s the whole thing:</p>
<p><pre class="brush: csharp;">
public delegate Task IteratorMethod(YieldEnumerator e);

public class YieldEnumerator : IEnumerator
{
    // Will be executed to get the next value
    private Action _continuation;

    // Will become the value of Current
    private TItem _nextValue;
    private bool _hasNextValue;

    // To be thrown inside the async method, as if by the await keyword
    private Exception _exception;

    // The task associated with our running async method
    private Task _task;

    public YieldEnumerator(IteratorMethod iteratorMethod)
    {
        _task = iteratorMethod(this);
    }

    private void Execute()
    {
        // If we already have a buffered value that hasn't been
        // retrieved, we shouldn't do anything yet. If we don't
        // and there's no continuation to run, we've finished.
        // And if _task is null, we've been disposed.
        if (_hasNextValue || _continuation == null || _task == null)
            return;

        // Be ultra-careful not to run same _continuation twice
        var t = _continuation;
        _continuation = null;
        t(); // may or may not have stored a new _continuation

        // And may also have hit a snag!
        if (_task.Exception != null)
        {
            // Unpeel the AggregateException wrapping
            Exception inner = _task.Exception;
            while (inner is AggregateException)
                inner = inner.InnerException;

            throw inner;
        }
    }

    public YieldEnumerator GetAwaiter()
    {
        return this;
    }

    // Performance optimisation added since original CTP. If we
    // returned true, the compiler-generated code would bypass the
    // OnCompleted/GetResult dance altogether, and the flow of the
    // async method would never be interrupted in the way that we
    // require.
    public bool IsCompleted
    {
        get { return false; }
    }

    // Was called BeginAwait in the original CTP
    public void OnCompleted(Action continuation)
    {
        Debug.Assert(_continuation == null);
        _continuation = continuation;
    }

    // Was called EndAwait
    public void GetResult()
    {
        // This is called by compiler-generated code caused by the
        // await keyword, so it's a chance to throw an exception to
        // be caught by the code in the async method
        if (_exception != null)
        {
            var t = _exception;
            _exception = null;
            throw t;
        }
    }

    // Our equivalent of yield return
    public YieldEnumerator YieldReturn(TItem value)
    {
        if (_hasNextValue)
        {
            // Shouldn't happen because MoveNext ought to have
            // been called and we should be inside the async
            // code at this point
            throw new InvalidOperationException();
        }

        _nextValue = value;
        _hasNextValue = true;
        return this;
    }

    public TItem Current { get; private set; }

    object System.Collections.IEnumerator.Current
    {
        get { return Current; }
    }

    public bool MoveNext()
    {
        Execute();

        if (_hasNextValue)
        {
            Current = _nextValue;
            _hasNextValue = false;
            return true;
        }

        return false;
    }

    private sealed class AbandonEnumeratorException : Exception {}

    public void Dispose()
    {
        // If async method is not yet complete, throw an exception
        // inside it to make it grind to a halt
        if (_continuation != null)
        {
            _exception = new AbandonEnumeratorException();
            try { Execute(); } catch (AbandonEnumeratorException) { }
        }

        _task.Dispose();
        _task = null;
    }

    public void Reset()
    {
        throw new NotImplementedException(&quot;Reset&quot;);
    }
}

// The usual obvious IEnumerable to go with our IEnumerator
public class YieldEnumerable : IEnumerable
{
    private readonly IteratorMethod _iteratorMethod;

    public YieldEnumerable(IteratorMethod iteratorMethod)
    {
        _iteratorMethod = iteratorMethod;
    }

    public IEnumerator GetEnumerator()
    {
        return new YieldEnumerator(_iteratorMethod);
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

class Program
{
    public static async Task MyIteratorMethod1(YieldEnumerator e)
    {
        Console.WriteLine(&quot;A&quot;);
        await e.YieldReturn(1);
        Console.WriteLine(&quot;B&quot;);
        await e.YieldReturn(2);
        Console.WriteLine(&quot;C&quot;);
        await e.YieldReturn(3);
        Console.WriteLine(&quot;D&quot;);
    }

    public static async Task MyIteratorMethod2(YieldEnumerator e)
    {
        try
        {
            Console.WriteLine(&quot;A&quot;);
            await e.YieldReturn(1);
            Console.WriteLine(&quot;B&quot;);
            await e.YieldReturn(2);
            Console.WriteLine(&quot;C&quot;);
            await e.YieldReturn(3);
            Console.WriteLine(&quot;D&quot;);
        }
        finally
        {
            Console.WriteLine(&quot;Running finally&quot;);
        }
    }

    public static async Task MyIteratorMethodInfinite(YieldEnumerator e)
    {
        for (var n = 0; ; n++)
            await e.YieldReturn(n);
    }

    public static async Task MyIteratorBroken1(YieldEnumerator e)
    {
        // always happens, but compiler doesn't know that
        if (DateTime.Now.Year &lt; 10000)
            throw new IOException(&quot;Bad&quot;);

        await e.YieldReturn(1);
    }

    public static async Task MyIteratorBroken2(YieldEnumerator e)
    {
        await e.YieldReturn(1);

        if (DateTime.Now.Year &lt; 10000)
            throw new IOException(&quot;Bad&quot;);
    }

    public static async Task MyIteratorBroken3(YieldEnumerator e)
    {
        await e.YieldReturn(1);

        if (DateTime.Now.Year &lt; 10000)
            throw new IOException(&quot;Bad&quot;);

        await e.YieldReturn(2);
    }

    static void Main(string[] args)
    {
        foreach (var i in new YieldEnumerable(MyIteratorMethod1))
            Console.WriteLine(&quot;Yielded: &quot; + i);

        foreach (var i in new YieldEnumerable(MyIteratorMethod2))
        {
            Console.WriteLine(&quot;Yielded: &quot; + i);
            break; // finally should still run
        }

        foreach (var i in new YieldEnumerable(MyIteratorMethodInfinite))
        {
            if (i % 1000000 == 0) // every million times...
                Console.WriteLine(&quot;Yielded: &quot; + i);

            if (i &gt; 10000000)
                break;
        }

        try
        {
            foreach (var i in new YieldEnumerable(MyIteratorBroken1))
                Console.WriteLine(&quot;Yielded: &quot; + i);
        }
        catch (IOException)
        {
            Console.WriteLine(&quot;Caught expected exception&quot;);
        }

        try
        {
            foreach (var i in new YieldEnumerable(MyIteratorBroken2))
                Console.WriteLine(&quot;Yielded: &quot; + i);
        }
        catch (IOException)
        {
            Console.WriteLine(&quot;Caught expected exception&quot;);
        }

        try
        {
            foreach (var i in new YieldEnumerable(MyIteratorBroken3))
                Console.WriteLine(&quot;Yielded: &quot; + i);
        }
        catch (IOException)
        {
            Console.WriteLine(&quot;Caught expected exception&quot;);
        }
    }
}
</pre></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smellegantcode.wordpress.com/642/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smellegantcode.wordpress.com/642/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smellegantcode.wordpress.com/642/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smellegantcode.wordpress.com/642/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/smellegantcode.wordpress.com/642/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/smellegantcode.wordpress.com/642/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/smellegantcode.wordpress.com/642/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/smellegantcode.wordpress.com/642/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smellegantcode.wordpress.com/642/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smellegantcode.wordpress.com/642/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smellegantcode.wordpress.com/642/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smellegantcode.wordpress.com/642/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smellegantcode.wordpress.com/642/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smellegantcode.wordpress.com/642/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=642&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://smellegantcode.wordpress.com/2012/01/29/asyncawait-iterator-updated-for-visual-studio-11-preview/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/344e328f9fad1934791575a99830ef80?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">earwicker</media:title>
		</media:content>
	</item>
		<item>
		<title>Asynchronous Memoization in JavaScript</title>
		<link>http://smellegantcode.wordpress.com/2012/01/16/asynchronous-memoization-in-javascript/</link>
		<comments>http://smellegantcode.wordpress.com/2012/01/16/asynchronous-memoization-in-javascript/#comments</comments>
		<pubDate>Mon, 16 Jan 2012 12:43:12 +0000</pubDate>
		<dc:creator>earwicker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[asychrony]]></category>
		<category><![CDATA[functional]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://smellegantcode.wordpress.com/?p=635</guid>
		<description><![CDATA[In pure functional programming there is a simple rule: if you evaluate (call) a function more than once with the exact same argument values, you&#8217;ll keep getting the same return value. It follows that there is no need to call it more than once, which is super-awesome!! because it means you can put a caching [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=635&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In pure functional programming there is a simple rule: if you evaluate (call) a function more than once with the exact same argument values, you&#8217;ll keep getting the same return value. It follows that there is no need to call it more than once, which is <strong>super-awesome!!</strong> because it means you can put a caching mechanism in front of the function that keeps a map (hash table, Dictionary, etc.) of all the return values produced so far, each one keyed by the bundle of arguments that produced that return value.</p>
<p>Of course it&#8217;s only worth doing this if the dictionary lookup is faster than simply re-executing the function itself, and if the same small set of arguments are highly likely to be passed repeatedly. <strong>Yawn!!</strong></p>
<p>In a non-pure language like JavaScript many (most?) functions are not pure: they examine information from other sources besides their parameters. However, they often have contexts within which they are &#8220;pure enough&#8221;. e.g. the information the user can see on the screen is, naively speaking, a projection of the information stored in the database, but if that were really true then when the database changes, the screen would immediately change as well. But it doesn&#8217;t; instead it usually remains stale until the user presses Refresh. This corresponds to &#8220;emptying the cache&#8221;.</p>
<p>In a complex app, there may be several separate components that project the same information in different ways. If they all go back to the external source for that information, and it is changing in real time, you could end up with an inconsistent picture on the screen. This might even cause instability, if one component tries to talk to another and they assume they&#8217;ll both have identical snapshots of the external information.</p>
<p>So memoization actually has a purpose in JavaScript: it can simulate a &#8220;freeze frame&#8221; of your dependencies on external data. But we need to provide the ability to delete things from the cache at the time of our choosing, &#8220;unfreezing&#8221; the frame so we can take a new snapshot.</p>
<p>Another complicating factor in JavaScript is asynchrony. JavaScript programmers just have to get used to doing the following transformation into &#8220;continuation-passing style&#8221; by hand; starting with:</p>
<p><pre class="brush: jscript;">
var add = function(a1, a2) {
  return a1 + a2;
};
</pre></p>
<p>We switch to:</p>
<p><pre class="brush: jscript;">
var add = function(a1, a2, done) {
  done(a1 + a2);
};
</pre></p>
<p>So the caller of <code>add</code> can no longer say:</p>
<p><pre class="brush: jscript;">
var sum = add(2, 2);
alert('The answer is ' + sum);
</pre></p>
<p>And must instead say:</p>
<p><pre class="brush: jscript;">
add(2, 2, function(sum) {
  alert('The answer is ' + sum);
});
</pre></p>
<p>This allows the implementation of <code>add</code> to utilise other functions that need to be passed a continuation in the same manner. <strong>Yo!!</strong></p>
<p>So, let&#8217;s memoize. To simplify matters we&#8217;ll start by assuming we&#8217;ll be dealing with functions that take no parameters (or always take exactly the same parameters, it&#8217;s the same thing). It means we can replace the map with a single variable. We&#8217;re displaying &#8220;prices&#8221; (whatever the hell they are) to the user, so if synchronous was a realistic option we&#8217;d start with:</p>
<p><pre class="brush: jscript;">
var getPrices = function() { 
    /// Talk to server to get prices, p, somehow.
    return p; 
};
</pre></p>
<p>Sadly we have to be asynchronous, but it&#8217;s no biggie:</p>
<p><pre class="brush: jscript;">
var getPrices = function(done) {
    /// Talk to server to get prices, p, somehow.
    done(p); 
};
</pre></p>
<p>Seems like memoizing something that will be easy!</p>
<p><pre class="brush: jscript;">
var makeCache = function(getter) {

  var value = null, ready = false;

  return {

    reset: function() {
      value = null;
      ready = false;
    },

    get: function(done) {
      if (ready) {
        done(value);
      } else {
        getter(function(got) {
          value = got;
          ready = true;
          done(value);
        });
      }
    }
  };

};
</pre></p>
<p>You&#8217;d use it to &#8220;wrap&#8221; the getPrices function like this:</p>
<p><pre class="brush: jscript;">
var pricesCache = makeCache(getPrices);

pricesCache.get(function(prices) {
  // we've got the prices!  
});
</pre></p>
<p>And when you want to reset the cache, just say:</p>
<p><pre class="brush: jscript;">
pricesCache.reset();
</pre></p>
<p>But actually there&#8217;s a bug here: do you know what it is? Give yourself a <strong>playful slap on the thigh</strong> if you got it.</p>
<p>What if there&#8217;s more than one call to <code>pricesCache.get</code> before the first one comes back with the data? We only set the <code>ready</code> flag when we&#8217;ve got the answer, which might take a second. In the meantime, various parts of the UI might be grabbing the prices to make their own updates. Each such call will launch a separate (unnecessary) call to the backend. What&#8217;s worse is that the prices may actually change during this mess, and so the callers will end up with inconsistent price information, just like I was <strong>a-bellyachin&#8217; about up yonder</strong>.</p>
<p>First reaction: oh, oh, I know, it&#8217;s a state machine! We thought there were two states, as indicated by the boolean <code>ready</code> flag. But actually there&#8217;s three:</p>
<ol>
<li>No value.</li>
<li>Okay, I&#8217;m, getting the value, sheesh.</li>
<li>Got the value.</li>
</ol>
<p>But hold on to your hose, little fireman. Think this one through for a second. It&#8217;s pretty clear that when the first caller tries to <code>get</code>, we need to transition to the middle state and make our call to the real <code>getter</code> function. And when the prices come back to us, we transition to the final state and call the callback function. But what about when a second caller tries to <code>get</code> and we&#8217;re already in the middle state? That&#8217;s the whole reason for doing this, to be able to handle that differently. Where do we put their callback function?</p>
<p>So, yes, it is a state machine, but not a three-state one. We need to keep a list of callback functions, so that when the prices come back, we can loop through those callback functions and give every single <strong>gosh darn</strong> one of them a calling they <strong>ain&#8217;t gonna forgit</strong>:</p>
<p><pre class="brush: jscript;">
var makeCache = function(getter) {

  var value, ready, waiting = [];

  return {

    reset: function() {
      value = null;
      ready = false;
      waiting = [];
    },

    get: function(done) {
      if (ready) {
        done(value);
      } else {
        waiting.push(done);

        if (waiting.length === 1) {
          getter(function(got) {

            value = got;
            ready = true;

            waiting.forEach(function(w) { w(value); });
            waiting = null;
          });
        }
      }
    }
  };

};
</pre></p>
<p>Notice how I use <code>waiting.forEach</code> to loop through the callbacks. By definition here I&#8217;m calling some code that I don&#8217;t have control of. It might call back into <code>pricesCache.get</code>. That may seem intrinsically problematic, because it sounds like it could keep happening forever and cause a stack overflow. But it might be perfectly valid: there could be some separate code making the second call to get the prices, which supplies a different callback. Anyway, is it a problem for my cache implementation? No, because any calls to <code>pricesCache.get</code> during my callback loop will find that <code>ready</code> is already set, and so will not affect the waiting array. And even if <code>pricesCache.reset</code> were called, that would cause a fresh array to be created and stored in <code>waiting.</code></p>
<p>And finally, nice piece of trivia for ya: even if there was some way for <code>waiting</code> to grow while we are still looping through it, according to the specification of <code>Array.forEach</code> the new item(s) won&#8217;t be included in the iteration.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smellegantcode.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smellegantcode.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smellegantcode.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smellegantcode.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/smellegantcode.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/smellegantcode.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/smellegantcode.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/smellegantcode.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smellegantcode.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smellegantcode.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smellegantcode.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smellegantcode.wordpress.com/635/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smellegantcode.wordpress.com/635/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smellegantcode.wordpress.com/635/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=635&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://smellegantcode.wordpress.com/2012/01/16/asynchronous-memoization-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/344e328f9fad1934791575a99830ef80?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">earwicker</media:title>
		</media:content>
	</item>
		<item>
		<title>Linq to C++ (or something much better)</title>
		<link>http://smellegantcode.wordpress.com/2011/10/31/linq-to-c-or-something-much-better/</link>
		<comments>http://smellegantcode.wordpress.com/2011/10/31/linq-to-c-or-something-much-better/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 13:03:10 +0000</pubDate>
		<dc:creator>earwicker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C++0x]]></category>
		<category><![CDATA[c++11]]></category>
		<category><![CDATA[lambdas]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://smellegantcode.wordpress.com/?p=611</guid>
		<description><![CDATA[A really long time ago (26th Jan 2009 to be exact), I got excited about lambdas in C++0x, and the idea of bringing a Linq-like lazily-evaluated sequence filtering system to C++. I wrote a blog post about this idea partly as a pedagogical exercise in explaining the parallels/divergences in how an iteratable sequence is represented [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=611&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A really long time ago (26th Jan 2009 to be exact), I got excited about lambdas in C++0x, and the idea of bringing a Linq-like lazily-evaluated sequence filtering system to C++. <a href="http://smellegantcode.wordpress.com/2009/01/26/linq-to-c0x/">I wrote a blog post about this idea</a> partly as a pedagogical exercise in explaining the parallels/divergences in how an iteratable sequence is represented in C++ and C#.</p>
<p>Whenever I&#8217;m asked if this would make sense as a real library, I&#8217;ve replied that in the real world it would make much more sense to build on the stuff in Boost, especially the range library.</p>
<p>And guess what? At that very moment someone was already working on it (only with a far more elegant, extensible interface), and the following month a set of extensions to range were put up for review, and were accepted&#8230; then a long time passed (they&#8217;re very careful) until summer of 2010, when finally the new features were released in Boost 1.43.</p>
<p>I only discovered this just now. People still seem to be finding that old blog post, so it only seems proper to get up-to-date. My first stab looked like this:</p>
<p><pre class="brush: cpp;">
#include &lt;boost/range/algorithm/for_each.hpp&gt;
#include &lt;boost/range/adaptor/filtered.hpp&gt;
#include &lt;boost/range/adaptor/transformed.hpp&gt;

#include &lt;boost/lexical_cast.hpp&gt;

#include &lt;vector&gt;
#include &lt;iostream&gt;
#include &lt;string&gt;

int main()
{
	using namespace boost::adaptors;

	std::vector&lt;int&gt; numbers;
	numbers.push_back(0);
	numbers.push_back(-1);
	numbers.push_back(4);
	numbers.push_back(-3);
	numbers.push_back(5);
	numbers.push_back(8);
	numbers.push_back(-2);
	
	auto quoted_positives = numbers 
		| filtered([] (int n) { return n &gt;= 0; })
		| transformed([] (int x) { 
                    return &quot;\&quot;&quot; + boost::lexical_cast&lt;std::string&gt;(x) + &quot;\&quot;&quot;; 
                  });

	boost::for_each(quoted_positives, [] (std::string n) { 
            std::cout &lt;&lt; n &lt;&lt; std::endl; 
        });
	return 0;
}
</pre></p>
<p>As you can see, the key is the use of <code>operator|</code> to make a piping syntax, so that we can naturally read from left to right (you may have seen the same approach used in F#). So I start with a vector of plain integers called <code>numbers</code>, I then pipe that through the <code>filtered</code> adaptor so as to get just the positives (corresponding to <code>Where</code> in Linq), and finally through the <code>transformed</code> adaptor to turn each positive into a quoted string (corresponding to <code>map</code> in most functional frameworks and to <code>Select</code> in Linq).</p>
<p><strong>Except&#8230; it doesn&#8217;t work.</strong></p>
<p>The problem is that <code>boost</code> is not yet entirely C++11 lambda-friendly. It&#8217;s unfortunate that the boost documentation (and other online information) is peppered with the word lambda signifying something else, so I may just be missing something. But the gist of the problem appears to be that <code>transformed</code> wants a functor with a member type called <code>result_type</code>. So you are supposed to write something like this:</p>
<p><pre class="brush: cpp;">
struct quote
{
    typedef std::string result_type;

    std::string operator()(int x) const 
    {
        return &quot;\&quot;&quot; + boost::lexical_cast&lt;std::string&gt;(x) + &quot;\&quot;&quot;; 
    }
};
</pre></p>
<p>C++11 lambdas don&#8217;t have that <code>result_type</code> inside them, so they don&#8217;t directly fit. It goes without saying that we don&#8217;t like this, because the whole point of lambdas is to avoid writing a separate class somewhere else.</p>
<p>It is surely possible to extend boost&#8217;s <code>function_traits</code> so that they can reflect on lambdas. In the past they have not been written to work on general functors because a functor can have multiple overloads of <code>operator()</code>, so you are required to manually pick one of those members before you ask questions. But this position is no longer sensible (if indeed it ever was). The majority of functors will now be lambdas, with a single overload of <code>operator()</code>, and it is (as we can see from this example) perfectly reasonable to want to know the return type of that single overload. A lambda is an alternative to a plain function, and whatever is useful for a function will be useful for a lambda.</p>
<p>But in the meantime, it is interesting to see how many hoops we have to jump through to make the above sample code work as expected. </p>
<p>If you read <a href="http://smellegantcode.wordpress.com/2009/05/22/vc16-has-decltype-in-beta-1-so-linq-to-c0x-looks-a-little-nicer/">my last update on this sordid subject</a> you&#8217;ll know that I don&#8217;t want to have to state the type of something that can be inferred, so I&#8217;m not going to be satisfied by a wrapper template that just adds a <i>manually specified</i> <code>result_type</code> member to my lambda. Ugh! It <i>must</i> be inferred automatically.</p>
<p>Fortunately this is just a matter of using a few simple steps in metaprogramming. Firstly, a template designed to match a member function:</p>
<p><pre class="brush: cpp;">
template &lt;class T&gt;
struct mem_fun_traits { };
</pre></p>
<p>Of course in this general form it will match anything. But we&#8217;ll only bother to specialise it for one case: a pointer to a const member function that accepts one argument:</p>
<p><pre class="brush: cpp;">
template &lt;class R, class C, class A&gt;
struct mem_fun_traits&lt;R (C::*)(A) const&gt; 
{
    typedef R result_type;
    typedef A argument_type;
};
</pre></p>
<p>So if you pass <code>mem_fun_traits</code> the type of a pointer to the <code>operator()</code> within a lambda, you know what it accepts and returns. But how do you get that type argument? With <code>decltype</code> that&#8217;s easy-peasy:</p>
<p><pre class="brush: cpp;">
template&lt;typename T&gt;
struct functor_member {
    typedef decltype(&amp;T::operator()) type;
};
</pre></p>
<p>Armed with these tools, we can write a traits class for our simple one-argument, single-overload functors (and hence, by an extraordinary coincidence, also for C++11 lambdas):</p>
<p><pre class="brush: cpp;">
template &lt;class F&gt;
struct functor_traits
{
    typedef typename functor_member&lt;F&gt;::type member_t;
    typedef mem_fun_traits&lt;member_t&gt; traits;

    typedef typename traits::result_type result_type;
    typedef typename traits::argument_type argument_type;
};
</pre></p>
<p>This is the thing that should be integrated into boost&#8217;s <code>function_traits</code>, to make lambdas work as true replacements for functions. I&#8217;m sure someone&#8217;s working on it.</p>
<p>In the event that this doesn&#8217;t happen, we can shoehorn it together anyway by making a function template that adds type metadata to any single-argument functor:</p>
<p><pre class="brush: cpp;">
template &lt;class F&gt;
class functor_with_traits_t
{
    F f;

public:
    functor_with_traits_t(F f_) : f(f_) {}

    typedef typename functor_traits&lt;F&gt;::result_type result_type;
    typedef typename functor_traits&lt;F&gt;::argument_type argument_type;

    result_type operator()(argument_type a) const { return f(a); }
};

template &lt;class F&gt;
inline functor_with_traits_t&lt;F&gt; functor_with_traits(F f) { return functor_with_traits_t&lt;F&gt;(f); }
</pre></p>
<p>So if you have a plain old lambda like this:</p>
<p><pre class="brush: cpp;">
auto l = [] (int x) { 
    return &quot;\&quot;&quot; + boost::lexical_cast&lt;std::string&gt;(x) + &quot;\&quot;&quot;; 
};
</pre></p>
<p>You can &#8220;fix&#8221; it to have type metadata like so:</p>
<p><pre class="brush: cpp;">
auto l2 = functor_with_traits(l);
</pre></p>
<p>This makes it compatible with boost&#8217;s <code>transformed</code>! Although manually putting in that wrapper each time is pretty tedious. We can work around that by defining our own adapter (let&#8217;s call it <code>selected</code> in slavish imitation of Linq) that just plugs together <code>functor_with_traits</code> and <code>transformed</code>. Sounds simple, though as always the difficulty is in figuring out the types:</p>
<p><pre class="brush: cpp;">
template &lt;class F&gt;
inline um... selected(F f)
{
    return boost::adaptors::transformed(functor_with_traits(f)); 
}
</pre></p>
<p>The <code>um...</code> is &#8220;whatever type we&#8217;re returning&#8221;. Wouldn&#8217;t it be nice if we could put <code>auto</code> there? Well, we almost can: <code>decltype</code> to the rescue as usual:</p>
<p><pre class="brush: cpp;">
decltype(
    boost::adaptors::transformed(
        functor_with_traits(make_ref&lt;F&gt;())
    )
)
</pre></p>
<p>That is: give me the type that would be returned if I called <code>transformed</code>, passing it the result of a call to <code>functor_with_traits</code>, passing it an <code>F</code>. Of course we can&#8217;t assume that <code>F</code> can be default constructed, hence the use of that funny <code>make_ref</code> function that always comes in handy with <code>decltype</code>.</p>
<p>So our completed adaptor is:</p>
<p><pre class="brush: cpp;">
template &lt;class F&gt;
decltype(
    boost::adaptors::transformed(
        functor_with_traits(make_ref&lt;F&gt;())
    )
)
selected(F f)
{
    return boost::adaptors::transformed(functor_with_traits(f)); 
}
</pre></p>
<p>We can use <code>selected</code> in place of <code>transformed</code> and everything is hunky dory. Full example:</p>
<p><pre class="brush: cpp;">
#include &lt;boost/range/algorithm/for_each.hpp&gt;
#include &lt;boost/range/adaptor/filtered.hpp&gt;
#include &lt;boost/range/adaptor/transformed.hpp&gt;

#include &lt;boost/lexical_cast.hpp&gt;

#include &lt;vector&gt;
#include &lt;iostream&gt;
#include &lt;string&gt;

template &lt;class T&gt;
T *make_ptr() { return (T *)0; }

template &lt;class T&gt;
const T &amp;make_ref() { return *(make_ptr&lt;T&gt;()); }

template &lt;class T&gt;
struct mem_fun_traits { };

template &lt;class R, class C, class A&gt;
struct mem_fun_traits&lt;R (C::*)(A) const&gt; 
{
  typedef R result_type;
  typedef A argument_type;
};

template&lt;typename T&gt;
struct functor_member {
    typedef decltype(&amp;T::operator()) type;
};

template &lt;class F&gt;
struct functor_traits
{
	typedef typename functor_member&lt;F&gt;::type member_t;
	typedef mem_fun_traits&lt;member_t&gt; traits;

	typedef typename traits::result_type result_type;
	typedef typename traits::argument_type argument_type;
};

template &lt;class F&gt;
class functor_with_traits_t
{
	F f;

public:
	functor_with_traits_t(F f_) : f(f_) {}

	typedef typename functor_traits&lt;F&gt;::result_type result_type;
	typedef typename functor_traits&lt;F&gt;::argument_type argument_type;

	result_type operator()(argument_type a) const { return f(a); }
};

template &lt;class F&gt;
functor_with_traits_t&lt;F&gt; functor_with_traits(F f) { return functor_with_traits_t&lt;F&gt;(f); }

template &lt;class F&gt;
decltype(boost::adaptors::transformed(functor_with_traits(make_ref&lt;F&gt;()))) selected(F f)
{
	return boost::adaptors::transformed(functor_with_traits(f)); 
}

int main()
{
	using namespace boost::adaptors;

	std::vector&lt;int&gt; numbers;
	numbers.push_back(0);
	numbers.push_back(-1);
	numbers.push_back(4);
	numbers.push_back(-3);
	numbers.push_back(5);
	numbers.push_back(8);
	numbers.push_back(-2);
	
	auto quoted_positives = numbers 
		| filtered([] (int n) { return n &gt;= 0; })
		| selected([] (int x) { 
                    return &quot;\&quot;&quot; + 
                      boost::lexical_cast&lt;std::string&gt;(x) +
                      &quot;\&quot;&quot;;
                  });

	boost::for_each(quoted_positives, [] (std::string n) {
            std::cout &lt;&lt; n &lt;&lt; std::endl; 
        });
	return 0;
}
</pre></p>
<p>(Tested on MSVC++ 16.00.40219.01 and GNU G++ 4.5.3.)</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smellegantcode.wordpress.com/611/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smellegantcode.wordpress.com/611/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smellegantcode.wordpress.com/611/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smellegantcode.wordpress.com/611/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/smellegantcode.wordpress.com/611/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/smellegantcode.wordpress.com/611/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/smellegantcode.wordpress.com/611/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/smellegantcode.wordpress.com/611/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smellegantcode.wordpress.com/611/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smellegantcode.wordpress.com/611/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smellegantcode.wordpress.com/611/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smellegantcode.wordpress.com/611/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smellegantcode.wordpress.com/611/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smellegantcode.wordpress.com/611/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=611&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://smellegantcode.wordpress.com/2011/10/31/linq-to-c-or-something-much-better/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/344e328f9fad1934791575a99830ef80?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">earwicker</media:title>
		</media:content>
	</item>
		<item>
		<title>Secrets of the GNU Make Ninjas: Part 2 &#8211; Introducing MORK</title>
		<link>http://smellegantcode.wordpress.com/2011/10/09/secrets-of-the-gnu-make-ninjas-part-2-introducing-mork/</link>
		<comments>http://smellegantcode.wordpress.com/2011/10/09/secrets-of-the-gnu-make-ninjas-part-2-introducing-mork/#comments</comments>
		<pubDate>Sun, 09 Oct 2011 14:32:32 +0000</pubDate>
		<dc:creator>earwicker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[gnu]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[make]]></category>
		<category><![CDATA[mork]]></category>

		<guid isPermaLink="false">http://smellegantcode.wordpress.com/?p=594</guid>
		<description><![CDATA[Suppose you had written some make scripts that took advantage of all the fun metaprogramming possibilities to make life as simple as possible for you. Imagine what that might look like. There would be a directory representing your whole project. (Everything else we discuss will be under that directory, so I&#8217;ll use full relative paths [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=594&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Suppose you had written some <a href="http://www.gnu.org/software/make/">make</a> scripts that took advantage of all the <a href="http://smellegantcode.wordpress.com/2011/10/01/secrets-of-the-gnu-make-ninjas-part-1/">fun metaprogramming possibilities</a> to make life as simple as possible for you. Imagine what that might look like.</p>
<p>There would be a directory representing your whole project. (Everything else we discuss will be under that directory, so I&#8217;ll use full relative paths from now on.)</p>
<p>It would have a subdirectory containing some general-purpose makefiles that take care of all the messy work, which you usually never need to look at. Let&#8217;s call that subdirectory <code>morkfiles</code>, because <strong>mork</strong> sounds like <code>make</code>, only it&#8217;s funnier, and so is a good name for our fantasy makefile framework.</p>
<p>And there would be one actual <code>makefile</code> under the top level directory, acting as the entry point. It would contain only this:</p>
<p><code>include morkfiles/main.makefile</code></p>
<p>It&#8217;s just there to allow you to conveniently type <code>make</code> at the command line and kick off a build of all targets, or say <code>make clean</code> to wipe everything previously built.</p>
<p><strong>Executables</strong></p>
<p>So, how would you go about writing, say, an executable?</p>
<p>You&#8217;d start with a subdirectory called, say, <code>myexe</code>, where you&#8217;ll build your first executable (hence the boring example name).</p>
<p>You&#8217;ll need a main source file, <code>myexe/myexe.cpp</code>:</p>
<p><pre class="brush: cpp;">
#include &lt;iostream&gt;

int main()
{
	std::cout &lt;&lt; &quot;Hello from myexe&quot; &lt;&lt; std::endl;
}
</pre></p>
<p>Not exactly world-changing, but good enough for now. If you typed <code>make</code> at this point, it would be weird and wrong if it went ahead and assumed anything. No, first we have to undertake the arduous task of writing a morkfile, which would be saved as <code>myexe/morkfile</code> and would contain this:</p>
<p><code>$(this)_type = exe</code></p>
<p>Now, there&#8217;s a lot of stuff to explain there, so I&#8217;ll go slowly&#8230; wait a second, no there isn&#8217;t. It&#8217;s literally one line long. It means, unsurprisingly, &#8220;This thing is going to be an executable&#8221;.</p>
<p>If you run <code>make</code> now, a mini-miracle occurs. Somehow <strong>mork</strong> figures out what to do. And you can run your new program:</p>
<p><code>myexe/bin/myexe</code></p>
<p>or on Windows:</p>
<p><code>myexe\bin\myexe.exe</code></p>
<p>Things to note:</p>
<ul>
<li>We haven&#8217;t told <strong>mork</strong> where to find the <code>myexe</code> directory. It automatically finds all files called <code>morkfile</code>. You can reorganise your source tree willy-nilly, add or remove modules, and never have to update any central configuration file.</li>
<li>Neither did we have to add <code>myexe/myexe.cpp</code> to a list. An executable module is simply assumed to have source files directly inside it. All files with extension <code>.cpp</code> are automatically compiled and linked. We could add more source files under <code>myexe</code> if we wanted to, re-run <code>make</code> and they would be added to our executable.</li>
<li>And of course, we only recompile what we need to. The second time you run make after changing nothing, it immediately reports it has nothing to do (even if you have dozens of modules, it says this very quickly, because only one instance of <code>make</code> is executing).</li>
</ul>
<p>If you&#8217;ve used <code>make</code> before you may be wondering about the business of using the preprocessor to generate include file dependencies. Don&#8217;t worry about it; that stuff is taken care of automatically. No need to say <code>make depends</code> or anything like that. No stupid error messages when you delete a header. It just works.</p>
<p><strong>Libraries</strong></p>
<p>But real projects involve multiple targets &#8211; some are executables, some are static libraries, some are shared libraries (DLLs on Windows). These all have to depend on one another, which typically means that they have to be built in the right order, and include each other&#8217;s header files.</p>
<p>So let&#8217;s make a static library. Create another directory called <code>myutil</code> &#8211; you can put it absolutely anywhere beneath the top-level project directory (even inside <code>myexe</code> though that would be unnecessarily confusing, so don&#8217;t do that).</p>
<p>This time the source file, <code>myutil/myutil.cpp</code>, has no <code>main</code> function. Instead it exposes a function intended to be called from another module:</p>
<p><pre class="brush: cpp;">
#include &lt;myutil.hpp&gt;

std::string myutil_says()
{
	return &quot;world.&quot;;
}
</pre></p>
<p>We also need to write that header file. It goes in a subdirectory of the module, as <code>myutil/include/myutil.hpp</code>:</p>
<p><pre class="brush: cpp;">
#ifndef MYUTIL_INCLUDED
#define MYUTIL_INCLUDED

#include &lt;string&gt;

std::string myutil_says();

#endif//MYUTIL_INCLUDED
</pre></p>
<p>That <code>include</code> subdirectory is where you put all headers that may need to be included by other modules &#8211; it&#8217;s the &#8220;public interface&#8221; of your module. Note that you don&#8217;t have to use the extension <code>.hpp</code>; the only significant thing here is the exact name and location of the <code>include</code> subdirectory.</p>
<p>Finally we have to confront that terrifying task of writing <code>myutil/morkfile</code>:</p>
<p><code>$(this)_type = static</code></p>
<p>Wait a second, that looks vaguely familiar! The only difference from last time is that we&#8217;re giving this module the type <code>static</code> instead of <code>exe</code>.</p>
<p>At this point we can run <code>make</code> and, no surprises, a library is built. It&#8217;s created under <code>myutil/lib</code>, but as we&#8217;ll see, you don&#8217;t even need to know that.</p>
<p>Now let&#8217;s make <code>myexe</code> use <code>myutil</code>. Back in <code>myexe/myexe.cpp</code> we adjust it to:</p>
<p><pre class="brush: cpp;">
#include &lt;iostream&gt;

#include &lt;myutil.hpp&gt;

int main()
{
	std::cout &lt;&lt; &quot;Hello, &quot; + myutil_says() &lt;&lt; std::endl;
}
</pre></p>
<p>So <code>myexe</code> requires <code>myutil</code>. Now, <strong>mork</strong> is helpful, but not telepathic (or smart/stupid enough to try to scan your source files looking for implied dependencies between modules). You have to tell it that <code>myexe</code> requires <code>myutil</code>, by amending <code>myexe/morkfile</code> like so:</p>
<p><code>$(this)_type = exe<br />
<strong>$(this)_requires = myutil</strong><br />
</code></p>
<p>Couldn&#8217;t be simpler, could it? If your module requires another other modules, you list them in the <code>$(this)_requires</code> variable, separated by spaces, and <strong>mork</strong> takes care of adding <code>myutil/include</code> to the compiler options for <code>myexe</code>. It also (of course) deals with the linker options.</p>
<p>But it goes further &#8211; requirements are automatically transitive. That is, if module A requires module B (including some of its headers), and module B requires module C (so some of B&#8217;s headers include some of C&#8217;s headers), then it follows that A will not be able to compile successfully unless it can include headers from both B <em>and</em> C. But this is handled automatically: you only have to configure A to require B, and A will implicitly require C also, and so &#8220;it just works&#8221;.</p>
<p>Note that you only give the name, <em>not the full path</em>, to the required modules. Hence modules need to have unique names within the entire source tree, not just unique paths. This is a good idea anyway because when you distribute your software it&#8217;s usually convenient to put all the binaries (executables and shared libraries) in one directory, so they&#8217;ll need to have unique names.</p>
<p>But it has an additional nice advantage here, which is that even if you have dozens of modules that require one another in complex ways, you can still rearrange the modules under neat organisational subdirectories. It makes no difference to <strong>mork</strong>.</p>
<p><strong>Dynamic Libraries</strong></p>
<p>What about dynamic libraries (shared objects on Linux or DLLs on Windows)? It&#8217;s as easy as amending <code>myutil/morkfile</code> to:</p>
<p><code>$(this)_type = shared</code></p>
<p>That&#8217;s it. Run <code>make</code> again and everything is taken care of &#8211; <strong>mork</strong> even copies the built DLLs or shared objects to the <code>bin</code> directory of any executable that requires them, so it can be instantly executed.</p>
<p><strong>Java</strong></p>
<p>Oh yes, for good measure <strong>mork</strong> can build Java .jar files as well. You just have the <strong>morkfile</strong> look like this:</p>
<p><code>$(this)_type = jar</code></p>
<p>You put your Java source files in a subdirectory called <code>src</code>. The <code>requires</code> works exactly the same &#8211; it controls build order, as with native code modules, but also figures out the <code>classpath</code> settings.</p>
<p>This can be useful if you&#8217;re writing a mixed native/Java project with the emphasis on the native code. (If it was mostly Java, you&#8217;d presumably use Java build tools&#8230; by the way, I have something a little bit like <strong>mork</strong> but layered on <a href="http://ant.apache.org/">ant</a>, and integrating very nicely with Eclipse, so I&#8217;ll write that up sometime soon.).</p>
<p><strong>Other stuff</strong></p>
<p>There are more topics to consider, my favourite being code generation, which is a massively important technique, sadly underused in many projects, and many build tools don&#8217;t seem designed to support it, but <strong>mork</strong> is ready. And how do you integrate unit testing? Also very easy. But this post is long enough already.</p>
<p><strong>ME WANT MORK!</strong></p>
<p>I almost forgot&#8230; here&#8217;s where <strong>mork</strong> lives:</p>
<p><a href="http://earwicker.com/mork">http://earwicker.com/mork</a></p>
<p>It has some examples with it that are very similar to the ones suggested here, but have more complex interdependencies. If you want to use it on Linux, it should just work, assuming you have the usual Gnu development tools.</p>
<p><strong>Windows Quirks</strong></p>
<p>On Windows, you need to install Cygwin with the development tools, and Visual Studio (for maximum interoperability with standard Windows libraries, <strong>mork</strong> uses Visual C++ as the compiler but relies on Cygwin for <code>make</code>, the <code>bash</code> shell and related commands &#8211; it even uses <code>gcc</code>, purely to get <code>make</code>-compatible dependencies).</p>
<p>So you need to have the Visual C++ tools and Cygwin accessible in your environment. The ordering of the <code>PATH</code> environment variable is important. Visual C++ paths need to be at the front of the <code>PATH</code>, so the correct (Microsoft) <code>link.exe</code> is used, then <strong>cygwin\bin</strong> so that the correct (Cygwin) <code>find.exe</code> is used, and finally the rest of your standard Windows <code>PATH</code>.</p>
<p><em>Next time: Part 3, in which we delve into how <strong>mork</strong> works, how to extend it, why the <code>morkfile</code> settings begin with <code>$(this)_</code> and so on.</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smellegantcode.wordpress.com/594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smellegantcode.wordpress.com/594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smellegantcode.wordpress.com/594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smellegantcode.wordpress.com/594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/smellegantcode.wordpress.com/594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/smellegantcode.wordpress.com/594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/smellegantcode.wordpress.com/594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/smellegantcode.wordpress.com/594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smellegantcode.wordpress.com/594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smellegantcode.wordpress.com/594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smellegantcode.wordpress.com/594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smellegantcode.wordpress.com/594/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smellegantcode.wordpress.com/594/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smellegantcode.wordpress.com/594/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=594&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://smellegantcode.wordpress.com/2011/10/09/secrets-of-the-gnu-make-ninjas-part-2-introducing-mork/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/344e328f9fad1934791575a99830ef80?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">earwicker</media:title>
		</media:content>
	</item>
		<item>
		<title>Secrets of the GNU Make Ninjas: Part 1</title>
		<link>http://smellegantcode.wordpress.com/2011/10/01/secrets-of-the-gnu-make-ninjas-part-1/</link>
		<comments>http://smellegantcode.wordpress.com/2011/10/01/secrets-of-the-gnu-make-ninjas-part-1/#comments</comments>
		<pubDate>Sat, 01 Oct 2011 16:28:40 +0000</pubDate>
		<dc:creator>earwicker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[gnu make]]></category>

		<guid isPermaLink="false">http://smellegantcode.wordpress.com/?p=586</guid>
		<description><![CDATA[The title of this post is a lie, of course. I am not a Ninja in GNU Make. I started learning it last week. However, in that time I&#8217;ve cooked up a tiny framework of makefiles that I&#8217;m excited about. To put it another way, I&#8217;ve been driven partially insane by the experience &#8211; how [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=586&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>The title of this post is a lie, of course. I am not a Ninja in <a href="http://www.gnu.org/software/make/">GNU Make</a>. I started learning it last week.</p>
<p>However, in that time I&#8217;ve cooked up a tiny framework of makefiles that I&#8217;m excited about. To put it another way, I&#8217;ve been driven partially insane by the experience &#8211; how else could someone get excited about something as old-fashioned as makefiles?</p>
<p>But if you&#8217;ve seen typical makefiles before, and then you see my beautiful new* alternative way of using them, I guarantee** you&#8217;ll get excited too. You&#8217;ll throw away*** your Visual Studio, Eclipse, NetBeans, Ant, Nant, Maven, and so on. They&#8217;ll seem so clunky in comparison to the elegance of my makefile framework. Oh yes.</p>
<p><em>(* Not really new)<br />
(** Not an actual guarantee)<br />
(*** Except for editing code and debugging and all that other stuff)</em></p>
<p>Note that throughout I&#8217;m talking about GNU make, not any of the many other incompatible makes.</p>
<p>The main cause of the excitement is my surprise when I actually starting <a href="http://www.gnu.org/software/make/manual/make.html">R-ingTFM</a>. Turns out that make is no less than a functional metaprogramming environment.</p>
<p>Like C++ templates, it uses recursively expanded definitions to generate a program. That generation process is &#8220;phase one&#8221;. Then the generated program actually runs, and has imperative/procedural elements to it: that&#8217;s &#8220;phase two&#8221;. Broadly speaking.</p>
<p>This is extremely powerful. Most of the things that people complain about being impossible in make are in fact perfectly possible, even easy, as long as you treat it as what it is: a functional metaprogramming environment.</p>
<p>Also, by the way, because it&#8217;s declarative and functional and so on, it&#8217;s amenable to automatic concurrency: make looks at what you&#8217;ve told it, and figures out which parts can run in parallel, and takes care of it (on Linux, anyway.)</p>
<p>It&#8217;s example time. If you want to play along, start a text editor, save the file as makefile. On Windows you&#8217;ll need to get Cygwin or MinGW, on Mac OS X you&#8217;ll need to install Xcode. Then you can type snippets in and save them, and from the same directory at the command line, run make. (Note that some of these early examples won&#8217;t do anything as we&#8217;re just defining variables.)</p>
<p><code>somevar = a b c d</code></p>
<p>I&#8217;ve created a variable called samovar, and stored a string containing four letters separated by spaces. Space separated lists are special &#8211; as well as being used wholesale as a simple string, there are handy built-in functions that treat them as lists.</p>
<p>This leads to <strong>Important Conclusion 1:</strong> spaces in filenames are bad. Just don&#8217;t put spaces in any of your directory or source files that you want make to deal with, and you&#8217;ll be fine. Probably seems a bit backward to you at first, but it turns out to be a fine trade-off.</p>
<p>To get the value of a variable:</p>
<p><code>othervar = before$(somevar)after</code></p>
<p>Now othervar contains <code>beforea b c dafter</code> because I referred to samovar in parentheses with a dollar sign in front, which tells make to substitute the value of the named variable.</p>
<p>Do those two definitions have to be in a particular order? What if I gave make the othervar definition at the top of the file and then the samevar definition after that? Can you guess?</p>
<p>The answer is due to the way make expands variables. My definition of othervar is stored exactly as I wrote it: the dollar sign, the parentheses, the somevar, are not expanded. Only when I actually refer to othervar in some context will make actually carry out the expansion, and by that stage it will know all the variable definitions.</p>
<p>Hence this is a problem:</p>
<p><code>a = $(b)<br />
b = $(a)</code></p>
<p>Torturing make like that will just get you error messages.</p>
<p>You can in fact cause the expansion to happen at the point where you define the variable, by using <code>:=</code> instead of plain <code>=</code>. For example, if you wanted to find all the png files in the images directory, you could say (using the built-in wildcard function):</p>
<p><code>all_pngs := $(wildcard images/*.png)</code></p>
<p>(<strong>Important Conclusion (IC)2</strong>: use forward slashes for file paths. On Windows, Cygwin will deal with it.)</p>
<p>The advantage of using := is that the directory gets scanned once and then all_pngs will contain a space-separated list of filenames. If you used plain = then the directory would get scanned every time you referred (directly or indirectly) to all_pngs.</p>
<p>And hence, <strong>IC3:</strong> variables defined with plain = are in fact functions. When you refer to them, you&#8217;re really calling them. They&#8217;re functions that don&#8217;t take any arguments, but they are still functions. They are in a simple sense closures: they close over the whole single variable namespace.</p>
<p><strong>IC4:</strong> choose variable names carefully. One big namespace =&gt; danger of accidental clashes.</p>
<p>Actually you can pass arguments to variables when you refer to them. There&#8217;s a built-in function called call:</p>
<p><code>square_brackets = [ $(1) ]</code></p>
<p><code>example := hello $(call square_brackets,world)</code></p>
<p>Now example contains <code>hello [ world ]</code> &#8211; note how you can get the argument&#8217;s value in the definition by referring to its position (one-based).</p>
<p>Back to our list of pngs. I want to get a list of jpgs that would have the same base names as those pngs:</p>
<p><code>image_basenames = $(basename $(all_pngs))</code></p>
<p>Note how I don&#8217;t have to say &#8220;for each thing on the list, do something to it&#8221;. The built-in <code>basename</code> is list-aware. That is, it breaks up the input according to spaces, and then operates on each piece, and finally joins them back into a single string with space separators. To finish the example:</p>
<p><code>jpg_names = $(addsuffix .jpg,$(image_basenames))</code></p>
<p>Or to do both steps in one line:</p>
<p><code>jpg_names = $(addsuffix .jpg,$(basename $(all_pngs)))</code></p>
<p>There&#8217;s also a built-in <code>foreach</code>, which is like a general list operator, analogous to <code>Select</code> in Linq, or <code>map</code> in most other functional libraries. If you&#8217;re up on your monads, you&#8217;ll already have realised something semi-cool.</p>
<p>The core of a monad is the <code>bind</code> operator. For list monads this goes by various names depending on the language: in Linq it&#8217;s <code>SelectMany</code>, in Scala it&#8217;s <code>flatMap</code>. But it always does the same thing: for each item of the list, create a new list (somehow), and then join all the little lists together into one big list. The input is a list, the output is a list: that makes it composable.</p>
<p>In make the built-in list operators are all automatically monadically composable in that way, because a list is a string and a string is a list. (If the string has no spaces, it&#8217;s a list of one item, right?) So if you have a list-of-lists-of strings, then you already have a list-of strings. They&#8217;re indistinguishable. I said semi-cool because what if you don&#8217;t want the list to be flattened? But mostly you do.</p>
<p><strong>IC5</strong>: This make stuff has all kinds of deep analogical relationships to interesting things! </p>
<p>Everything we&#8217;ve done so far is actually useless because it just defines string (or lists, same thing). With some shell incantations we can run make and print out the final value of a variable:</p>
<p><code>make -p | grep 'my_variable_name = '</code></p>
<p>But to actually cause make to do something we have to define a rule. The simplest kind of rule is:</p>
<p><code>
<pre>files-to-build : required-files
	shell command
	shell command
	and so on
</pre>
<p></code><br />
The shell commands are executed as normal operating system shell programs. The required-files and files-to-build are of course space separated. You can refer to variables anywhere. Note that each shell command has a tab indentation, and it must be a proper tab character, not spaces.</p>
<p><strong>IC6</strong>: Make depends on a shell, so for portable makefiles, use UNIX-style shells on all systems (it&#8217;s the default on Windows with Cygwin anyway).</p>
<p><strong>IC7</strong>: Use an editor that can make tab characters visible in some way.</p>
<p>The commands under a rule will only be executed if any of files-to-build has a timestamp that is earlier than any of required-files (or doesn&#8217;t exist at all). If any of required-files doesn&#8217;t exist, then make will complain, unless there is another rule in which that missing file appears in the files-to-build list, in which case make will run that other rule first, in the hope that it will cause the missing file to miraculously appear.</p>
<p>The upshot is that if you put a non-existent filename on the left, and nothing on the right, and then you make sure your shell commands don&#8217;t create the non-existent file, then you have something that will run every time you execute make:</p>
<p><code>
<pre>run_every_time:
	@echo Hello, world!</pre>
<p></code></p>
<p>When you run make, it will notice that run_every_time doesn&#8217;t exist, and go ahead with the commands in an attempt to make it. Note that it is not a terrible crime to fail to generate the target file of a rule, but most rules should be designed to do that. Most problems people get into with make involve trying to use phony rules to do imperative programming.</p>
<p><strong>IC8</strong>: This is a tool for generating output files from input files, doing the minimum amount of work each time it is run. Each rule should take in some input files and write out some output files. Avoid writing rules that try to cheat the system; otherwise you&#8217;ll eventually get into a mess.</p>
<p>Now, what we&#8217;ve seen so far comprises the standard feature set of make as used in most makefiles. But I mentioned metaprogramming before; that&#8217;s not possible with these features along. Consider:</p>
<p><code>a = b = won't work<br />
$(a)</code></p>
<p>That is, in variable a I store an expression that would (if it appeared on its own) assign the value <code>won't work</code> to b. And then on the next line I refer to that variable, hoping that this will cause b to be defined. But it&#8217;s a syntax error.</p>
<p>However, with another built-in, <code>eval</code>, we can do this:</p>
<p><code>$(eval $(a))</code></p>
<p>And that works! The variable b gets defined. So we can generate statements and then get them evaluated. But some things in make are inherently multi-line: rules especially. Can we define multi-line variables and so automate the declaring of rules? You&#8217;re darn tootin&#8217; we can:</p>
<p><code>
<pre>define my_recipe
cake: flour eggs sugar butter spices
	preheat oven
	mix sugar and butter
	stir in eggs
	stir in flour
	bake
	oh, forgot to add spices
endef
</pre>
<p></code></p>
<p>Note that <code>my_recipe</code> is just a variable. And by the way, did I mention that we can pass parameters to eval? I didn&#8217;t? Well, consider it duly mentioned.</p>
<p>This is where we can experience the true joy of metaprogramming, because we&#8217;re using the <code>$(syntax)</code> of variable references to generate code that must then go on to declare variable references that will only make sense later on. Some variables should be expanded before eval interprets its input. Others should go through eval unmolested so that they can be expanded later. To arrange this, we have to tell make to ignore some of our variable references by writing two dollars together: $$ is the escape sequence for a dollar. So eval ignores those variable references and &#8220;outputs&#8221; one dollar as a result, which can then be seen by make when it actually tries to evaluate things later on.</p>
<p>So, <strong>IC9</strong>: anything you&#8217;d declare in a makefile can be auto-generated within make from a multi-line template stored in a variable. There is never any need to repeat yourself. Say it once, say it loud: I&#8217;m metaprogramming and I&#8217;m proud.</p>
<p>It can get quite hair-raising when you&#8217;re trying understand snippets of metaprogramming, because two levels are intermingled. It is <a href="http://smellegantcode.wordpress.com/2011/07/25/specifying-how-to-specify-a-bnf-like-grammar-in-a-bnf-like-grammar/">code talking about code</a>. If you like that kind of thing, you&#8217;re a proper nerd like me. Hi!</p>
<p>Anyway, with these tools of functional metaprogramming in our back pocket, we can easily get make to solve a huge range of problems. Yes, easily. And we can make it so it runs fast. Yes, fast!</p>
<p>And yet so many blogs are full of people complaining about how <a href="http://www.conifersystems.com/whitepapers/gnu-make/">make wouldn&#8217;t let them do this or that</a>, or it took ten minutes to compile each file, so they came up with something else entirely. It&#8217;s a tragedy. Like the LISP programmers would say, every non-trivial C program contains an ad hoc implementation of LISP. Well, every new build-directing tool is basically the same as make, except that the author didn&#8217;t bother to RTF-make-M, so they didn&#8217;t realise they didn&#8217;t need to write their own version.</p>
<p>The number one cause of irritations with make is a technique called recursive make. When you have to build five static libraries, three dynamic libraries and four executables, plus some code generation, its often suggested that you should have a main makefile that visits each module&#8217;s directory and there runs another instance of make. But this turns out to be a very bad idea, <a href="http://miller.emu.id.au/pmiller/books/rmch/">as noted in this famous paper</a>. I tried recursive make last week, and I&#8217;m not going to use it ever again. It runs counter to your nerd instincts to reject anything recursive, of course, because recursion is such an important, primal nerd totem. But this isn&#8217;t the same as abandoning recursion altogether! All the techniques described above are powerfully recursive &#8211; much more so than the specific technique known as &#8220;recursive make&#8221;, where you actually launch a separate instance. That technique sucks.</p>
<p><em><a href="http://smellegantcode.wordpress.com/2011/10/09/secrets-of-the-gnu-make-ninjas-part-2-introducing-mork/">In Part 2</a>: a quick tutorial of my fantasy make framework, where everything is easy and fast. And it&#8217;s not just a fantasy!</em></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smellegantcode.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smellegantcode.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smellegantcode.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smellegantcode.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/smellegantcode.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/smellegantcode.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/smellegantcode.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/smellegantcode.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smellegantcode.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smellegantcode.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smellegantcode.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smellegantcode.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smellegantcode.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smellegantcode.wordpress.com/586/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=586&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://smellegantcode.wordpress.com/2011/10/01/secrets-of-the-gnu-make-ninjas-part-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/344e328f9fad1934791575a99830ef80?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">earwicker</media:title>
		</media:content>
	</item>
		<item>
		<title>Specifying how to specify a BNF-like grammar in a BNF-like grammar</title>
		<link>http://smellegantcode.wordpress.com/2011/07/25/specifying-how-to-specify-a-bnf-like-grammar-in-a-bnf-like-grammar/</link>
		<comments>http://smellegantcode.wordpress.com/2011/07/25/specifying-how-to-specify-a-bnf-like-grammar-in-a-bnf-like-grammar/#comments</comments>
		<pubDate>Mon, 25 Jul 2011 14:53:10 +0000</pubDate>
		<dc:creator>earwicker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://smellegantcode.wordpress.com/?p=583</guid>
		<description><![CDATA[I love this bit of the XML specification, the part where in definitions 47-50, it states how to use * to mean &#8220;the preceding can appear zero or more times&#8221; and + to mean &#8220;the preceding can appear one or more times&#8221; and ? to mean &#8220;the preceding is optional&#8221; and &#124; to mean &#8220;either [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=583&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I love <a href="http://www.w3.org/TR/xml/#sec-element-content">this bit of the XML specification</a>, the part where in definitions 47-50, it states how to use * to mean &#8220;the preceding can appear zero or more times&#8221; and + to mean &#8220;the preceding can appear one or more times&#8221; and ? to mean &#8220;the preceding is optional&#8221; and | to mean &#8220;either of these may appear&#8221;, but it does this using those very same symbols, with the same meanings.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smellegantcode.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smellegantcode.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smellegantcode.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smellegantcode.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/smellegantcode.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/smellegantcode.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/smellegantcode.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/smellegantcode.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smellegantcode.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smellegantcode.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smellegantcode.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smellegantcode.wordpress.com/583/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smellegantcode.wordpress.com/583/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smellegantcode.wordpress.com/583/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=583&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://smellegantcode.wordpress.com/2011/07/25/specifying-how-to-specify-a-bnf-like-grammar-in-a-bnf-like-grammar/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/344e328f9fad1934791575a99830ef80?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">earwicker</media:title>
		</media:content>
	</item>
		<item>
		<title>Dao De Web (or: The Painful History of the URL)</title>
		<link>http://smellegantcode.wordpress.com/2011/04/19/dao-de-web-or-the-painful-history-of-the-url/</link>
		<comments>http://smellegantcode.wordpress.com/2011/04/19/dao-de-web-or-the-painful-history-of-the-url/#comments</comments>
		<pubDate>Tue, 19 Apr 2011 07:27:15 +0000</pubDate>
		<dc:creator>earwicker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[history]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://smellegantcode.wordpress.com/?p=551</guid>
		<description><![CDATA[Think of an application as being like a building. It has several rooms, and the URL tells you which room you’re in: reception accounts-dept meeting-rooms/1 meeting-rooms/2 bathroom This is the ideal way to use the URL because it will fit perfectly with how the user expects the browser to work. The URL tells the application [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=551&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Think of an application as being like a building. It has several rooms, and the URL tells you which room you’re in:</p>
<ul>
<li><code>reception</code></li>
<li><code>accounts-dept</code></li>
<li><code>meeting-rooms/1</code></li>
<li><code>meeting-rooms/2</code></li>
<li><code>bathroom</code></li>
</ul>
<p>This is the ideal way to use the URL because it will fit perfectly with how the user expects the browser to work. The URL tells the application which room to display, and so the user can:</p>
<ul>
<li>Press the Back button to go back to the room they were in just now.</li>
<li>Press the Forward button if they change their mind again.</li>
<li>Bookmark (or “favourite”) the rooms they visit most frequently.</li>
<li>Look at their History to see which rooms they’ve been in.</li>
<li>Press the Refresh button to see an up-to-date view.</li>
<li>Copy the URL from the address bar, paste it in an email and send it to a co-worker to say “Look at this!”</li>
<li>Click a link (an underlined piece of text concealing a URL) to get to a different room.</li>
<li>Right-click and choose <em>Open in new tab</em> to see a room on a different tab in their browser.</li>
</ul>
<p>The above operations are the core features of the web browser. People expect them to work, and they are part of the reason why web applications have an advantage over custom thick client software. The mantra should always be:</p>
<blockquote><p>If you want to know where you are, look at the URL</p></blockquote>
<p>The interesting thing is that in many interactive web-based applications, including some of the most widely-used commercial sites on the Web, URLs are not used in this way, and they break much of that idealised functionality.</p>
<h2>State</h2>
<p>In the real world we learn to expect our environment to be stateful. Suppose you go up to your desk and arrange things to your liking, and then you turn away for a second. But it’s a magical desk: when you turn back to look at it again, it has “reset” itself! All the things you moved have somehow moved back to their original positions.</p>
<p>That would be usually very counter-intuitive and unhelpful (not to mention scary). So there’s nothing more annoying than an application that plays dumb and doesn’t remember what you were doing with it five minutes ago.</p>
<p>On the other hand, imagine checking into your hotel room only to find that the room is still in the state that the previous guest created: wet towels on the floor, bed not made, and so on. There should be a strict boundary between hotel guests so they don’t have visibility of another guest’s room state. So state has to have a well-defined and limited scope during which it is applicable.</p>
<p>So, can the URL store the state of a web application? Obviously there&#8217;s more to the state of a building than the name of the room you&#8217;re currently in. It is possible to encode various other pieces of information into plain text and then append that to the URL. But would that be a good idea?</p>
<h2>The Accidental Time Machine</h2>
<p>Consider an online store. Suppose when you visit the page that shows you what’s in your cart, the URL was:</p>
<p><code>shoppingCart?contents=12,8,442,23</code></p>
<p>That list of numbers contains the product codes of all the things you put in your cart. Each time you add a product to your cart, the URL changes, and the previous URL is added to your browsing history. And this in turn means that your browsing history contains previous <em>versions</em> of that list of purchases.</p>
<p>So that’s a crazy implementation! When you press the Back button to go back to your shopping cart, it won’t show you what it contains <em>now</em>. Instead it will show you what it contained at some previous time.</p>
<p>So instead of the <em>Back</em> button allowing you to retrace your steps, it allows you to <em>move backwards through time</em>! Or to put it less outrageously, it sort of works a bit like an <em>Undo </em>button.</p>
<p>You may have encountered this problem in real online stores; one example for many years was <a href="http://www.play.com">play.com</a>, although it is fixed now.</p>
<h2>The Receptionist Fired Twice</h2>
<p>An even worse problem occurs when the URL in the address bar represents a command. Suppose you want to go into reception and fire the receptionist. If that was represented on the address bar:</p>
<p><code>reception?fireReceptionist=true</code></p>
<p>The page comes back telling you that you successfully fired the receptionist. You then visit a meeting room to tell them the news. While you’re in that room, <em>a new receptionist is sent by the agency</em>.</p>
<p>Then you hit the Back button to go back to reception, and… oh dear. You just fired the new receptionist as well! When you go back in the browser history, the URL is sent to the server exactly the same as the first time, and the server obeys it. This is even worse than the time machine bug. So applications have to employ all kinds of trickery to stop commands being obeyed more than once.</p>
<p>You may have seen some sites that plead with you not to press the Back button during some process &#8211; issuing a credit card payment, for example. It&#8217;s obviously not a great experience for the user, but for many years it was the best that could be done in some situations.</p>
<h2>Another Page Expires</h2>
<p>The most common problem of all is caused by POST. This is another way to send requests to the server, favoured because it allows a larger amount of data to be sent, even large files, but it has a very unfortunate side-effect. It puts an entry into the browser’s history that doesn’t work properly. When the user presses their Back button, they typically just get a confusing error message:</p>
<blockquote><p>The page you requested was created using information you submitted in a form. This page is no longer available. As a security precaution, Internet Explorer does not automatically resubmit your information for you.</p></blockquote>
<p>This still happens today on Amazon when you try to back out of buying whatever&#8217;s in your shopping cart. One workaround favoured by experienced users is to right-click on the Back button (click and hold on the Mac) to reveal a popup menu of recent history, so you can skip the problematic entry in your history and instead go to the page before that one. But you can&#8217;t do that on the iPad. In any case, instead of being a helpful UI, the browser has been transformed into a puzzle to be solved.</p>
<p>A large proportion of web applications have historically suffered from these and other issues. It’s only in the last five years or so that a pattern has emerged that allows us to build dynamic applications and yet still consistently deliver the original intended user experience of the web.</p>
<h2>Some Modern Websites</h2>
<p>Next time you look at a website, look closely at the URL in your browser’s address bar. Here’s what the Gmail address bar looks like:</p>
<p><a href="http://smellegantcode.files.wordpress.com/2011/04/gmail.png"><img class="alignnone size-full wp-image-559" title="gmail" src="http://smellegantcode.files.wordpress.com/2011/04/gmail.png?w=600&#038;h=126" alt="" width="600" height="126" /></a></p>
<p>And here&#8217;s Twitter (when you&#8217;re signed in):</p>
<p><a href="http://smellegantcode.files.wordpress.com/2011/04/twitter.png"><img class="alignnone size-full wp-image-563" title="twitter" src="http://smellegantcode.files.wordpress.com/2011/04/twitter.png?w=600&#038;h=191" alt="" width="600" height="191" /></a></p>
<p>The special ingredient these have in common is the hash symbol: #. That marks a division in a URL. Everything on the left, before the hash, is an instruction to the remote Web server, and so is interpreted on the server side. Everything on the right, starting with the hash, <em>is never used by the server.</em></p>
<p>In normal Web development terminology (which can be confusingly overloaded) the part of URL starting at the hash symbol is also known as “the hash” of the URL. So in the Gmail example, the hash is:</p>
<p><code>#inbox</code></p>
<p>If the server is going to ignore this part of the URL, why is it there?</p>
<h2>A Brief History of Hash</h2>
<p><a href="http://smellegantcode.files.wordpress.com/2011/04/wikicontents.png"><img class="alignright size-full wp-image-565" title="wikicontents" src="http://smellegantcode.files.wordpress.com/2011/04/wikicontents.png?w=600" alt=""   /></a>The original purpose of the hash (and still a perfectly good use for it) was to allow the creation of links to other places within the same document. For example, visit this page on Wikipedia:</p>
<p><a href="http://en.wikipedia.org/wiki/Web_browser#Features">http://en.wikipedia.org/wiki/Web_browser</a></p>
<p>It has a contents box <em>(right) </em>that just contains a few links to sections of the document. When you click the <em>Features</em> link, the browser’s address bar changes to:</p>
<p><a href="http://en.wikipedia.org/wiki/Web_browser#Features">http://en.wikipedia.org/wiki/Web_browser#Features</a></p>
<p>The key point is that the browser doesn’t contact the server when the hash changes or is added. That part of the URL is of no interest to the server, so there’s no need to contact it again. By default, all the browser does when the hash changes is scan through the HTML looking for an element that has an ID that is the same as the new hash, and scrolls the page so that the identified element is at the top of the window.</p>
<p>If there is no element in the document with that ID, <em>it doesn’t do anything</em>. So you can edit the hash to say anything you want, and your browser will just ignore you.</p>
<p>But otherwise, hash URLs are treated just like server URLs: they go into the browser history. You can press the Back button to revisit then, bookmark them, and so on.</p>
<p>This is the key to solving the various issues with the browser interactive applications. The hash part of a URL is for linking to things <em>within the current document</em>, instead of linking to other documents.</p>
<p>But now suppose you were to accept the following astonishing principle:</p>
<blockquote><p>An interactive application is a single document.</p></blockquote>
<p>Therefore it follows unavoidably that to support navigation within the application, you would use only hash URLs. That is, you would only vary the stuff after the hash symbol. Every navigation performed by the user within the application will not <em>directly</em> result in a round-trip to the server. Something else has to happen instead.</p>
<p>The default behaviour, scrolling to an element with the specified ID, isn&#8217;t much use generally speaking. But with JavaScript we can respond to a change in the URL in any way we like.</p>
<h2>Detecting a Hash Change</h2>
<p>Newer versions of many browsers have a built-in scripting event that is raised whenever the URL changes. In less capable browsers it is necessary to start a timer that will periodically check the URL to see if it has changed. Of course, it&#8217;s simple enough to hide this inside a jQuery plugin, and sure enough, <a href="http://benalman.com/projects/jquery-hashchange-plugin/">here&#8217;s such a plugin</a>.</p>
<p>For even greater convenience, you will want to bind different handlers to a specific URL pattern. You could do that by handling the <code>hashchange</code> event and then parsing the URL manually, or you could use a library to do this for you. For this I&#8217;ve found <a href="http://sammyjs.org/">sammy.js</a> to be excellent. For example, you can register a handler to render meeting rooms:</p>
<p><code>this.get('#/meeting-rooms/:roomNumber', function(context) {</code></p>
<p>Within the handler, you can access <code>context.params.roomNumber</code> to get the variable part of the URL, because any path segment prefixed with a colon denotes a parameter.</p>
<p>The remaining question is: now that we&#8217;ve utterly eliminated the server from this picture, how do we bring it back?</p>
<h2>Ajax To the Max</h2>
<p>The answer is that we call it when we want to. The browser doesn&#8217;t dictate anything. Calls to &#8220;the backend&#8221; are decoupled from the UI, and it&#8217;s entirely up to us how we re-couple them.</p>
<p>The short answer is simple and obvious: when you need some more data, or you need to update some data stored on the server, you make a call. You may even find it convenient to make multiple calls in sequence or in parallel, depending on how much control you have over the backend&#8217;s API &#8220;surface&#8221;.</p>
<p>If you sign into Twitter and use a logging proxy like the wondrous <a href="http://www.fiddler2.com/fiddler2/">Fiddler</a>, you will see that once the main page of the application has been downloaded, practically all subsequent calls back to the server are to <code>api.twitter.com</code> and they return very clean JSON data structures, rather than HTML formatted on the server. All the updates to the page are performed in the client-side JavaScript.</p>
<p>And this allows the user experience to take on a new slickness &#8211; it isn&#8217;t necessary to discard and rebuild the whole page. You can update some patch of it, and perform an animated transition. There are suddenly a lot more possibilities for making your application more modern, fresh and engaging, and they are <em>easy</em> to do, especially with jQuery and its army of plugins &#8211; the Web is full of examples, because jQuery is so widely used already.</p>
<h2>What About Search Engines?</h2>
<p>The scope of this kind of architecture is limited by a simple fact: search engines (which is to say: Google) will not execute JavaScript code during their indexing processes, and so will not follow your hash-links.</p>
<p>So if you want Google to index your site, you either cannot use this approach, or you&#8217;ll need to develop a basic old-school version of the site so that Google can index it. It doesn&#8217;t have to be as snazzy or helpful as the JavaScript version &#8211; it just has to serve up all the indexable text.</p>
<p>Of course, a great many web applications are behind an &#8220;authentication wall&#8221; &#8211; the user must sign in before they can see anything. Such applications don&#8217;t want Google to index their data, and so they don&#8217;t need to worry about this.</p>
<p>Another possibility is that you may want to support users who suffer from the same limitation as Google&#8217;s indexer &#8211; they don&#8217;t want to execute JavaScript and choose to disable it. It&#8217;s up to you whether you see that as a market you need to serve, of course. It&#8217;s a rapidly shrinking market &#8211; and in fact some newer browsers don&#8217;t even have an option to switch JavaScript off.</p>
<p>Much more important is the issue of accessibility: how does a blind person access your site? But this is not actually solved automatically by the classic web model &#8211; you have to design accessibility. And you can do this for a heavily JavaScript-based application too. </p>
<p>The unfortunate truth is that most companies neglected accessibility when working under the classic web model, and they&#8217;ll probably continue to neglect it in the future, but this is an underlying problem that probably cannot be solved by technology.</p>
<h2>The Unnameable Way<em><strong></strong></em></h2>
<p>The term AJAX was introduced to describe an early variant of this pattern: the X stood for XML, which has nothing to recommend it nowadays. And when most people say AJAX, they are probably still talking about a traditional web application that contains a few specific uses of scripted calls to the server, but otherwise suffers from the flaws we identified earlier.</p>
<p>By fully embracing the pattern, those flaws can be solved. And to be clear, the pattern is:</p>
<ul>
<li>A single static <code>.html</code> document establishes the permanent structural framework of the application, and pulls in the script that registers handlers for certain hash URL patterns.</li>
<li>Those handlers update the UI to reflect the location specified in the current hash URL, probably by making calls back to a clean JSON-based API exposed at the server.</li>
<li>State that is not related to navigational location never appears in the URL, and nor do commands that have side-effects on state, because URLs can be revisited via the browser&#8217;s history features.</li>
</ul>
<p>Naturally there&#8217;s an ironic footnote to this story.</p>
<h2>The Ironic Footnote</h2>
<p>Back in the early 1990s, people wrote things that were grandly called &#8220;client-server applications&#8221;. In practise, this meant a Visual Basic UI with an RDBMS storing the data. Microsoft dominated the desktop, and it seemed only a matter of time before they would dislodge Oracle from the server side as well.</p>
<p>The web seemed to blow this model out of the water, because people were &#8211; quite rightly &#8211; impressed by the browser as a universal window to the information world and began to view it as something that applies to everything. The old model was derided as &#8220;thick client&#8221;, in contrast to the much-admired &#8220;thin client&#8221; represented by the browser.</p>
<p>In truth, the client server approach was evolving towards a &#8220;not-too-thick&#8221; client model, because the RDBMS was a fairly capable development platform itself. Business logic <em>could</em> be moved into stored procedures. Even so, that implied an unnecessary dependency on a highly proprietary platform, and was generally avoided for that reason.</p>
<p>One proposed alternative, prior to the Web, was the business logic server, embodied in products like <a href="http://en.wikipedia.org/wiki/Microsoft_Transaction_Server">Microsoft&#8217;s Transaction Server (MTS)</a>. There was much talk of tiered applications: the client (in Visual Basic, of course), the business logic in MTS, and the data layer in SQL Server. But again, it was obviously proprietary, and it was hard to see how it might fit into the all-conquering Web, so it was swept into the dustbin of history.</p>
<p>The <a href="http://en.wikipedia.org/wiki/LAMP_(software_bundle)">LAMP</a> stack was all-conquering! Or so it seemed.</p>
<p>The strange truth is that the built-in capabilities of the browser actually did <em>not</em> make it at all easy to support the browser&#8217;s navigation model in an interactive application. In fact it made it very easy to break it. If you wanted a nice browsable UI, it would have been easier to just add Back and Next buttons to your crummy Visual Basic application!</p>
<p>Where we have now arrived, the world doesn&#8217;t look too dissimilar to the proposed pre-Web model. The vital difference is that it is a victory for the vendor-neutral approach:</p>
<ul>
<li>There is now a great variety of ways to store data, not all of them SQL-based.</li>
<li>The business logic API is exposed by any Web server, simply so it can be called directly in standard ways from any browser.</li>
<li>And within the browser we can write &#8220;not-too-thick&#8221; clients that present an ideal user interface into the business logic.</li>
</ul>
<p>We took quite a tortured route to get to the destination. But we&#8217;re there now. Phew.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smellegantcode.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smellegantcode.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smellegantcode.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smellegantcode.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/smellegantcode.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/smellegantcode.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/smellegantcode.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/smellegantcode.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smellegantcode.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smellegantcode.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smellegantcode.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smellegantcode.wordpress.com/551/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smellegantcode.wordpress.com/551/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smellegantcode.wordpress.com/551/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=551&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://smellegantcode.wordpress.com/2011/04/19/dao-de-web-or-the-painful-history-of-the-url/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/344e328f9fad1934791575a99830ef80?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">earwicker</media:title>
		</media:content>

		<media:content url="http://smellegantcode.files.wordpress.com/2011/04/gmail.png" medium="image">
			<media:title type="html">gmail</media:title>
		</media:content>

		<media:content url="http://smellegantcode.files.wordpress.com/2011/04/twitter.png" medium="image">
			<media:title type="html">twitter</media:title>
		</media:content>

		<media:content url="http://smellegantcode.files.wordpress.com/2011/04/wikicontents.png" medium="image">
			<media:title type="html">wikicontents</media:title>
		</media:content>
	</item>
		<item>
		<title>The Cancel Button Puzzle</title>
		<link>http://smellegantcode.wordpress.com/2011/04/16/the-cancel-button-puzzle/</link>
		<comments>http://smellegantcode.wordpress.com/2011/04/16/the-cancel-button-puzzle/#comments</comments>
		<pubDate>Sat, 16 Apr 2011 11:01:55 +0000</pubDate>
		<dc:creator>earwicker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[UI mistakes]]></category>

		<guid isPermaLink="false">http://smellegantcode.wordpress.com/?p=548</guid>
		<description><![CDATA[It&#8217;s rare to see a genuine example of this classic UI blunder in a product, but it&#8217;s always a delight &#8211; like encountering an old friend! This is the first one I&#8217;ve seen in a Mac product, where the Cancel button is normally placed first (the opposite arrangement to Windows), and I&#8217;m not sure, but [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=548&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s rare to see a genuine example of this classic UI blunder in a product, but it&#8217;s always a delight &#8211; like encountering an old friend!</p>
<p>This is the first one I&#8217;ve seen in a Mac product, where the Cancel button is normally placed first (the opposite arrangement to Windows), and I&#8217;m not sure, but that seems to make the problem slightly worse.</p>
<p><a href="http://smellegantcode.files.wordpress.com/2011/04/cancel.jpg"><img class="alignnone size-full wp-image-547" title="cancel" src="http://smellegantcode.files.wordpress.com/2011/04/cancel.jpg?w=600" alt=""   /></a></p>
<p>Pavtube Bytecopy for Mac OS X. <a href="http://www.pavtube.com">http://www.pavtube.com</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smellegantcode.wordpress.com/548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smellegantcode.wordpress.com/548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smellegantcode.wordpress.com/548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smellegantcode.wordpress.com/548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/smellegantcode.wordpress.com/548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/smellegantcode.wordpress.com/548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/smellegantcode.wordpress.com/548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/smellegantcode.wordpress.com/548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smellegantcode.wordpress.com/548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smellegantcode.wordpress.com/548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smellegantcode.wordpress.com/548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smellegantcode.wordpress.com/548/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smellegantcode.wordpress.com/548/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smellegantcode.wordpress.com/548/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=548&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://smellegantcode.wordpress.com/2011/04/16/the-cancel-button-puzzle/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/344e328f9fad1934791575a99830ef80?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">earwicker</media:title>
		</media:content>

		<media:content url="http://smellegantcode.files.wordpress.com/2011/04/cancel.jpg" medium="image">
			<media:title type="html">cancel</media:title>
		</media:content>
	</item>
		<item>
		<title>Filtering exceptions inside an iterator method</title>
		<link>http://smellegantcode.wordpress.com/2011/01/24/filtering-exceptions-inside-an-iterator-method/</link>
		<comments>http://smellegantcode.wordpress.com/2011/01/24/filtering-exceptions-inside-an-iterator-method/#comments</comments>
		<pubDate>Mon, 24 Jan 2011 10:15:57 +0000</pubDate>
		<dc:creator>earwicker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[stackoverflow]]></category>
		<category><![CDATA[yield return]]></category>

		<guid isPermaLink="false">http://smellegantcode.wordpress.com/?p=536</guid>
		<description><![CDATA[This was an interesting Stack Overflow question from last week. At first glance it seems to be impossible, but if you think about what yield return actually does, an answer presents itself.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=536&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://stackoverflow.com/questions/4710897/getting-reference-to-an-exception-in-finally-block-in-an-iterator/4736238#4736238">This was an interesting Stack Overflow question from last week</a>. At first glance it seems to be impossible, but if you think about what <code>yield return</code> actually does, an answer presents itself.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smellegantcode.wordpress.com/536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smellegantcode.wordpress.com/536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smellegantcode.wordpress.com/536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smellegantcode.wordpress.com/536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/smellegantcode.wordpress.com/536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/smellegantcode.wordpress.com/536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/smellegantcode.wordpress.com/536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/smellegantcode.wordpress.com/536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smellegantcode.wordpress.com/536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smellegantcode.wordpress.com/536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smellegantcode.wordpress.com/536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smellegantcode.wordpress.com/536/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smellegantcode.wordpress.com/536/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smellegantcode.wordpress.com/536/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=536&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://smellegantcode.wordpress.com/2011/01/24/filtering-exceptions-inside-an-iterator-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/344e328f9fad1934791575a99830ef80?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">earwicker</media:title>
		</media:content>
	</item>
		<item>
		<title>Call-with-current-continuation demystified</title>
		<link>http://smellegantcode.wordpress.com/2010/12/16/call-with-current-continuation-demystified/</link>
		<comments>http://smellegantcode.wordpress.com/2010/12/16/call-with-current-continuation-demystified/#comments</comments>
		<pubDate>Thu, 16 Dec 2010 16:21:46 +0000</pubDate>
		<dc:creator>earwicker</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[call-with-current-continuation]]></category>

		<guid isPermaLink="false">http://smellegantcode.wordpress.com/?p=531</guid>
		<description><![CDATA[Many interpreted languages (though sadly not Javascript, yet) include a feature called call-with-current-continuation. As usually described, it&#8217;s&#8230; (deep breath)&#8230; a function A that accepts a function B that will immediately be called by the language runtime, passing it a function C that when eventually (optionally) called will cause the previous call to A to return [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=531&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Many interpreted languages (though sadly not Javascript, yet) include a feature called <code>call-with-current-continuation</code>.</p>
<p>As usually described, it&#8217;s&#8230; (deep breath)&#8230; a function <code>A</code> that accepts a function <code>B</code> that will immediately be called by the language runtime, passing it a function <code>C</code> that when eventually (optionally) called will cause the previous call to <code>A</code> to return the argument previously passed to <code>C</code> and so take us back to where we started &#8211; but only if <code>C</code> was actually called. All clear?</p>
<p>No. Nobody ever learned what it&#8217;s for by reading a description like that. It&#8217;s the kind of description <a href="http://a-kleber.narod.ru/lw/lw-tractatus-eng.pdf">you can understand only if you&#8217;ve already had the thoughts that are expressed in it.</a></p>
<p>Well, my ambition in life is to explain it in a way that any reasonably experienced Java or C# programmer can understand, so I&#8217;ll put my current best effort here. Let me know if it helps, or hinders.<br />
<span id="more-531"></span><br />
There are actually several ways to implement this feature, and any good Java programmer can invent one, once they have a description of it in Java (or OO C#) terms. In fact I suspect it&#8217;s easier to go the other way: understand a familiar practical problem in Java terms, and then see how it can be seen as an example of <code>call-with-current-continuation</code>. And then we&#8217;ll see why it&#8217;s not a great way to implement it, and eventually we&#8217;ll understand why the &#8220;call stack&#8221; concept (the basis for method calls, threads and local variables in Java and C#, as well as older machine-level languages) isn&#8217;t quite as fundamental as it may seem. And also why (thinking about C# 5.0), depending on how a runtime is implemented, it may not be necessary to have special keywords to support continuations.</p>
<p>(Although I&#8217;m talking in terms of Java, you can follow this just as well if you think of it as C#-without-delegates, which is much the same thing.)</p>
<p>Suppose you had an interface:</p>
<p><pre class="brush: java;">
public interface AsyncResultReceiver&lt;T&gt; {
  void setResult(T result);
}
</pre></p>
<p>(C# programmers will be itching to put an <code>I</code> in front of that name. Let it go!) It looks like it&#8217;s part of some asynchronous programming library, a way to push a return value back to something that is waiting for it.</p>
<p>And suppose you had another interface:</p>
<p><pre class="brush: java;">
public interface AsyncRunnable&lt;T&gt; {
  void doStuff(AsyncResultReceiver&lt;T&gt; receiver);
}
</pre></p>
<p>This represents some operation that you can start off by calling <code>doStuff</code>, and you pass it your implementation of <code>AsyncResultReceiver</code> so you can receive the result whenever it&#8217;s ready.</p>
<p>So for example you might write a class such as <code>DownloadUrl</code> that implement <code>doStuff</code> so it downloads in a background thread. When it finishes, it has a <code>String</code> of downloaded <code>content</code>, and internally it says:</p>
<p><pre class="brush: java;">
notifyComplete.setResult(content);
</pre></p>
<p>Now, suppose the bit of application code you&#8217;re writing needs to block (wait) until the operation has finished. You&#8217;d prefer to be able to say:</p>
<p><pre class="brush: java;">
String url = askUserForUrl();

byte[] html = downloadUrl(url); // much more helpful

displayHtml(html);
</pre></p>
<p>But you can&#8217;t, because of this pain-in-the-neck fancy asynchronous system. You need some kind of helper class to receive the result:</p>
<p><pre class="brush: java;">
String url = askUserForUrl();

DownloadUrl downloader = new DownloadUrl(url);
BlockingReceiver&lt;String&gt; receiver = new BlockingReceiver&lt;String&gt;();
downloader.doStuff(receiver);
byte[] html = receiver.getResult();

displayHtml(html);
</pre></p>
<p><code>BlockingReceiver</code> is a simple stock implementation of <code>AsyncResultReceiver</code> designed to solve your exact problem. I imagine, with my <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html">limited knowledge of Java concurrency primatives</a>, it would look like this:</p>
<p><pre class="brush: java;">
class BlockingReceiver&lt;T&gt; 
  implements AsyncResultReceiver&lt;T&gt; {

  CountDownLatch signal = new CountDownLatch(1);
  T result;

  public void setResult(T r) {
    result = r; // stash the result
    signal.countDown(); // wake up anyone waiting for it
  }
  
  public T getResult() {
    signal.await(); // sleep until there's a result
    return result;
  }
}
</pre></p>
<p>It seems simple enough, but we can make it even more easy to use by writing a static helper method, with a curiously familiar name:</p>
<p><pre class="brush: java;">
public T callCC(AsyncRunnable&lt;T&gt; func) {
  BlockingReceiver&lt;T&gt; receiver = new BlockingReceiver&lt;T&gt;();
  func.doStuff(receiver);
  return receiver.getResult();
}
</pre></p>
<p>That captures the standard pattern so our example call shrinks to:</p>
<p><pre class="brush: java;">
String url = askUserForUrl();

String html = callCC(new DownloadUrl(url));

displayHtml(html);
</pre></p>
<p>We could use that same <code>callCC</code> helper for any asynchronous operation, as long as it is encapsulated in a class that implements <code>AsyncRunnable</code>. It&#8217;s a general tool for bridging the mismatch that occurs when we have information being returned via a callback, and we would prefer to receive the information in a return value.</p>
<p>Let&#8217;s go back to that opaque abstract description we started with:</p>
<blockquote><p>
A function <code>A</code> that accepts a function <code>B</code> that will immediately be called by the language runtime, passing it a function <code>C</code> that when eventually (optionally) called will cause the previous call to <code>A</code> to return the argument previously passed to <code>C</code> and so take us back to where we started &#8211; but only if <code>C</code> was actually called.
</p></blockquote>
<p>We need to label some pieces of the Java example to see how it matches up. Function <code>A</code> is <code>callCC</code>. So it accepts a function <code>B</code>&#8230; wait a second, looking at our code we can see it actually accepts an object that implements <code>AsyncRunnable</code>. But that interface only has one method, <code>doStuff</code>. So that object is a &#8220;function&#8221;, in the sense that there is only one way you can interact with it: to call its single method. So logically speaking, it&#8217;s no more than a function.</p>
<p>Therefore function <code>B</code> must be that instance of our <code>DownloadUrl</code> class. According to the description, it is immediately called back and passed a function <code>C</code>. In our Java code we see:</p>
<p><pre class="brush: java;">
BlockingReceiver&lt;T&gt; receiver = new BlockingReceiver&lt;T&gt;();
asyncRunnable.doStuff(receiver);
</pre></p>
<p>Sure enough, we immediately call <code>asyncRunnable.doStuff</code>, and we pass it a fresh instance of <code>BlockingReceiver</code>&#8230; which must therefore be function <code>C</code>!</p>
<p>So we&#8217;ve successfully labeled all the pieces. One of the functions is a static method, and the other two are really objects with one method, but they&#8217;re functions too, logically speaking. Fine.</p>
<p>The description then notes that <code>C</code> can <i>optionally</i> be called. This caveat refers to the fact that whoever writes the <code>DownloadUrl</code> class has a responsibility: they have to at some point call <code>AsyncResultReceiver.setResult</code> from the background thread, or we&#8217;ll never find out what was downloaded.</p>
<p>When they do call it, passing a string hopefully containing some downloaded HTML, the <code>BlockingReceiver</code> stashes it and wakes up the original thread, which then returns the string. Or as the description has it, it will &#8220;cause the previous call to <code>A</code> return the argument previously passed to <code>C</code> and so take us back to where we started.&#8221;</p>
<p>Okay, so we can be certain that <code>callCC</code> is <code>call-with-current-continuation</code> implemented in a certain way. But it&#8217;s not quite the way it gets implemented in interpreted languages. It has a particular disadvantage.</p>
<p>I&#8217;ve drawn attention to the fact that calling <code>C</code> (a.k.a. <code>AsyncResultReceiver.setResult</code>) is optional. If it isn&#8217;t called, then <code>A</code> (<code>callCC</code>) never returns. This is certainly true in our Java implementation &#8211; what happens is that the thread that called <code>callCC</code> stays locked up forever! It&#8217;s waiting for someone to call <code>CountDownLatch.countDown</code>.</p>
<p>So we&#8217;re interpreting the word &#8220;optional&#8221; very liberally here. It&#8217;s only optional if you don&#8217;t mind your program leaking locked threads. Can anything be done to avoid this? On the other hand, what would it mean to simply avoid the problem &#8211; would that be useful?</p>
<p>What we&#8217;re saying is that we could write a sequence of statements like:</p>
<p><pre class="brush: java;">
String url = askUserForUrl();

String html = callCC(new DownloadUrl(url));

displayHtml(html);
</pre></p>
<p>&#8230; and if the download fails, we are quite happy if the <code>callCC</code> never returns (maybe the <code>DownloadUrl</code> class takes care of displaying an error?) and so the sequence of statements doesn&#8217;t continue executing. It somehow gets garbage collected away into nothing.</p>
<p>This is quite neat. It&#8217;s an alternative approach to exception handling. We don&#8217;t have to write code to say what the thread should do if there&#8217;s an error. The thread simply pops out of existence; it is absolved of all future responsibilities.</p>
<p>To achieve this, we&#8217;d need to modify how the JVM works. Right now it has threads, and every thread has a call stack containing the local variables (including parameters) for every currently incomplete method call in the thread. None of this is under the control of the garbage collector, so it can&#8217;t help clean up after us.</p>
<p>Instead, let&#8217;s make it work by allocating a garbage collectable object to represent each incomplete method call. These objects will contain the local variables and parameters as fields, and also an integer field indicating where they have reached inside the method&#8217;s bytecode. Finally, they hold a reference to another method call object, the one that called them and that they will eventually return to.</p>
<p>For example, given a Java method:</p>
<p><pre class="brush: java;">
public int foo(int x, int y) {
  System.out.writeln(&quot;Going to add some numbers&quot;);
  int z = x + y;
  System.out.writeln(&quot;Answer was: &quot; + z);
  return z;
}
</pre></p>
<p>That would need this class to store its local variables and parameter values:</p>
<p><pre class="brush: java;">
public class FooCall extends MethodCall {
  public int x, y, z;
}
</pre></p>
<p>The base class would take care of the stuff common to all method calls:</p>
<p><pre class="brush: java;">
public class MethodCall {
  public byte[] code;
  public int position;
  public MethodCall returnTo;
}
</pre></p>
<p>So the new model JVM would start by loading a class, looking for the <code>main</code> method, and allocating a suitable <code>MethodCall</code> to represent a call to it. It would put the method&#8217;s definition in the <code>code</code> field, and leave <code>returnTo</code> set to <code>null</code> and <code>position</code> at zero (pointing to the start of the method&#8217;s bytecode in the <code>code</code> array).</p>
<p>When it hits a call to another method, it sets the <code>position</code> to the right place to return to, and creates another <code>MethodCall</code> object for the called method, in which the <code>returnTo</code> field is set to point to the calling method. So at any given moment there is a chain of objects all the way back to <code>main</code>.</p>
<p>This means that the JVM itself only has to hold a reference to the top-most <code>MethodCall</code> object &#8211; the one it is executing. That alone will cause the garbage collector to keep the chain of objects alive. But it also means that if the JVM ever abandoned that top-most object, then the chain would automatically get collected by the GC. Nifty!</p>
<p>With these underpinnings, the JVM can implement <code>callCC</code> for us, in a different way, using some butt-ugly primitive operations:</p>
<p><pre class="brush: java;">
public T callCC(AsyncRunnable&lt;T&gt; asyncRunnable) {

  BlockingReceiver&lt;T&gt; receiver = new BlockingReceiver&lt;T&gt;(CALLER);
  
  asyncRunnable.doStuff(receiver);
  return null; // we never get here!
}
</pre></p>
<p>And so it must implement <code>BlockingReceiver</code> a different way as well:</p>
<p><pre class="brush: java;">
class BlockingReceiver&lt;T&gt; 
  implements AsyncResultReceiver&lt;T&gt; {

  MethodCall returnTo;
  
  public BlockingReceiver(MethodCall r) {
    returnTo = r;
  }

  public void setResult(T r) {
    GOTO(returnTo, r);
  }
}
</pre></p>
<p>Here I&#8217;m imagining that the JVM has two low-level instructions: <code>CALLER</code> is a pseudo-variable containing the <code>MethodCall</code> that called the currently executing method. <code>GOTO</code> is a pseudo-method that swaps in a different <code>MethodCall</code> to be the currently executing one (abandoning the existing one). It expects that method call to be stuck in a position where it is about to return from a method call, and so it needs to know the return value to pass back (if any).</p>
<p>So the statement <code>return "A string";</code>  really means:</p>
<p><pre class="brush: java;">
GOTO(CALLER, &quot;A string&quot;);
</pre></p>
<p>This is how <code>call-with-current-continuation</code> works in interpreted languages. In these ugly, technical terms, a &#8220;continuation&#8221; is literally just an object of a class derived from <code>MethodCall</code>, which has its <code>position</code> field pointing to the bytecode instruction that comes right after a call to a method and is expecting a return value (unless it called a <code>void</code> method, of course).</p>
<p>Sometimes people describe a continuation as a snapshot of the state of the program at some point in the past, but that is incorrect. It&#8217;s not a complete snapshot of <i>all</i> state. It&#8217;s just a reference to a <code>MethodCall</code> and hence the chain of other calls that led to its creation. But when we bring it back to life using <code>GOTO</code>, various other things might have changed; the values stored in the fields of various objects will have been modified. So the program is definitely not put back into exactly the state it was in previously.</p>
<p>This is enough for one blog post, but there are implications to deal with. Somewhere further down the line, I&#8217;ll tie this into my series of posts on exceptions (like, what the heck happens to <code>try</code>/<code>finally</code> in this alternative runtime model?)</p>
<p>In my next post I&#8217;ll address the first question that probably springs to mind: why is it customary to expose <code>callCC</code> as the primitive operation for public use, instead of exposing <code>CALLER</code> and <code>GOTO</code> directly? And if a method call can sometimes never return, is it okay for it return more than once?!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/smellegantcode.wordpress.com/531/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/smellegantcode.wordpress.com/531/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/smellegantcode.wordpress.com/531/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/smellegantcode.wordpress.com/531/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/smellegantcode.wordpress.com/531/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/smellegantcode.wordpress.com/531/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/smellegantcode.wordpress.com/531/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/smellegantcode.wordpress.com/531/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/smellegantcode.wordpress.com/531/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/smellegantcode.wordpress.com/531/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/smellegantcode.wordpress.com/531/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/smellegantcode.wordpress.com/531/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/smellegantcode.wordpress.com/531/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/smellegantcode.wordpress.com/531/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=smellegantcode.wordpress.com&amp;blog=8231797&amp;post=531&amp;subd=smellegantcode&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://smellegantcode.wordpress.com/2010/12/16/call-with-current-continuation-demystified/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/344e328f9fad1934791575a99830ef80?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">earwicker</media:title>
		</media:content>
	</item>
	</channel>
</rss>
