View Full Version : Continuation
michele
September 21st, 2005, 07:58 AM
Why does the following code print "doing other stuff" twice?
def cc
puts "do A"
puts "----> 1. #{caller}"
callcc { |cont| return cont}
puts "----> 2. #{caller}"
puts "do B"
end
puts "calling cc"
cont = cc()
puts "doing other stuff"
cont.call() if cont
puts "end of work"
puts
result:
calling cc
do A
----> 1. remove2.rb:59
doing other stuff
----> 2. remove2.rb:59
do B
doing other stuff
end of work
steve_d555
September 21st, 2005, 07:39 PM
How 'bout something like this:
def cc
puts "do A"
puts "----> 1. #{caller}"
puts "doing other stuff"
callcc { |cont| return cont}
puts "----> 2. #{caller}"
puts "do B"
end
puts "calling cc"
cont = cc()
cont.call() if cont
puts "end of work"
puts
michele
September 22nd, 2005, 03:41 AM
The idea was that I wanted to leave cc's work in the middle, to do some work somewhere else and return to cc. Your code will of course work, but it doesn't show my intentions.
BlackEdder
September 22nd, 2005, 05:48 AM
It really seems like a bug.. You can see that the line codes are the same in both calls, ----> 2. remove2.rb:59
so clearly the "program" thinks it's being called from that line and returns there, resulting in the code in the middle being execute4d twice. Strangely the code works normally in irb
michele
September 22nd, 2005, 09:12 AM
That's because it remembers the context from where it returned - i.e. from callcc { |cont| return cont} in cc()
BlackEdder
September 22nd, 2005, 09:27 AM
Oops I kinda read over that line apparently.. What happens is this (let's see if I can explain it in words:)
cc is called from the line cont=cc()... It puts in a call_sign with the callcc and then immediately returns to the "main" program. Then: puts "doing other stuff". Then returns to the call sign, and as you remember cc() was called from the cont=cc() line so as soon as it ends the method cc() it will return to that line and redo: puts "doing other stuff"..
michele
September 22nd, 2005, 09:38 AM
http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/36708767909d56fa/6f42acf8c0a259d3#6f42acf8c0a259d3
You can follow this thread at Google Groups. I has some good answers.
vBulletin® v3.7.3, Copyright ©2000-2008, Jelsoft Enterprises Ltd.