From: Sean O'Halpin Date: 2008-09-11T03:27:07+09:00 Subject: Re: Local variable in loop affects callcc On Tue, Sep 9, 2008 at 5:48 PM, Pinku Surana wrote: > I was trying to do some simple backtracking, but it kept failing for > some reason. In the simplified version below, I use continuations to > return either a 1 or 2 from interval. testcc assigns a value to the > array, prints it out, then calls the next continuation on the stack > (@next_cc) to jump back into interval and return the other number. The > output should be: > [1, 1] > [1, 2] > [2, 1] > [2, 2] > > But if I introduce a temporary local variable, I get this instead: > [1, 1] > [1, 2] > [1, 1] # WRONG > [1, 2] # WRONG > > The local variable seems to cause the continuations to jump only to > the point where i=1, not where i=0 where it should go. How does a > local variable effect continuations like that? > > I'm using "ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux]" built > for Ubuntu. Thanks for your help. > > > > def interval > return callcc { |ret| > callcc { |k| > @next_cc.push(k) > ret.call(1) > } > ret.call(2) > } > end > > def testcc > @next_cc = [] > a = Array.new(2) > for i in 0...2 > # This produces the WRONG output > # x = interval > # a[i] = x > > # This produces the CORRECT output > a[i] = interval > end > > puts a.inspect > > while (not @next_cc.empty?) do > @next_cc.pop.call > end > end > > Like David, I haven't fully unravelled this myself, however it appears to be a scoping issue. If you replace the for i in 0..2 with (0..2).each do |i| you get the correct result in both cases. Regards, Sean