continuations and state

Ruby continuations have been described as "going back in time" in your program, but that's not really true. You go back into the stack, but all your state remains the same. This ruby snippet:

state = "label 1"
continuation = callcc { |c| c }
puts "state: #{state}"
state = "label 2"
continuation.call if continuation


Will produce the following output:

state: label 1
state: label 2


Note that the state variable keeps it's value. This is how you can do useful programming with continuations, even though you've jumped "back in time."

The next wierd thing, is that we don't get stuck in a loop. Notice "if continuation"? The second time we try to call the continuation, it is nil.

If you want, you can make a loop by doing the assignment inside the callcc block:

state = "label 1"
continuation = nil
callcc { |c| continuation = c }
puts "state: #{state}"
state = "label 2"
continuation.call if continuation


That will give you this output:

state: label 1
state: label 2
state: label 2
state: label 2
... (ad nauseam)



~ Patrick May