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

<channel>
	<title>gnuu.org &#187; continuations</title>
	<atom:link href="http://gnuu.org/tag/continuations/feed/" rel="self" type="application/rss+xml" />
	<link>http://gnuu.org</link>
	<description>my word against yours, fight.</description>
	<lastBuildDate>Fri, 16 Jul 2010 22:12:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Demystifying Continuations in Ruby (because they shouldn&#8217;t be feared)</title>
		<link>http://gnuu.org/2009/03/21/demystifying-continuations-in-ruby/</link>
		<comments>http://gnuu.org/2009/03/21/demystifying-continuations-in-ruby/#comments</comments>
		<pubDate>Sat, 21 Mar 2009 18:35:03 +0000</pubDate>
		<dc:creator>Loren Segal</dc:creator>
				<category><![CDATA[post]]></category>
		<category><![CDATA[continuations]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby 1.9]]></category>

		<guid isPermaLink="false">http://gnuu.org/2009/03/21/demystifying-continuations-in-ruby/</guid>
		<description><![CDATA[So most people won’t touch continuations with a 10 foot pole, that’s probably why in Ruby 1.9 they’ve been pseudo-deprecated (YARV performance was also an issue here, to be fair) by being pushed out to an explicit “require ‘continuation’” call. Perhaps it’s been misunderstood, but there’s a secret that nobody knows about continuations: they’re dead simple. BRAINDEAD simple.]]></description>
			<content:encoded><![CDATA[<p>So most people won’t touch continuations with a 10 foot pole, that’s probably why they&#8217;ve been <a href="http://wiki.jruby.org/wiki/Differences_between_mri_and_jruby">left out of JRuby</a> and <a href="http://www.atdot.net/~ko1/pub/ContinuationFest-ruby.pdf">pseudo-deprecated</a> in Ruby 1.9 (YARV performance was also an issue here, to be fair) by being pushed out to an explicit “<em>require ‘continuation’</em>” call. Perhaps it’s been misunderstood, but there’s a secret that nobody knows about continuations: <strong>they’re dead simple</strong>. <em>BRAINDEAD</em> simple.</p>
<p>Most blogs and articles I’ve seen that try to explain continuations get it wrong. They bore you with low level details that confuse you in the first place, or scare you by starting with the premise that “it’s complicated, but I&#8217;ll try to make you understand”. I’m not going to do either, I’m actually going to explain continuations in two words, and I want you not to laugh, cry, or vomit on yourself when you read them:</p>
<h2>GLORIFIED GOTOs</h2>
<p>Oh no, I just said a dirty word, didn&#8217;t I. You may have your own irrational fears of the goto statement, but you probably know what they are and how they work:</p>
<pre class="sh_c">#include &lt;stdio.h&gt;
int main() {
  int i = 0;
  printf("%d\n", i);
  goto some_label;
  i = 1;
  some_label:
  printf("%d\n", i);
  return 0;
}</pre>
<p>The above snippet of working C shows how we can jump to different points in a function. It prints 0 twice instead of 0 followed by 1, as you would expect. Language evolution has mostly deprecated this form of programming through method calls and, more intricately, exception handling. These new practices are really just syntactic sugar on the old goto concept. Hopefully all those who scoff at any mention of goto will one day sit down and realize that they&#8217;re a central part of how computers work, but I&#8217;m getting off topic. The point is, whether you use gotos or not, they&#8217;re extremely simple to understand. In fact, they’re exactly as simple as continuations; let’s re-write the above using those &#8220;scary&#8221; guys:</p>
<pre class="sh_ruby">def main
  i = 0
  callcc do |label| # callcc gives us ‘label’, a continuation object
    puts i
    label.call # this is our "goto" statement
    i = 1      # we skip this completely
  end          # this is where our "label" would otherwise sit
  puts i
end</pre>
<p>To those in the know, this doesn&#8217;t really show off the full-extent of callcc&#8217;s powers (that comes later), but you can look at &quot;label.call&quot; as the equivalent of &quot;goto label&quot;, and the end of the callcc block is where the label would be. That&#8217;s basically how continuations work.</p>
<p><em>If you’re having trouble parsing the above: the little trick to understanding the code is simply realizing that the block that callcc yields is <strong>executed immediately, once, and only once</strong>. It’s simply there so you can do any one-time initialization with the continuation you’re creating. The end of the block is where any subsequent calls to the yielded continuation object will go, not the block itself.</em></p>
<h3>NOW YOU KNOW.</h3>
<p>So what, is it really that simple? Continuations are another way to write gotos? The answer is: pretty much. There are actually only two functional difference that makes them even more powerful than the above C-style gotos, but one that makes them a little less-so.</p>
<h4>More Powerful, How?</h4>
<p><span style="font-size: 140%">1.</span> <strong>They’re not local to your method</strong>. Simply put, we can’t do the following in C:</p>
<pre class="sh_c">// a() is called by main()
void a() {
  printf("hello world\n");
  label1:
  printf("then you say...\n");
  b();
}
void b() {
  printf("then I say...\n");
  goto label1;
}</pre>
<p>This should print &quot;hello world&quot; followed by &quot;then you say&quot;, &quot;then I say&quot;, in a never-ending loop. Problem is, it won&#8217;t compile. Without getting into the nitty-gritty of why C can’t do this, I’ll just simply show how we can actually get away with it using continuations:</p>
<pre class="sh_ruby">def a
  puts "hello world"
  callcc {|cc| $label1 = cc } # pretend this says "label1:"
  puts "then you say..."
  b
end

def b
  puts "then I say"
  $label1.call # pretend this says "goto label1"
end</pre>
<p>As the comments indicate, this is almost a one-to-one translation of the C code above. Our continuation object is set to a global variable, essentially making it a “<em>global label</em>” that can be goto’d by running the method #call (picture it as “label.goto” instead of #call).</p>
<p><span style="font-size: 140%">2.</span> <strong>They maintain stack-frame state</strong>. That’s the reason why labels in C are local to a function, because you can’t just jump between functions without switching stack frames. Actually, there are tricks in C to do just that (namely <tt>longjmp</tt> and <tt>setjmp</tt> to jump to arbitrary addresses and continue execution which is actually how continuations are done in C), but we’re focusing on Ruby here, right? Basically, the continuation object yielded from callcc (the {|cc| thing}) contains a snapshot of our stack frame at the point it was yielded at (remember, the block is only yielded that first time). This allows us to jump between methods in a class, between classes, and jump back from a nested call when we are arbitrarily deep in a stack frame. </p>
<h4>Anyone Up For A Quick Real World Example?</h4>
<p>The last situation is the one with some real world usage. Imagine we’re writing a web framework with a Rails-style before_filter and we want the ability to halt the execution during a filter and jump all the way back up to the router code to find the next matching route. <a href="http://www.sinatrarb.com">Sinatra</a> (sort-of) does this with the `pass` method, and though it probably doesn’t use continuations to achieve the result, the concept here is a perfect example of wanting to jump back through our stack frames arbitrarily. We could be 3 method calls deep, or we could be 20 method calls deep, but we need to “go to” a specific point in our program execution. Usually, people implement this with try/catch style exception handling (RouteAbortError maybe), but continuations may be a little cleaner depending on the scenario (we might have a method handling the exception 3 method calls up, but we want to jump 7 method calls up to the initial point in code).</p>
<h4>Less Powerful, How?</h4>
<p>There’s one thing you may have noticed from the initial example, it’s that jumping forward looks different from the example where we jumped backwards. The limitation is that continuations can’t actually jump <em>forwards</em>, at least not between method calls. The reason is that in C, labels are compiled into the program statically, but in Ruby, the continuation objects are created at runtime. This means that we’d need to execute that callcc call in our future method to generate the continuation, but we can’t run code that hasn’t yet been run. In short, continuations are great for jumping back in time, not quite so for jumping forwards.</p>
<h3>Final Correction</h3>
<p>So I initially called continuations “glorified gotos”. Hopefully this got you to understand the simple concept behind their use; but now I should fess up and modify the definition just a little bit to be slightly more accurate. Instead of glorified gotos, think of continuations as:</p>
<h2>GLORIFIED, <u>STATEFUL, BACKWARDS JUMPING,</u> GOTOs</h2>
<p>Now that you know what the fuss is about, you can decide to hate continuations all you want.</p>]]></content:encoded>
			<wfw:commentRss>http://gnuu.org/2009/03/21/demystifying-continuations-in-ruby/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Seaside Statefulness: Call-and-Answer</title>
		<link>http://gnuu.org/2009/01/26/seaside-statefulness-call-and-answer/</link>
		<comments>http://gnuu.org/2009/01/26/seaside-statefulness-call-and-answer/#comments</comments>
		<pubDate>Mon, 26 Jan 2009 08:00:44 +0000</pubDate>
		<dc:creator>Loren Segal</dc:creator>
				<category><![CDATA[post]]></category>
		<category><![CDATA[avi bryant]]></category>
		<category><![CDATA[continuations]]></category>
		<category><![CDATA[cusec]]></category>
		<category><![CDATA[seaside]]></category>
		<category><![CDATA[smalltalk]]></category>
		<category><![CDATA[stateless http]]></category>

		<guid isPermaLink="false">http://gnuu.org/2009/01/26/seaside-statefulness-call-and-answer/</guid>
		<description><![CDATA[So Avi Bryant spoke at CUSEC this last week and I was fortunate enough to sit in on a Seaside tutorial that he gave to a couple of people. It got me really interested in this Smalltalk web framework stuff. Smalltalk is of course nothing new except for the fact that it was the first [...]]]></description>
			<content:encoded><![CDATA[<p><img alt="Seaside - The framework for developing sophisticated web applications in Smalltalk" align="right" src="http://seaside.st/styles/logo-plain.png" width="194" height="104" /></p>
<p>So <a href="http://www.avibryant.com/">Avi Bryant</a> spoke at <a href="http://2009.cusec.net/">CUSEC</a> this last week and I was fortunate enough to sit in on a <a href="http://www.seaside.st">Seaside</a> tutorial that he gave to a couple of people. It got me really interested in this Smalltalk web framework stuff. Smalltalk is of course nothing new except for the fact that it was the first language to have some of the awesome code features we use today, but that&#8217;s all in the past, so let&#8217;s move on. </p>
<p>The interesting part is that playing with Seaside is completely unlike learning Smalltalk (unless you&#8217;ve never seen a language with lambdas). It&#8217;s a complete mind-blowing experience on its own level; a revolutionary way to look at web application development, <strong>not</strong> <em>&quot;let&#8217;s do what Ruby on Rails does.. in Smalltalk!&quot;</em>. The revolution is in the idea that the statelessness of HTTP need not be transitive. It&#8217;s the idea that you shouldn&#8217;t have to reconstruct bits and pieces of many web requests and figure out what your user just did. In short, it brings back the workflow based semantics that make desktop app development so much more intuitive by comparison. In shorter: <em>it&#8217;s the future</em>. Smalltalk might not be, but these concepts definitely are.</p>
<h3>State: Big Deal? </h3>
<p>There&#8217;s something <em>really</em> sexy about being able to do the following:</p>
<p> <small style="padding-bottom: 0px; display: block; font-family: monospace; margin-bottom: 0px">AuthRegisterTask&gt;&gt;#go</small>
<pre class="sh_smalltalk" line="1">go

  | user |
  user := self call: AuthRegisterComponent new.
  user username ~= ''
    ifTrue:  [ self inform: ('Good Job ', user username)  ]
    ifFalse: [ self inform: 'You did not register' ]
</pre>
<p>The code above starts from class <tt>AuthRegisterTask</tt>, throws you off to a register screen (<tt>AuthRegisterComponent</tt>) and then returns a new <tt>AuthUser</tt> object back to the task. The task then validates and sends you off to another <tt>inform:</tt> page (helper page with some text and a simple &quot;Ok&quot; button that brings you back to the previous page when clicked) with the success/failure results. A total of <big><strong><u>4</u></strong></big> web requests are happening here from start to finish, but by looking at the code (assuming haven&#8217;t seen Seaside before) you would never know it. In fact, it looks like you just created an <tt>AuthRegisterComponent</tt> object and verified the results&#8212; the implementation details of how those results are retrieved are properly hidden from you. They&#8217;re hidden because they&#8217;re ugly.</p>
<p><tt>AuthRegisterComponent</tt> is implemented as:</p>
<p><small style="padding-bottom: 0px; display: block; font-family: monospace; margin-bottom: 0px">AuthRegisterComponent&gt;&gt;#renderContentOn:</small> </p>
<pre class="sh_smalltalk" line="1">renderContentOn: html

  | user |
  user := AuthUser new.
  html form: [
    html paragraph with: [
      html span with: 'Username'.
      html textInput on: #username of: user.
      ].
    html paragraph with: [
      html span with: 'Password'.
      html textInput on: #password of: user.
      ].
    html submitButton callback: [ self answer: user ].
    ].
</pre>
<p>The magic here is in the <tt>call:</tt> and <tt>answer:</tt> methods. This is where Seaside communicates (continuation style) between requests by saving and restoring state like a conventional application would.</p>
<h3>Seaside: Pages are not Islands</h3>
<p>Of course the example I used wasn&#8217;t perfect, but it&#8217;s the shortest illustration I can come up with right now. A much more appropriate (and much longer) example would be a 3+ page wizard style registration where the user might follow one of many possible flow graphs to complete the form. Seaside would handle this with ease because it does not treat <em>pages as islands</em>. In fact, such a wizard would be as easy as implementing one in Swing, or using some Neatbeans auto-wizardifier because the logic and implementation would be equivalent. This is not the case when dealing with the web. You usually have to hack your session and throw tons of state in there to emulate what continuations do in a very clean fashion.</p>
<h3>AJAX WAT? AJAX Where Art Thou.</h3>
<p>In researching the necessity for such behaviour, I came across <a href="http://lists.squeakfoundation.org/pipermail/seaside/2007-December/015571.html">an interesting post</a> from Avi himself (dating to 2007) where he states that AJAX trumps <em>most </em>(not all) of the benefits of continuations. It is indeed true that AJAX does emulate the concept of statefulness in some sense, but I&#8217;d say AJAX is not nearly as elegant as the above code. Using JavaScript to make requests for tiny tidbits of data, or using JavaScript as glue to throw back to the browser, is almost the opposite of elegant. AJAX surely has it&#8217;s place, but I&#8217;d rather see more of the above than more crappy &amp;&amp; broken JS.</p>
<h3>Continuations FTW?</h3>
<p>Moral of the story: you should learn continuations because they will blow your mind.</p>]]></content:encoded>
			<wfw:commentRss>http://gnuu.org/2009/01/26/seaside-statefulness-call-and-answer/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
