Can I copy a generators state and then backtrack to it if necessary?

Steve Horne sh at ttsoftware.co.uk
Fri Jul 20 11:31:34 EDT 2001


Can I copy a generators state and then backtrack to it if necessary?

To explain what I mean, imagine the following...

  from __future__ import generators

  def test_gen (p) :
    for i in range (p) :
      yield i

  def use_gen (p) :
    i = p.copy ()  #  or some equivalent

    #  Do something that may accept values from p

    p = i   #  Backtrack

    #  Do something that may accept values from p


  use_gen (test_gen (50))


I know that I could rewrite the use_gen function to accept a function
rather than a generator, so that it would be called as...

  use_gen (test_gen, 50)

... and the function parameter could then be evaluated to rederive the
initial generator state at any time, but this isn't really as flexible
(you can't easily recreate any state other than the initial state),
and it also seems less intuitive to me.

A major use I could think of for this is in applications that need to
balance searching by depth and by breadth according to some heuristic.
In addition to the search tree so far, it would be easy to record
generator states that have only identified some of the branches from a
particular state - so you could explore this area of the tree
depth-wise for a bit then nip-back to expand the breadth later. An
obvious application would be for board games such as chess.

-- 
Steve Horne
Home : steve at lurking.demon.co.uk
Work : sh at ttsoftware.co.uk



More information about the Python-list mailing list