It’s just data

Continuations for Curmudgeons

This essay is for people who, in web years, are older than dirt.  More specifically, if there was a period of time in which you programmed in a language which did not have garbage collection, then I mean you.  For most people these days, that means that you had some experience with a language named C.

It is a pretty safe bet that — despite your deep technical background — you find that you have some genetic defect that makes it completely impossible for you to understand articles with titles like Continuations Made Simple and Illustrated.  And for some reason, that bothers you.

If so, then maybe this article is for you.  Think of yourself as a frog.  Prepare to be boiled.

Local Variables

Let me start with something far, far, away from continuations.  Something that you should be comfortable with.  It should bring back memories of battles you heroically fought, and mostly won, long ago.  This example is in C:

#include <stdio.h>

int* f(int n) {
  int result = n + 1;
  return &result;
}
 
main() {
  int *n1 = f(1);
  int *n2 = f(2);
 
  printf("%d\n", *n1);
}

OK, now let’s walk through this program.  First a function named f is defined.  It takes in one argument, an integer named n.  It adds one to that value, and stores the result in a local variable named result.  Finally, f returns the address of result.

At this point, any self respecting compiler should issue a warning.  In fact, gcc does exactly that:

test.c: In function 'f':
test.c:5: warning: function returns address of local variable

The problem is that local variables are stored on the stack.  And when f returns, it pops the stack, making this memory available for other uses.

In this program, main calls f twice.  Once with a value of 1 and once with a value of 2.  Quite likely, the second call will use the exact same storage layout as the first call, meaning that the first result will be overlaid.

In fact, on my machine, this is exactly what happens.  When I compile and run this example, I get the following result:

3

If you now look around, you will notice that all the tadpoles that never really programmed in C have jumped out of the pond.

ByValue vs ByReference

The above example could be fixed by using malloc.  Of course, this would introduce a leak, so calls to free would also have to be added.  Aren’t you glad that you are now programming in a language with garbage collection?

Even so, there still are quirks that will snare the unsuspecting programmer.  For this pair of examples, I will use JavaScript.  If you like, you can run these in your favorite web browser.

<script>
  var v = 5;
 
  function f() {
    v = v + 1;
    return v;
  }
 
  var x = f();
  x = x - 2;
  document.write(f());
</script>

In this script, v starts out at 5.  Function f is called, and v gets incremented, and the result gets returned and stored in a variable named x.  That variable is then decremented by two.  Then f is called again, v get incremented again, and the result is printed.

When I run this I get

7

Now, lets change this example slightly.

<script>
  var v = [5];
 
  function f() {
    v[0] = v[0] + 1;
    return v;
  }
 
  var x = f();
  x[0] = x[0] - 2;
  document.write(f()[0]);
</script>

The only difference between this script and the first script is that v is an array of length one.  However, this difference is significant, because arrays are allocated on the heap, so v is really just a reference to the array.  And after the first call, x is a reference to the same array, so when the value at index 0 is decremented by two, this affects the value referenced by v.

Sure enough, when I run the new script, I get

5

Inconsistent?  Yes.  Strange?  Yes.  But generally, this doesn’t cause too much problems.  In any case, you avoid SEGVs as things allocated on the heap never go out of scope.  They simply become eligible to be reclaimed when there is nothing left which references them.

If you are still with me, you don’t realize it yet, but you are about to become dinner.

Frames

Let’s recap.

While a stack can be seen as a consecutive sequence of bytes, in most languages there are either conventions (which are not enforced) or policies (which are) which prevent a function from “popping” off more data than they pushed onto the stack.  In other words, each active scope (e.g., a function) is separated from one another much in the same way as the little bars that you put in between groceries on the conveyor belt in line separate each person’s purchases.

A procedure call pushes the return address (the address of the instruction after the call instruction) onto the stack, along with any arguments, and creates a new frame.  A return statement uses this information to set the Instruction Pointer and Stack Pointer back to what it was as the point of call.

Within the procedure, arguments and local variables may be located based on their offset from the start of the stack segment.

Hashes

Everything so far has been very traditional computer science.  Now, let’s start to diverge from that a bit.  Instead of viewing a stack as a contiguous sequence of bytes, let’s view a stack as a linked list of frames.  And instead of viewing a frame as a contiguous sequence of bytes, let’s substitute a dictionary or hashtable.

Now instead of knowing that this data resides at a predetermined offset in the frame, you would look up x simply by looking up “x” in the frame’s hash table.

In case you didn’t notice, this organization of frames is more oriented towards dynamic languages.

callcc

Now, let’s revisit the notion of a procedure call with this organization of frames.  A procedure call creates a new frame, and stores the current context (consisting of both the instruction pointer and the stack pointer) in the new frame.  The syntax for creating a new frame and storing the current context into a global variable named $cc in Ruby is:

callcc{|$cc|}

The syntax for returning to this exact point, restoring both the instruction pointer and stack pointer, is:

$cc.call

This is naturally called a continuation, as you are continuing where you left off.

At this point, you are probably feeling a little bit disoriented.  But go back and reread the above few paragraphs and examples.  Other than the last examples being in a foreign language, all the words make sense.  You are probably wondering “is that all there is?” and “what’s the big deal?”.  If so, the answers are “pretty much yes”, and “read on”.

One thing to note here is that as long as $cc retains its current value, the stack frame it refers to can not be reclaimed by garbage collection.  Frames themselves are not automatically freed upon encountering return statements; instead they are subject to garbage collection.  Simply by “continuing” at a prior point in the execution, and creating a new continuation, call “stacks” become arbitrary trees.

Generators

At this point, discussions generally veer off into either contrived or complicated examples.  Let’s instead take a simple example where the machinery for continuations is not quite so raw and exposed: Python generators.  Here is an example that prints Fibonacci numbers less than 1000:

def fib():
  yield 0
  i,j = 0,1
  while True:
    yield j
    i,j = j,i+j
 
for n in fib():
  if n>1000: break
  print n

Instead of return statements, the fib function uses yield statements.  This yields one number at a time out of the inexhaustible supply of Fibonacci numbers.  The caller simply invokes that continuation as many times as desired, and all program state (instruction pointer, local variables) are restored, and the fib function starts back up where it left off.

Once the loop is exited, the state if the fib function is eligible for reclaiming.

Cool, eh?

If you try to recode this without continuations, you will find that you will need to return a “token” which contains all the relevant state, and that token will need to be passed back in on subsequent calls.  That’s pretty much what is happening under the covers.  (Note: you may be tempted to use global variables instead.  Don’t.  Your code would no longer be reentrant, and if there were two callers, they would get confused).

Cocoon

Now let’s look at a web application, this time in JavaScript.  A single function implements the entire form based application that involves the display of three (or four, depending on the options selected) web pages.  This is accomplished via the cocoon.sendPageAndWait primitive.

This style of programming is quite different than the resource oriented approach advocated by RESTSome, however, find it to be more intuitive.

This hearkens back to the days in Basic when you coded things like

10 print "Enter your name"
20 input a$
30 print "Hello, "; a$; "!"

When the computer got to the input statement, the operating system would suspend your program until the user provided an input.  At which point, your program would be paged back into memory and would pick up exactly where it left off.

SAX

A SAX parser is an example of a task that could be recast as a generator.  It consumes an InputSource byte by byte and occasionally emits startElement, endElement, characters and other events.  After each event, the parser picks back up where it left off.

While this organization is convenient for parser writers, many consumers find XML Pull Parsers easier to deal with.

Judicious application of continuations allows both constituencies to be satisfied.  From the user of the library’s perspective, they are using a pull parser.  From the person who codes up the SAX handler, each event simply invokes a continuation.  There is no memory bloat like you see with DOM style parsers.  Everybody is happy. 

UI

Event programming, in general, is for wizards.  These wizards live and breathe events.  But even they regress every once and a while.  You can tell when this happens when you see a modal dialog box.

With User Interface Continuations, even scripters can become £337 h4x0r UI gods.  Without a modal dialog box in sight.

Closures

Consider the following JavaScript:

var msg = "Hello, world!";
setTimeout(function(){alert(msg)}, 1000);

The use of setTimeout is common in JavaScript based animation.  The first parameter is a function to be invoked.  The second parameter is the number of miliseconds to wait until this string is executed.

The question you should be asking yourself is “in which context is this function to be evaluated?”  In particular, how does JavaScript go about looking for the value of msg?

The answer is simple: in the current context.  This, it turns out, is a closure, continuation’s more general cousin.  Wrapped up in a nice neat little package.

Continuations are bookmarks — they tell you where to pick up after you last left off. Closures are simply the current lexical stack — they represent the current local context and its immediate parent, recursively.

Classes

If the notion of a nested set of scopes residing on the heap seems foreign to you, it really shouldn’t. Here’s an example in Java:

public class Scopes {

  class Outer {
    class Inner {
       void alert() {System.out.println(msg);}
    }
    String msg = "Schweet!";
    Inner inner = new Inner();
  }

  Outer outer = new Outer();

  public static void main(String[] args) {
    String msg = "Bogus!";
     (new Scopes()).outer.inner.alert();
  } 
}

Epilogue

One thing that people don’t often tell you about continuations is that they don’t actually resume exactly where you left off.  After all, if they did, you would end up in an infinite loop.  The only thing that is really restored is a few pointers.  Everything that resides on the heap, or is stored externally in places like files and databases, remains unaffected when you invoke a continuation.  But like the ByValue or ByReference discussion above, this doesn’t cause problems very often.  In fact, it generally works out pretty much the way you would like it to, without you having to worry about it.

When you realize this, you realize that there really is no magic in continuations.  Sure, more things are put on the heap, but there are ways to optimize this.

Oh, and by the way, you probably taste like chicken right about now.


Sam Ruby: Continuations for Curmudgeons

[link]...

Excerpt from del.icio.us/tag/python at

Actually in JavaScript setTimeout executes the code in the context of window. If you want to execute the code in the context you created it in, you need to use a closure:

  setTimeout(function(){alert(msg)}, 1000);

Posted by Mark Wubben at

Mark: fixed.  Thanks!

Posted by Sam Ruby at

Sam Ruby with a great explanation of continuations for those who easily understand “while (*p++ = *q++);” but keep wondering what this strange MIT CS speak might be about....... [more]

Trackback from Stefan Tilkov's Random Stuff

at

Confused by Continuations?

Sam Ruby gives a nice summary of them - especially useful for people who aren’t that familiar with Smalltalk or Ruby....

Excerpt from Smalltalk Tidbits, Industry Rants at

“At this point, discussions generally veer off into either contrived or complicated examples.”

In fairness to conventional discussions, they are usually following a discussion of closures. The following illustrates that closures are sufficient, and that Python’s generators are extremely elegant. My Javascript code is much uglier.

js> makeFib = function(){

        var i=0;
        var j=1;

        fib = function(){

                var k = i;
                i = j;
                j = k + j;
                return k;

        }

        return fib;

}

js> printFib = function(fib1, fib2){
        var i = fib1();
        var j = fib2();
        while( i < 1000){
                //works on rhino and xpcshell
                print("fib1: " + i + " fib2: " + j);
                i = fib1();
                j = fib2();
        }
}

js> printFib(makeFib(),makeFib())
fib1: 0 fib2: 0
fib1: 1 fib2: 1
fib1: 1 fib2: 1
fib1: 2 fib2: 2
fib1: 3 fib2: 3
fib1: 5 fib2: 5
fib1: 8 fib2: 8
fib1: 13 fib2: 13
fib1: 21 fib2: 21
fib1: 34 fib2: 34
fib1: 55 fib2: 55
fib1: 89 fib2: 89
fib1: 144 fib2: 144
fib1: 233 fib2: 233
fib1: 377 fib2: 377
fib1: 610 fib2: 610
fib1: 987 fib2: 987
js>


Posted by Robert Sayre at

Getting smarter

Sam Ruby has an essay on continuations that will make you smarter. This essay is complement to the other essay on continuations that I linked to awhile back. When I read essays like these, I wish I had gutted it out and majored in computer science....

Excerpt from rc3.org Daily at

Sam Ruby: Continuations for Curmudgeons

[link]...

Excerpt from del.icio.us/tag/continuations at

[Python] Continuations for Curmudgeons

Sam “Intertwingly” Ruby starts off his article with this: This essay is for people who, in web years, are older than dirt.  More specifically, if there was a period of time in which you programmed in a language which did not have garbage...

Excerpt from The Farm: The Tucows Developers' Hangout at

Incidentally, I tried a similarly mechanical approach to explaining continuations a while ago, but more focused on the interpreter:
[link]

Posted by Ian Bicking at

Are continuations unRESTful?

I was reading through Sam Ruby’s excellent continuations lesson, and I noticed that he asserted continuations were “quite different” than...... [more]

Trackback from franklinmint.fm

at

This still doesn’t beat that one famous sentence of sigmund freud ;)

Posted by Bas Westerbaan at

Thanks for writing this - it helps a lot.  Unless I’m mistaken, C coders (or at least, POSIX ones) have had continuations all along, in the form of setjmp() and longjmp().

Posted by Dave Duchene at

You are mistaken — setjmp/longjmp don’t implement general continuation functionality.

Posted by Dan at

More Continuations

Sam Ruby: Continuations for Curmudgeons is a great article that discribes how continuations are implemented. It makes it a bit easier for me to understand how continuations are used. Interesting, generators (iter methods in Magik) are implemented...

Excerpt from Peter Williams' Weblog at

Continuations

The inimitable Sam Ruby pens another masterpiece. Sam has a gift for distilling really nerdy stuff into Evian-clear prose. When I grow up, I want to be this guy....... [more]

Trackback from XML-BLOG

at

Sam Ruby is one smart cookie.
I’ve been reading his blog for a while now for this insights into REST

Anyway he has an excellent article on Continuations...

Posted by Alex James at

Sam Ruby: Continuations for Curmudgeons

Sam Ruby: Continuations for Curmudgeons....

Excerpt from Keith's Weblog at

links for 2005-04-13

Sam Ruby: Continuations for Curmudgeons (tags: continuations computerscience)...... [more]

Trackback from .:: a few thoughts on the subject by rob wright ::.

at

var msg = "Hello, world!";
setTimeout(function(){alert(msg)}, 1000);

This, I believe, is a closure, not a continuation.  A continuation is a closure, but not vice versa.  Can you please clarify why you say that this example represents a continuation?

Posted by Philip Jacob at

Simon Willison : Continuations for Curmudgeons - They aren’t as scary as you may have been lead to believe....

Excerpt from HotLinks - Level 1 at

Sam Ruby: Continuations for Curmudgeons

Sam Ruby: Continuations for Curmudgeons: "This essay is for people who, in web years, are older than dirt. More specifically, if there was a period of time in which you programmed in a language which did not have garbage collection, then I...

Excerpt from Adnans Sysadmin/Dev Blog at

@Robert Sayre: In the JavaScript code you posted, you should make fib a local variable of makeFib (precede it with a var statement), or even return an anonymous function. Otherwise, fib would be globally available in the code. Here’s a reproduction of Sam’s Python code in JavaScript, using closures:

fib = function(max, f) {
    var k, i = 0, j = 1;
    while(true) {
        k = i, i = j, j = k + j;
        if(k > max) break; else f(k);
    }
}
fib(1000, function(n) {
    print n;
});


Posted by Jonas Galvez at

Continuations explained

Sam Ruby writes about Continuations. I stumbled over the name once but never cared to read more as it seemed somewhat obscure to me. Sam starts his article with this: This essay is for people who, in web years, are older than dirt. More...

Excerpt from Martins Notepad at

Jonas, sloppy declaration on my part. Your code isn’t really cricket though, as you can’t call it as many times as you want from the caller. btw, it doesn’t close over anything interesting. It’s just local variables and first-class functions.

Posted by Robert Sayre at

And instead of viewing a frame as a contiguous sequence of bytes, let’s substitute a dictionary or hashtable. […] first attempting to locate the name in the dictionary at the top of the stack, and then proceeding down the stack until it is located.

This confuses me. Do you mean that you look variables up by name, going through function frames as you go up the list? In other words, all variable names are global, but a function can overlay/shadow a previously defined variable by declaring one with the same name? Just like Perl’s local function does? If so, isn’t this completely irrelevant to the point? I think it only matters that the call frames are allocated on the heap and kept around, no?

Posted by Aristotle Pagaltzis at

If, after all this talking about what is and what is not a continuation, you’re feeling slightly confused, go over to Sam Ruby’s site ad read Continuations for Curmudgeons, where Sam, in his inimitable style, provides a very nice explanation.And in cas...... [more]

Trackback from Agylen

at

Continuations, slightly updated

Frankly, I’m surprised how much interest  Continuations for Curmudgeons generated.  I guess that there was a demand for an explanation from the perspective of a C programmer, eh? Based on  two  bugs reported in  one section, I’ve updated it... [more]

Trackback from Sam Ruby

at

Sam Ruby: Continuations for Curmudgeons: "This essay is for people who, in web years, are older than dirt.  More specifically, if there was a period of time in which you programmed in a language which did not have garbage collection, then I mean...

Excerpt from duncan.smeed.org | Duncan's Jotter at

Dave: another way to express what Dan said is that while those things that can be done with setjmp and longjmp can also be done with continuations, this represents but a small fraction of what continuations can do.

Aristotle: yes, in most languages I am familiar with, scopes nest and inner declarations can hide outer declarations.  Understanding how call frames relate was crucial to the process of my coming to understand what continuation are.  Since you mention Perl, here’s an example that illustrates how defining a sub in that language captures the scope and how scopes can cause variables to shadow one another:

{
  my $msg = "x";
  my $f;
  {
    my $msg = "y";
    sub g() {
      print $msg;
    }
    $f = *g;
  }
  &$f();
}
Posted by Sam Ruby at

Continuations explained to C programmers

Sam Ruby writes an awesome essay on continuations, taking you progressively from the close-to-the-metal execution stack in C to dynamic... [more]

Trackback from Sylvain Wallez

at

Thanks for responding, Dan.  If setjmp() and longjmp() don’t implement continuations, what is missing to make it so?  If I read things correctly, a continuation is basically just a snapshot of the stack (or stack-equivelent), which can be restored at will.  Isn’t that what set/longjmp() do?

Posted by Dave Duchene at

Sam Ruby: Continuations for Curmudgeons: "This essay is for people who, in web years, are older than dirt.  More specifically, if there was a period of time in which you programmed in a language which did not have garbage collection, then I mean...

Excerpt from Duncan's Jotter at

Dan from “Squawks of the Parrot” has a great explanation of continuations, that also explain closures and how they relate: [link]

I wrote myself a summary:

*

Posted by Julien Couvreur at

Sam, I know about closures in Perl, and I use them extensively, but they are beside the point. Searching up through the list of call frames has nothing to do with continuations. A continuation has to close over the spatial scope; searching up the call frame list addresses temporal scope.

in most languages I am familiar with, scopes nest and inner declarations can hide outer declarations.

Please ponder the following two pieces of code:

*

{
    my $foo = "hello";
    print "outer scope: $foo\n";
    {
        print "inner scope, pre-declaration: $foo\n";
        my $foo = "world";
        print "inner scope, post-declaration: $foo\n";
    }
}

*

sub bar {
    print "bar: before local: $foo\n";
    local $foo = "hello";
    print "bar: after local: $foo\n";
    baz();
    print "bar: after call: $foo\n";
}

sub baz {
    print "baz: before local: $foo\n";
    local $foo = "world";
    print "baz: after local: $foo\n";
}

In the first one, a declaration in an inner hides the corresponding one from an outer scope. There is no call frame involved.

In the second one, a declaration in a scope where execution has moved into is hiding a declaration from a scope which execution was previously moving through. There is no nesting of lexical scopes involved. (The Perl world uses the term “dynamic scoping”, as opposed to “lexical scoping”, to talk about this concept.)

Only for the second case do you need to search up the list of call frames as opposed to the list of scopes, something you need to do in the first case.

Posted by Aristotle Pagaltzis at

Dirt, be thou proud!

Even for us dirt farmers who understand and appreciate continuations, Sam’s writeup is still amusing.... [more]

Trackback from Jim's Ramblings

at

Julien: When I originally read what Dan had written, it seemed much better than other explanations I had seen, but it was still too theoretical and abstract for me.  It wasn’t until I saw how it was implemented in Parrot that I finally started to grasp the concept.

Aristotle: Got it.  Paragraph removed.  It was incorrect, and didn’t add anything anyway.  Thanks!

Posted by Sam Ruby at

Very nice article.
However, it’s Fibonacci, not Fibonnaci

Francesco

Posted by Francesco Bellomi at

Francesco: fixed.  Thanks!

Posted by Sam Ruby at

In Order of Importance?

The inimitable David Heinemeier Hansson points out that in a recent set of slides by Sam Ruby, Rails is the fourth item from the top on a list of things Worth Watching. What’s item number three? Continuations. Sam also brings us Continuations for...

Excerpt from HREF Considered Harmful at

Sam Ruby: Continuations for Curmudgeons

Sam Ruby: Continuations for Curmudgeons .. make you smarterintertwingly.net/blog/2005/04/13/Continuations-for-Curmudgeonstrack this site | 3 links...

Excerpt from blogdex - the weblog diffusion index at

Continuations Article for Web MVC

See Use continuations to develop complex Web applications... [more]

Trackback from Confluence: Research and Development

at

Sam Ruby: Continuations for Curmudgeons

Sam Ruby has the best article I’ve read yet on Continuations. Although I, of course, am a curmudgeon C programmer. Stephen O’grady on mono: “developers I track are using it, and using it a lot.” The developers I track are using Ruby. And the more I...

Excerpt from christopher baus.net at

In RIFE (similarly to Cocoon) we have adopted a continuations style that doesn’t mandate their use throughout the whole web engine (which is what Seaside does iirc). There are a number of situations where continuations make your life easier, however there are even more situations where they don’t feel natural in a web application. The solution continuations solve best is one where you have a multi-step ‘island of functionality’ that does one particular thing on its own and that shouldn’t be committed to the backend before the final step is finished. These are typically a wizard, a game, a multi-page admin intervention, a survey, ...

You can find a presentation about RIFE continuations at java.net. For more information, feel free to browse some sources or read our wiki pages about it.

Posted by Geert Bevin at

call/cc has been around a while in scheme. Did not find any mentioning of that fact.

Posted by Burkhard Neppert at

Burkhard: my goal wasn’t to present a comprehensive history of continuations.  My goal was to prevent the little froggies from jumping out of the pond.

Posted by Sam Ruby at

Sam Ruby does a great job of explaining continuations in his Continuations for Curmudgeons piece. I also discovered through Sam an article on using conitnuations in user interfaces....... [more]

Trackback from Phil Windley's Technometria

at

Here is a Java implementation of continuation based on a Thread to keep the current state...

Note that right now, the continuation thread is never killed (it is set to be a deamon thread so when the main thread dies, the program finish properly).

public class ContinuationTest {
	public static abstract class Continuation {
		private Object result;
		Thread continuationThread= new Thread(new Runnable() {
			public void run() {
				execute();
			}
		});
		
		public abstract Object execute();

		public Continuation() {
			continuationThread.setDaemon(true);
		}
		public synchronized Object doit() {
			if (!continuationThread.isAlive()) {
				continuationThread.start();
			}
			notify();
			try {
				wait();
			} catch (InterruptedException e) {
			}
			return result;
		}
		public synchronized void yield(Object o) {
			try {
				result= o;
				notify();
				wait();
			} catch (InterruptedException e) {
			}
		}
		public void yield() {
			try {
				result= null;
				notify();
				wait();
			} catch (InterruptedException e) {
			}
		}
		
	}
	
	private static Continuation fib= new Continuation() {
		private int i, j;
		public Object execute() {
			yield(new Integer(0));
			i= 0;
			j= 1;
			while (true) {
				yield(new Integer(j));
				i= j; j= i+j;
			}
		}
		
	};
	
	public static void main(String[] args) {
		Integer result= null;
		do {
			result= (Integer) fib.doit();
			System.out.println(result);
		} while (result.intValue() < 1000);
	}
}


Posted by Emmanuel Pirsch at

Sorry, I messed up the fib function.

Use this one instead :

private static Continuation fib= new Continuation() {
		private int i, j;
		public Object execute() {
			yield(new Integer(0));
			i= 0;
			j= 1;
			while (true) {
				yield(new Integer(j));
				int k= i;
				i= j; 
				j= k+j;
			}
		}
		
	};


Posted by Emmanuel Pirsch at

Sam Ruby: Continuations for Curmudgeons

This essay is for people who, in web years, are older than dirt. More specifically, if there was a period of time in which you programmed in a language which did not have garbage collection, then I mean you. For most people these days, that means...

Excerpt from Lambda the Ultimate - Programming Languages Weblog at

Closures & Continuations

For some reason, closures and continuations are a topic that I regularly look into, and every time think I got it. Yet every time I dig into it again, I realize my understanding is still somewhat superficial and discover more. Sam Ruby just wrote an intro article to continuations. I found it a bit too hand-wavy to be really satisfying, but it made me want to completely get it this time ;-) I’ve been re-reading my bookmarks and new pages on the topic, especially in the context of Scheme and Javascript. Today’s post will stay rather general, summarizing what closures...... [more]

Trackback from Curiosity is bliss

at

Tax filing and Java

JCP News from Brazil . . . also Poll: Breaking the last dependency Weblogs: Brazil, Clustering’s new alternative and JSF and JSP public review Also in Java Today: Continuations for Curmudgeons and duplication in customer and programmer tests...

Excerpt from Editor's Daily Blog at

Links for 2005-04-14 [del.icio.us]

Sam Ruby: Continuations for Curmudgeons sweet — a great intro to continuations. I can’t wait for perl6 ;) Freedom to Tinker: Why Use Remotely-Readable Passports? Government spokesman: ‘because contact-based chips are too non-standard’. what an...

Excerpt from Happy Software Prole at

Thanks for writing such a clear explanation!  However, it seems to me that whenever you explain continuations, you should also warn people not to actually use them.  There are good reasons why Guido van Rossum added generators to Python but not raw continuations.

What’s essentially going on here is that stack frames are being repurposed as long-lived data structures.  A data structure represented as an ordinary class tends to be less confusing than an implicit data structure in all but the simplest cases.  Even Java’s inner classes are somewhat of a mixed blessing because of the difficulty of explaining them to newbies, so they’re good mostly for one-line anonymous methods.

Posted by Brian Slesinsky at

Closures & Continuations

For some reason, closures and continuations are a topic that I regularly look into, and every time think I got it. Yet every time I dig into it again, I realize my understanding is still somewhat superficial and discover more. Sam Ruby just wrote an...

Excerpt from Curiosity is bliss at

Not just for CS students

Programmatic techniques that have until recently been the preserve of the CS students and the scripting elite are slowly trickling down to mainstream languages. Java proved you could have a common, not-entirely-nauseating general purpose language...

Excerpt from Archgrove - Implicit Definition at

... [more]

Trackback from David's blog

at

Continuations are older than dirt. Stack Recursion(aka Continuations) is not new and shiny. Go back to how Prolog’s backtracking inference engine works. It’s also standard technique for Digital Signal Processing(DSP) calculations of FIR digital filters. And so on and so on ...

I wish this whole group of “Emerging Technology” Thought Leaders would stop taking credit for “new concepts” that have been around forever and then disparaging people by patronizing statements like:

“It is a pretty safe bet that — despite your deep technical background — you find that you have some genetic defect that makes it completely impossible for you to understand articles with titles like Continuations Made Simple and Illustrated.”

It’s not that people don’t understand the concepts, it’s because it’s misused or overhyped for the sake of being overhyped. Sort of what you’ve done here.

And instead of throwing a concept at a problem, how about analyzing the problem domain before you go off and recommend a solution. For instance, the Fibonacci solution could’ve been solved using Binet’s Theorem (in Javascript):

var C1 = Math.pow(5.0,0.5);
var PHI =  (1+ C1)/2;

// Return the n’th Fibonacci number 
function fib(n){
  value = ((Math.pow(PHI,n+1) - Math.pow((1-PHI),n+1)))/C1;
  return parseInt(value)

Now you have a solution that is closed form, constant time as n -> Infinity and is thread-safe if coded in multi-threaded language environments and lo and behold is a lot shorter ( or should I say more “agile” to be PC) than your bloated continuation solution.

Posted by Frank Bolander at

Continuations and the e2e principle

Exactly a decade ago, Alan, Tom, Dan, Dave, Brock, and I were under incredible pressure at work: we had a potentially huge application development deal in hand, and needed to do our best to close the deal. Sarah and Greg (and Transarc, unknown to...

Excerpt from Deep in the Heart of .... France? at

setjmp and longjmp are a very limited form of continuation--they can only “jump” up the stack to an existing caller. They don’t save a copy of the stack; they only save a pointer to a stack frame on the current stack.

You can implement non-portable continuations in C by storing local variables on the heap and using <code>memcpy</code> to save copies of the entire stack. When you invoke a continuation, you need to switch over to the saved stack.

(And, yeah, there’s a closed-form solution for the Fibonacci series. It’s a toy example. Python’s generators are useful when there isn’t a closed form solution, or when it’s ridiculously complicated.)

Posted by Eric at

Sam Ruby on Continuations

... [more]

Trackback from Don Box's Spoutlet

at

Whilst the article is very well written I don’t think it makes a strong case for continuations in an OO language. Objects are very good at retaining state between calls! The following fib code is simpler and doesn’t require anything that a common OO language can’t do:

class Fib {
    int i = 0;
    int j = 1;

    int eval() {
        final int result = i;
        i = j;
        j += result;

        return result;
    }

    public static void main( final String[] notUsed ) {
        final Fib f = new Fib();

        for ( int n = f.eval(); n <= 1000; n = f.eval() ) {
            System.out.println( n );
        }
    }
}


Posted by Howard Lovatt at

Now really, if you don’t understand them after this I’d give up programming. [link]...

Excerpt from Talideon.com Linklog at

Continuations Explained

Continuations are a fascinating feature of some programming languages that...well, the problem is that they’re hard to describe, and groking their implementation can make your head spin. Thankfully, Sam Ruby has an excellent and lucid discussion of...

Excerpt from Quabit: the Blog at

Howard, simple generators can certainly be recast as objects — which, after all, can be viewed as collections of name/value pairs allocated on the heap.

SAX is an example where the state is somewhat more involved, and more difficult to capture and restore.

Posted by Sam Ruby at

Continuation:  still not quite convinced

Sam Ruby and Don Box have posted a couple of interesting articles on continuations.  Sam’s article is a good explanation of what continuations are for "old-timers" and gives a...... [more]

Trackback from Otaku, Cedric's weblog

at

Sam Said :) “simple generators can certainly be recast as objects — which, after all, can be viewed as collections of name/value pairs allocated on the heap.”

I agree totally with this comment, in fact I often use a Java Collection as a generator, i.e. extending AbstractCollection, AbstractList, etc., and instead of having an array storing values I calculate the value on the fly. I also use this for lazy evaluation of lists.

I can also counter your SAX example with java.util.Scanner, which is a parser written as though it were an Iterator. Therefore I suspect that all such continuations can easily be recast as objects and that the existing Collections that are in most OO languages can be used to provide the base. In particular there is little difference between a continuation and an Iterator (which are in Java, C++, Smalltalk, etc.).

I am not saying that continuations aren’t useful in none OO languages, just that having got OO and some form of Collection there is little need for the extra facility.

Posted by Howard Lovatt at

Howard, some tasks that continuations can do can be accomplished by a generator, and some generators can easily be recast as an iterator.  But the reverse is not always true.

As an exercise, see if you can “easily” convert the following to not use iterators: tokenize.py.

When Don Box mentioned that C# has a yield instruction, he did not mention mention that what C# has amounts to compiler magic: it takes the instructions and converts it into a state machine.  Instead of capturing the scope, it makes copies of everything it references.  Non-trivial stuff.

In any case, Ruby is a thoroughly OO language, and Ruby programmers actually do make heavy use of blocks.

Posted by Sam Ruby at

Continuaciones para cascarrabias

Suelo consultar el blog de Sam Ruby, porque tiene comentarios breves pero muy interesantes. En este caso se me escapó fue un articulillo un poco más largo titulado “Continuations for Curmudgeons” (continuaciones para cascarrabias). Me ha resultado...

Excerpt from Yet Another Programming Weblog at

If i had read this about a year ago i might have gotten a decent grade at my functional programming exam. Anyway i’m really glad that i understand now, at least the basics, of this concept. I wonder if my professor knew that call-cc still involves frames... or maybe it was a test to see if i can figure it out my self ... well ...

Posted by bogdanutz at

About Continuations

Sam Ruby wrote a piece on Continuations, Don Box followed up....

Excerpt from Jan-Erik's Weblog at

Sam, I have posted a comment on your Blocks for Box discussion you reference. It basically says that inner classes cover much the same ground as closures, blocks, or what ever you want to call them and that inner classes have some advantages. The primary difference is that a Java inner class does not have write access to local variables (it can read final local variables).

Some people find this too restrictive, but I like it because I have seen bad code written using blocks in other languages. The particular bit I like about the none-write restriction is that it decouples the inner class from the surrounding code more. In fact I would go as far as to say that I wished for, if, etc. were the same. IE I wish

int[] list = { 1, 2, 3 };
int sum = 0;
for ( int item : list ) sum += item;

was illegal in Java. The bit I don’t like is that you can’t refactor the above into:

int[] list = { 1, 2, 3 };
int sum = 0;
for ( int item : list ) sumIt( item );

IE you can’t take the block and turn it into a function and I think the block should behave like a function to increase the decoupling.

Posted by Howard Lovatt at

Sam, I forgot to mention - why is tokenize.py so different than java.util.Scanner? Continuations can be converted to Iterators using a state machine. Therefore using Iterators the worst case is that you add an int to keep track of the state and a switch statement to select the state. In many cases the state already exists and needn’t be explicitly coded, e.g. fib. With continuations you have to explicitly code repeats, e.g. in fib example you needed to add while( true ) loop. Seems to be about the same overhead with each technique!

Posted by Howard Lovatt at

Howard, if you want if, while, for etc to be side effect free, you will quickly find that they are useless.

Try untangling any non-trivial program into a flat state machine.  It can be done, but it is not easy.  It also requires more than an int - all local variables must be captured and accessed indirectly.

One can make the case that all C++ programs can be coded in C (after all, the initial “compilers” were mere translators).  The more interesting question isn’t whether it can be done, but whether concepts like classes and blocks are useful.

Those that have programmed with these concepts tend to quickly find them useful.  Those that haven’t tend not to know what they are missing.

Both C# iterators and Java inner classes take significant short cuts, and therefore are limited in what they can do with respect to full blocks, closures, and continuations.

Posted by Sam Ruby at

i18n (Globalization) usando Mono.Posix (i18n globalization using Mono.Posix)  enzo writing in the blog Mono explains how to write and compile the class i18n in Mono.Posix and use it for internationalization of applications in...

Excerpt from Extracts from Planeta Codigo at

Continuations for Curmudgeons [lambda].......

Excerpt from Gimboland at

Continuations

Continuations for Curmudgeons. ]]>...

Excerpt from Jean-Claude Wippler at

Sam, what you say is correct: both about untangling continuation code and adding features to languages. I guess we disagree on what is good, not on the principle itself.

First untangling code, continuation code is often reminiscent of unstructured goto code and for the same reason that unstructured goto code is hard to untangle then so can continuation code. I guess we disagree on whether unstructured code is good or not.

Second on features, this was my original point. Is it worth adding continuations, closures etc., when you already have classes? Particularly in Java which has inner classes? My call is no, yours is yes.

Posted by Howard Lovatt at

Howard, it is not about structured vs unstructured.  The question is whether one should always be required to use a heavyweight solution when a lightweight one will do.

Posted by Sam Ruby at

Sam, I don’t know about implementation detail for the lightweight heavyweight issue. My comments are based on my assumption that at runtime the two are fairly similar. To summarize:

Pro closures/blocks
  short syntax
  write access to local variables

Pro inner classes
  can have fields
  can have more than one method
  can extend abstract classes and hence reuse code
  no need for an extra concept

So as a compromise I would suggest inner classes with shorter syntax and write access to local variables. This language may already exist, BETA, it certainly has short syntax and inner classes, I can’t remember about write access :)

Posted by Howard Lovatt at

Old webdesign grudge

Let me see if anyone agrees. A suggestion for web designers (and I mean all the bloggers out there, too): make the main text on your blog look good in your browser(s) by setting the default fonts (and mainly sizes)...... [more]

Trackback from Kopretinka

at

Sam, except for my font size grudge (see the trackback), thanks for this! While I had a simple understanding of what continuations do before, now I know how they do it and that there are really the edge cases I suspected, but, as you say, since they don’t often cause problems, I feel better about continuations now. 8-)

Posted by Jacek (Kopretinka) at

Jacek: I get the following:

Your comment submission failed for the following reasons:

You are not allowed to post comments.

Please correct the error in the form below, then press Post to post your comment.

The comment I wanted to post follows:

I’m confused.

My main content is 100%.  That should translate to be the default size, right?

I did not change my default font size for monospace fonts on either FireFox or IE.  In both, they appear smaller than the surrounding text to me.  Adjusting it slightly (120%) makes them closer.  And the results smoothly scales with both browsers.

I guess I could change my defaults, but then visitors would not see the results.

Given my css file, what would you recommend changing?

Posted by Sam Ruby at

Hi Sam, sorry about that “comments disabled” problem, too much IP banning (everybody), fixed now. 8-)

My problem is with that 120% on monospace. If you don’t like your browser’s defaults because the default size is too small for you (or smaller than the other fonts) you can tweak that. Then you’ll be able to leave everything (the main textual content, that is) at 100%.  The fact that others wouldn’t see the results of your font size tweaking is IMO good because others don’t necessarily have default monospace smaller than other fonts.

I won’t send you a dead fish if you don’t do it - disrespecting others' defaults is too widespread. It was just that in this case I couldn’t use simple zoom to be able to read your (very good) post without being disturbed by variables sticking out of text. 8-)

Posted by Jacek at

Jacek - refresh, and see if that is any better.

Posted by Sam Ruby at

Sam, thanks, of course it’s better now. One more accessibility improvement on the Web, I consider my day very successful. 8-)

Posted by Jacek at

Modal webapps, iterators and beyond

Excellent, easy to understand for old fashioned programmers, the introductory lecture that Sam Ruby does about continuations, Continuations for Curmudgeons. Brian McCallister writes about guidelines to write webapps, including a reference to the...

Excerpt from Boxes and Glue (Santiago Gala) at

Also take a look at java.util.concurrent.Exchanger in:

[link]

It does a yield like suspension of a thread:

exchanger.exchange( dataBuffer );
Posted by Howard Lovatt at

C# Continuations useful? Hell yeah!

Last week, Sam Ruby posted a very interesting article on continuations for “people older than dirt” (a category which I, according to his definition, fall into). The topic became even more interesting when Don Box posted how you can use a very similar syntax in the next iteration of C#. Shortly thereafter, Cedric Beust posted that he wasn’t convinced on...... [more]

Trackback from public virtual MemoryStream

at

Sam Ruby: Continuations for Curmudgeons

(posted by sighup, keywords: continuations,dynamic languages,python,ruby,javascript)...

Excerpt from list9 > all members at

Amazing!

If you have some background in programming, try to write a program to display  Fibonacci numbers less than 1000. Here is my version in C++: void main() {     int...

Excerpt from Flying Eagle at

Sam Ruby: Continuations for Curmudgeons

Wonderful article, helping us old C people to clue in. Link: Sam Ruby: Continuations for Curmudgeons. This essay is for people who, in web years, are older than dirt.  More specifically, if there was a period of time in which......

Excerpt from Virtual Pragmatics at

I’m older than dirt

... [more]

Trackback from Uffe's Blog

at

Sam Ruby: Continuations for Curmudgeons

Sam Ruby: Continuations for Curmudgeons...

Excerpt from frogspit at

Sam Ruby on Continuations

This is an old link in web time, almost a month old. Regardless, if you haven’t read it and you’re interested in programming paradigms, you should. I’ve been a fan of Ruby and other scripting languages for a while so I had an basic understanding of...

Excerpt from DevelopingStorm at

Continuations

Everybody who started in a language other than a web scripting one has written programs like this: WriteLn('What''s your name?'); ReadLn(name); WriteLn('What''s your age?'); ReadLn(age); WriteLn('Hello ‘ + name + ’, you are ‘ + age + ’ years old.');...

Excerpt from ZefHemel.com at

Links for 2005-05-02 [del.icio.us]

Sam Ruby: Continuations for Curmudgeons Coroutines in C...

Excerpt from PlasticBoy at

Links for 2005-05-02 [del.icio.us]

Sam Ruby: Continuations for Curmudgeons Coroutines in C...

Excerpt from PlasticBoy at

Sam Ruby: Continuations for Curmudgeons

I found this article on the concept of continuations really cool, which makes me older than dirt, I suppose....

Excerpt from Jeff's Blog at

Sam Ruby has a much praised blog entry entitled “Continuations for Curmudgeons”. I didn’t like the tone of the article which seem to treat the C programmers as some kind of dinasaur with no interest in other languages (or language...

Excerpt from Steve's Stuff at

Orthagonality, continuations and frogs

This is the first post (excluding the test) to the Design Patterns NYC blog. Schedule permitting I’ll try to follow up the week’s discussion with a quick summary, at the very least the chapters covered and topics discussed. First, the turnout was...

Excerpt from Design Patterns NYC at

Continuation-based web programming

People reading this blog might be forgiven for thinking that I don’t do software development for a living, so here’s some technical stuff to even up the balance. Spent some of the weekend reading up on continuation-based web programming. This......

Excerpt from markallerton.com at

User Guide - Part Three

I was out for this weekend and will be busy the next few days, but today I’ll talk about continuations. I really don’t think I’m up to the task of explaining continuations, however this is a good introduction on the topic. So, what will...

Excerpt from the Jau Virtual Machine at

Continuations in SQL: Using #temporary table created in stored procedure in its

... [more]

Trackback from Misha Bergal's blog

at

My experiments with continuation in C#

The blogs are buzzing with continuation support in C# 2.0 and what cool things can be done with it. [link] explains the concept of continuation extremely well. I also found Don Box’s...

Excerpt from I know the answer (its 42) at

Iterator, generator, coroutine and continuation...

今天, 本來打算將iterator弄清楚, 然後做個結束 沒想到看了幾個blog後, 從 iterator => generator => coroutine => continuation 愈來愈複雜, 一發不可收拾 所以先把目前看到的記下來, 再消化一陣子...   continuation這個觀念, 自從我在stackless python中看到後 一直是自己希望瞭解的東西 不過可能因為資質不太好, 當時看了幾次, 都不是很清楚 但是, 現在我覺得,...

Excerpt from 打發時間的小地方... at

Binkley: My kind of technical writer

Sam Ruby writes about continuations for old-time programmers like me. Anyone who starts of a technical article with: This essay is for people who, in web years, are older than dirt. and after the first example observes: If you now look around, you...

Excerpt from Planet Ruby at

Links for 2005-09-20 [del.icio.us]

Sam Ruby: Continuations for Curmudgeons Reengineer That Ad - Forbes.com RAA source code search [preview]: raggle/raggle [link]...

Excerpt from feed for thought at

Python.

So far, the things I like about Python: the functional programming stuff: filter/map/reduce ranges list comprehension sets and operations on sets loops and iterators/generators introspection continuations (code invocation context awarness) Things I...

Excerpt from Technology reading at

From reading, I know continuations will be added in perl6 and are in ruby and python, but I really didn’t understand them. Like closures they are a simple idea but very powerful. Here is an post that explains continuations quite well....

Excerpt from RLB3.COM: Continuations for Curmudgeons at

Fun with Functional JavaScript

My recent reading has included: The Secret Art of Futamura Projection Parenscript - Lisp dialect that compiles to JavaScript Continuations in Mozilla Continuations for Curmudgeons As a result, I’m in a very functional mood now, particularly with...

Excerpt from Thought Torrent at

A. Sundararajan: Continuations in JavaScript

Rhino JavaScript engine (which is included in Mustang) supports Continuations. Rhino optimizer needs to be switched off to enable continuations — i.e., scripts are run in interpreted mode and Rhino does not generate bytecodes for scripts. In...

Excerpt from Planet JDK at

In Order of Importance?

The inimitable David Heinemeier Hansson points out that in a recent set of slides by Sam Ruby, Rails is the fourth item from the top on a list of things Worth Watching. What’s item number three? Continuations. Sam also brings us Continuations for...

Excerpt from HREF Considered Harmful at

More fun with ruby

Jim Weirich’s presentation on Dependency Injection (in ruby).If you are a ruby newbie, read Jim’s guide for Java programmers. And the cherry on the cake: Jim’s presentation on continuations.For more continuation goodies, see Sam Ruby’s explanation,...

Excerpt from thought-tracker at

Web heresies and Python frameworks

Seaside is an innovative web application framework, written in Smalltalk. You may have heard something about it recently, probably referred to as a “continuation based framework”. Avi Bryant, the mind behind Seaside, will be speaking about...

Excerpt from I blog therefore I am at

Fibonacci via continuation in Euphoria language...or would this not be considered to be a continuation?  You can call this multiple times without the callers interfering with each other results wise. If not, maybe this simulates the effect of a continuation?

include get.e

function fibonacci(sequence obj)
if length(obj) = 0 then
obj = {0, 1}
end if
obj = obj & (obj[$-1] + obj[$])
return obj
end function

puts(1, "\n")

sequence s1
s1 = “”

for i = 1 to 10 do
s1 = fibonacci(s1)
print(1, s1)
puts(1, "\n")
end for

integer ch
ch = wait_key()

Posted by Marc Conley at

Sam Ruby: Continuations for Curmudgeons

Someone at Smarking has bookmarked your post.... [more]

Trackback from Smarking

at

JSR: Continuations

We need a JSR for Continuations. I’ve been working with Greg Wilkins to allow Ajax in DWR to work properly with Jetty Continuations. But Jetty Continuations are just one of a number of implementations of a great idea. We need a JSR so that I don’t...

Excerpt from Joe Walker's Blog at

Finite state machines vs. multithread, CPS to the rescue

Here is a simple implementation of a finite state machine driver. The nice thing is that state transition rules are all in one place (the Session constructor) and code driving state transition is all in one place, too (the go function). The bad...

Excerpt from hyperstruct at

Microsoft, Ruby, and War

... [more]

Trackback from Knowing.NET

at

No Need for First-Class Continuations in Java

Gilad Bracha posted a longish entry about continuations: [...] I’ve thought about this a bit, and here’s my take on why we really shouldn’t add continuations to the JVM. It’s bound to stir up controversy and annoy people,...

Excerpt from mult.ifario.us at

Continuatiions

If it’s accurate, this post over at idea.log is definately the clearest explanation of continuations I’ve ever read.  These two posts also look like they could be enlightening, but I haven’t finished digesting them yet....

Excerpt from Negative Acknowledgment at

The cocoon web model is employed by Raining Data’s (formerly Pick System’s) FlashCONNECT API.  We used it to web-enable a legacy application (written in PICK BASIC) that held most of its state in COMMON blocks.  The company for whom we did the consulting never transitioned to the REST model (difficult, since much of the code was automatically generated by a venerable program no one understood), so it was nice to have a framework which supported both models.  Continuations plus the idea of a timeout (ala Actors) and viola :-).

I am also much reminded of the implementation of Knuth’s Co-routines in C using Duff’s device (Simon Tatham has done so much for the world).  Heck, it’s even almost readable with some macros ;-).

-Tom

Posted by Thomas Trias at

Sam's continuations based REXML parser based on Expat

Just came across Sam’s REXML compatible XML parser based on Expat which had my brain thinking for a bit. The interesting thing about this XML parser (other than it implements the REXML interfaces with an Expat implementation) is that it’s......

Excerpt from crafterm's weblog at

Sam Ruby: Continuations for Curmudgeons

[link]...

Excerpt from del.icio.us/danhodos at

Closures for Java?

Wow. Not only does Neal Gafter have a blog, he’s talking about some dramatic changes in Java for JDK 7. Update: Oh dear. There’s a lot of traffic coming here from Neal’s blog. Apparently, people who read his post and are looking...

Excerpt from Wander, Think, Repeat at

Continuations

Everyone who understands continuations writes their own explanation of what they are and how they work. In fact, what follows is a list of those I found helpful:A page about call/ccUnderstanding Continuations, a thread on Lambda the Ultimate which...

Excerpt from Learn Things at

Musings on Java Closures and Continuations

I see lots of posts on closures and continuations (more, and more) lately, many relating to Java. See also lambda-the-ultimate.org. Must I re-hash what these are? No, not really. Now, I do find the evolution of Java here interesting. There is a...

Excerpt from Nico's blog at

Blogosphäre (aus JavaSPEKTRUM 05/06)

Starten wir mit der Kurzzusammenfassung: Java EE 5 (Nachfolger von J2EE) ist tot, Glassfish ist legitimer JBoss-Nachfolger, JRuby ist (fast) prima, und Java verwandelt sich in Lisp. Das könnte man zumindest glauben, wenn man die Links unseres...

Excerpt from JavaSPEKTRUM Blogosphäre at

Sam's continuations based REXML parser based on Expat

Just came across Sam’s REXML compatible XML parser based on Expat which had my brain thinking for a bit. The interesting thing about this XML parser (other than it implements the REXML interfaces with an Expat implementation) is that it’s pull based...

Excerpt from crafterm's weblog at

Collections in Base Language

Currently, it is almost not possible to write code in Base Language and avoid using of java collections and other JDK classes like Object and String. Such a dependency on Java is not good for BL (in the end, MPS is not a java development tool) and...

Excerpt from MPS Blog at

Finite state machines vs. multithread, CPS to the rescue

Update: the driver evolved from this article is now available as part of MozLab. Here is a simple implementation of a finite state machine driver. The nice thing is that state transition rules are all in one place (the Session constructor) and code...

Excerpt from hyperstruct: Finite state machines vs. multithread, CPS to the rescue at

Finite state machines vs. multithread, CPS to the rescue

Update: the driver evolved from this article is now available as part of MozLab. Here is a simple implementation of a finite state machine driver. The nice thing is that state transition rules are all in one place (the Session constructor) and code...

Excerpt from hyperstruct blog - Home at

My Experiments with continuation in C#Cross-posted from [link] blogs are buzzing with continuation support in C# 2.0 and what cool things can be done with it....

Excerpt from Don't Panic at

Finite state machines vs. multithread, CPS to the rescue

Update: the driver evolved from this article is now available as part of MozLab. Here is a simple implementation of a finite state machine driver. The nice thing is that state transition rules are all in one place (the Session constructor) and code...

Excerpt from hyperstruct blog - Main at

how closures relate to continuations: a good overview from Sam Ruby. Links: ps.uni-sb.de, intertwingly.net...

Excerpt from Jean Sini: structured communications at

Continuations for Java

Continuation is an object that represents the execution state of a program at a certain point. We can use continuation to restart the execution from the point stored in it. How about continuations for the Java platform? There are atleast two...

Excerpt from Java Planet - Daily Blog Posts about Java at

After the last LRUG meeting there was much discussion of continuations, and following up from that Ross pointed the LRUG irc channel at Sam Ruby: Continuations for Curmudgeons which explains continuations pretty damn well....

Excerpt from Codepapacy at

I do not think you understand continuations completetly.

~rAGU

Posted by Ragu at

Sam Ruby: Continuations for Curmudgeons

Sam Ruby: Continuations for Curmudgeons by gavrie & 2 other(s) dev continuations Copy | React (0) [link]...

Excerpt from Public marks with tag continuations at

Generator與串接Asynchronous calls

我們時常必須以一定的順序呼叫底層module所提供的函式。比如說, def callSeq(api): api.setEnv() api.produce() api.report() 這在任何procedural language當中都是很直覺的事情。但是GUI app的開發原則是,UI thread必須能夠很快的消耗event...

Excerpt from Simple, Complex and Complicated at

My Experiments with continuation in C#Cross-posted...

My Experiments with continuation in C# Cross-posted from [link] The blogs are buzzing with continuation support in C# 2.0 and what cool things can be done with it....

Excerpt from Don't Panic at

Closing in on Closures and Jumping into Continuations

Recently on ruby-talk someone asked if continuations and closures were the same thing. They are related in that they both are tied to a particular point in time in the execution of a program. The difference is that closures are like a souvenir of a...

Excerpt from Talk Like A Duck: Closing in on Closures and Jumping into Continuations at

Episodic Computation

Or, How I Learned to Stop Returning and Embrace Yield! You really should stop reading this and go read this . To this point in my career, I’ve found that Addison Wesley can be counted upon to deliver the more academically-minded texts on the topics...

Excerpt from IFormattable at

Sam Ruby: Continuations for Curmudgeons

[link]...

Excerpt from del.icio.us/tag/javascript at

JavaScript redux: Closures and Continuations

This is why I love being back blogging, I had three insanely smart people contact me to help me understand the problems I wrote about in my last post. First, Martin IMed and gave me yet another late night lesson in programming (I think the last...

Excerpt from Russell Beattie's Weblog at

Sam Ruby: Continuations for Curmudgeons

[link] [more]...

Excerpt from reddit.com: programming - newest submissions at

Bookmarks: August 6th through August 18th

Ruby on Rails Forum Vlad the Deployer Continuations Tutorial - Ruby New Foliotek Demo Making sense of monads Ubuntu + Postifix, a good tutorial Videolectures from rhe 24th Annual International Conference on Machine Learning LDAP integration in Ruby...

Excerpt from Mark McGranaghan at

Jeremy Zawodny : Continuations for Curmudgeons - Continuations for Curmudgeons: good stuff Sam.. I never saw this until last week. I wish I had. Tags : links...

Excerpt from HotLinks - Level 1 at

Modal webapps, iterators and beyond

Excellent, easy to understand for old fashioned programmers, the introductory lecture that Sam Ruby does about continuations, Continuations for Curmudgeons . Brian McCallister writes about guidelines to write webapps, including a reference to the...

Excerpt from Boxes and Glue at

Links for 11-Sep

Continuations made simple Rainbow tables and passwords — a resolution Styling with CSS and DOM — and a little bit of lateral thinking...

Excerpt from Distributed Memory at

Sam Ruby: Continuations for Curmudgeons

Sam Ruby: Continuations for Curmudgeons...

Excerpt from drawohara at

Sam Ruby: Continuations for Curmudgeons

Sam Ruby: Continuations for Curmudgeons (via Erik Jones)...

Excerpt from ni.hili.st at

Instead of viewing a stack as a contiguous sequence of bytes, let’s view a stack as a linked list of frames. (continuations for curmudgeons)

[link] [more]...

Excerpt from reddit.com: what's new online at

Just for fun, here’s the D programming language version of the fibonacci example, using the stackthreads module I finally made to work a few days ago and am now showing around happily :)

fib.d
module fib;
import std.stdio, tools.stackthreads;
class fib : Generator!(int) {
  void generate() {
  yield(0);
  auto i=0, j=1;
  while (true) { yield(j); auto t=i+j; i=j; j=t; }
  }
}

void main() {
  foreach (n; new fib) {
  if (n>1000) break;
  writefln(n);
  }
}

Pretty good for a C-family language, I’d say! :D
--FeepingCreature, D fanboy

Posted by FeepingCreature at

Just for fun, here’s the D programming language version of the fibonacci example, using the stackthreads module I finally made to work a few days ago and am now showing around happily :)

module fib;
import std.stdio, tools.stackthreads;
class fib : Generator!(int) {
  void generate() {
    yield(0);
    auto i=0, j=1;
    while (true) { yield(j); auto t=i+j; i=j; j=t; }
  }
}

void main() {
  foreach (n; new fib) {
    if (n>1000) break;
    writefln(n);
  }
}

Pretty good for a C-family language, I’d say! :D
--FeepingCreature, D fanboy

Posted by FeepingCreature at

Generators are not continuations

While I was looking around at some of the prominent examples of continuations on the internet, I saw a tendency to call a “generator” a type of continuation. Generators are great, but the only thing special about them is their ability to...

Excerpt from brynthomas.net at

Continuations, continued.

Long ago, Sam Ruby wrote an introduction to continuations and their use. This is likely the simplest, clearest introduction I’ve seen. Sam Ruby: Continuations for Curmudgeons Denys Duchier also wrote a description of continuations and continuation...

Excerpt from Maniagnosis at

Continuation dan Abstraksi Yang Bocor

Pertama tentang leaky abstraction (abstraksi yang bocor?) dulu. Law of leaky abstraction berbunyi: All non-trivial abstractions, to some degree, are leaky. TCP adalah abstraksi. TCP menjamin data yang anda kirim ke alamat tujuan pasti sampai. Tapi...

Excerpt from I Debug Codes at

Starting Continuations

This blog is titled Continuations because I did not want to call it Closures .  If that makes absolutely no sense to you, then some of my geekier posts may not either.  You may still want to stick around though because I plan to write about many...

Excerpt from Continuations at

Continuations explained

Post summary...

Excerpt from Martin's Notepad at

Continuations: Arc vs Java

What’s a continuation? Despite much googling on the topic, continuations remained opaque to me until I stumbled upon Sam Ruby’s amazingly excellent Continuations for Curmudgeons . Please read that article instead of this, it will be much more...

Excerpt from fnargs at

Continuation diggest

What behind this obscure title? Just a web programming paradigm which is very nice and enhances greatly the way of developping web applications. It is also another way of thinking, the consequence being maybe a difficulty for many to integrate the...

Excerpt from IceTea Tonic at

Real-world use of binding objects in ruby

Last night, I was thinking about what i think are advanced ruby language features, namely Continuations (callcc) and Binding objects. I mean advanced because I have a statically-typed oo langages background (C#, Java, C++), I discovered ruby very...

Excerpt from Real-world use of binding objects in ruby - Stack Overflow at

Re: Ъ gui toolkit is dead?

С этого места можно подробнее??? да в основном, общие соображения. вот тут про продолжения на [link] есть неработающая ссылка uist2003-uicont.pdf . Вот тут про паттерны и

...

Excerpt from Linux.org.ru: Ъ gui toolkit is dead? at

Re: Ъ gui toolkit is dead?

С этого места можно подробнее??? да в основном, общие соображения. вот тут про продолжения на [link] есть неработающая ссылка uist2003-uicont.pdf . Вот тут про паттерны и

...

Excerpt from Linux.org.ru: Ъ gui toolkit is dead? at

[conanite] This Sam Ruby article helped me a lot with continuations: ...

This Sam Ruby article helped me a lot with continuations: [link]... A continuation behaves just like a one-arg function except it never returns to its caller. It returns to the point where it...

Excerpt from AF.SearchYC - continuation at

Closing in on Closures and Jumping into Continuations

Recently on ruby-talk someone asked if continuations and closures were the same thing. They are related in that they both are tied to a particular point in time in the execution of a program. The difference is that closures are like a souvenir of a...

Excerpt from Talk Like A Duck : Category ruby_for_nubys, everything about ruby_for_nubys at

Re: lisp как препроцессор для C

есть ли там примитивы, транслирующиеся в сишные “функции с переменным числом аргументов” и setjmp? вот такая мысль про прозрачный Cи ABI <-> списки: В си есть полиморфизм указателей (на функции). Это полиморфизм типов символов.

...

Excerpt from Linux.org.ru: lisp как препроцессор для C at

Re: lisp как препроцессор для C

есть ли там примитивы, транслирующиеся в сишные “функции с переменным числом аргументов” и setjmp? вот такая мысль про прозрачный Cи ABI <-> списки: В си есть полиморфизм указателей (на функции). Это полиморфизм типов символов.

...

Excerpt from Linux.org.ru: lisp как препроцессор для C at

Add your comment