| Store | Cart

Suggesting a new feature - "Inverse Generators"

From: Andrew Koenig <a...@acm.org>
Fri, 25 Mar 2005 16:18:47 GMT
"Jordan Rastrick" <jrastrick at student.usyd.edu.au> wrote in message 
news:1111766687.125697.311420 at f14g2000cwb.googlegroups.com...

> def combineIntoRecord(): # This is an acceptor function>       optionalline = None # We may not get given a value for this line>       accept firstline>       accept secondline>       if condition(secondline):>          accept optionalline>       accept lastline>       r = createRecord(firstline, secondline, lastline, optionalline)>       return r> recordlist = []> for line in lines:>     recordlist.append(combineIntoRecord(line))

How about doing it this way?

    class Acceptor:
        def __init__(self, gen):
            self.gen = gen
        def next(self):
            firstline = self.gen.next()
            secondline = self.gen.next()
            if condition(secondline):
                optionalline = self.gen.next()
            accept lastline
            r = createRecord(firstline, secondline, lastline, optinalline)
            return r

This is just a generator done longhand.  If anything in Acceptor.next raises 
StopIteration, so will Acceptor.next itself.  Which means that you can now 
write this:

    for r in Acceptor(line):
        recordlist.append(r)

or, for that matter,

    recordlist = list(Acceptor(line))

Incidentally, I did not try to fix the bug in your code that if 
condition(secondline) is false, optionalline never gets set so the program 
will crash :-)

Recent Messages in this Thread
Jordan Rastrick Mar 25, 2005 04:04 pm
Jordan Rastrick Mar 25, 2005 04:10 pm
Andrew Koenig Mar 25, 2005 04:18 pm
Jordan Rastrick Mar 25, 2005 04:36 pm
Andrew Koenig Mar 26, 2005 01:40 pm
Tim Hochberg Mar 25, 2005 04:25 pm
Michael Spencer Mar 25, 2005 04:46 pm
Jordan Rastrick Mar 25, 2005 05:23 pm
Michael Spencer Mar 25, 2005 06:41 pm
Serge Orlov Mar 25, 2005 07:14 pm
Jordan Rastrick Mar 26, 2005 06:56 am
Peter Otten Mar 26, 2005 08:04 am
Scott David Daniels Mar 25, 2005 07:34 pm
Michael Spencer Mar 25, 2005 08:07 pm
Scott David Daniels Mar 25, 2005 09:00 pm
Bengt Richter Mar 25, 2005 10:11 pm
Bengt Richter Mar 25, 2005 07:43 pm
Terry Reedy Mar 25, 2005 07:13 pm
Jordan Rastrick Mar 25, 2005 04:49 pm
Diez B. Roggisch Mar 25, 2005 06:13 pm
Jordan Rastrick Mar 26, 2005 04:11 pm
phil...@yahoo.com Mar 27, 2005 03:44 am
Oren Tirosh Mar 27, 2005 06:58 am
Messages in this thread