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:
Will produce the following output:
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:
That will give you this output:
state = "label 1"
continuation = callcc { |c| c }
puts "state: #{state}"
state = "label 2"
continuation.call if continuationWill produce the following output:
state: label 1
state: label 2Note 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 continuationThat will give you this output:
state: label 1
state: label 2
state: label 2
state: label 2
... (ad nauseam)
