Jeff Mesnil
Weblog · Dev · Photos · Books

Continuations In Ruby

March 24, 2005

updated with a code example

Via Tim Bray, I read an example of Continuations in Ruby.

The example is very impressive but I didn't grok it at first (I'm still not sure to have understood it yet!).

After some searches on continuations, I found this funny analogy on the RubyGarden Wiki which helped me to understand better what continuations are.

I don't see yet where and when I would use them but it's a new way for me to think about the execution of the code that I'm not accustomed to. Very interesting stuff!

Here is the Ruby code corresponding to the analogy:

puts "Walking..."
turn_left = callcc do | turn_left |
    turn_left
end
if turn_left
  puts "Turning left..."
  puts "Bitten by a dog!"
  bitten = callcc do | bitten |
      bitten
  end
  turn_left.call false if turn_left
  puts "I prefer to bleed!"
else
  puts "Turning right..."
  puts "Hit by a train!"
  bitten.call
  puts "DEAD!!"
end

which outputs

Walking...
Turning left...
Bitten by a dog
Turning right...
Hit by a train!
I prefer to bleed!

The simple example is no better than using goto statements but the example in Continuations on the Web shows that continuations can become more powerful than that when they keep state.