From: Pinku Surana Date: 2008-09-10T03:43:38+09:00 Subject: Re: Local variable in loop affects callcc On Sep 9, 1:30 pm, "David A. Black" wrote: > Hi -- > > > > On Wed, 10 Sep 2008, 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 > > I haven't unraveled it entirely but I believe it's not about the local > variable itself; it's about the fact that the interval method gets > called before the assignment to a[i]. If you do this: > >    a[i] = x = interval > > you'll get the result you want. > > David > > -- > Rails training from David A. Black and Ruby Power and Light: >    Intro to Ruby on Rails  January 12-15   Fort Lauderdale, FL >    Advancing with Rails    January 19-22   Fort Lauderdale, FL * >    * Co-taught with Patrick Ewing! > Seehttp://www.rubypal.comfor details and updates! "a[i] = x = interval" probably gets translated into "a[i] = interval" anyway because x is not used. I want to do something with the value of x before I assign it to the array. The sample code I posted is just a simplified version of my code that still exhibits the bug.