Re: iteration count register

Lou Kates (louk@research.teleride.on.ca)
Sun, 12 Jul 1992 14:10:41 -0400

Forwarded message:
> From: brannon@jove.cs.caltech.edu (Terrence M. Brannon)
>
> I notice I have to do certain things by myself in Python that it would
> be nice if there were registers for. The one example I keep running
> into right now is if I have a loop like this:
>
> tmp = open('file','r').readlines()
> iterationCount=0
> for line in tmp:
> iterationCount = iterationCount + 1
> if regex.match('adfasdf',line) > 5
> break
> else:
> serverloop_code.insert(iterationCount,line) # line X
>
> It would be nice if iterationCount were a pre-defined register like @i
> or something so the code could be more compact . However, it would be
> more cryptic to someone just getting into the language. Registers were
> the main thing that made me quit learning Perl quickly.
>
> Another way to look at this is that since Python is an object-oriented
> language the for statement above is sending a message to `for' with 2
> arguments. Since objects have their own private data, it would seem
> that we could type serverloop_code.insert(for.current_pos(), line) at
> line X to access some data in the `for' object.
>
> What do you all think ?
>
> --
> terrence brannon
> brannon@jove.cs.caltech.edu
>
>

> tmp = open('file','r').readlines()
> iterationCount=0
> for line in tmp:
> iterationCount = iterationCount + 1
> if regex.match('adfasdf',line) > 5
> break
> else:
> serverloop_code.insert(iterationCount,line) # line X

Your OO solution seems neat.

Note that if your only objective is reduction in code size then
the above example could be reduced to the same size as the
perlized python solution by iterating over an index instead of
over the lines themselves:

lines = open('file','r').readlines()
for i in range(len(lines)):
if regex.match('adfasdf',lines[i]) > 5:
break
else:
serverloop_code.insert(i,lines[i])

My example still has a few problems:

- you have to generate the range(len(lines)) list. If the
number of lines is large this seems rather wasteful.

- if the number of lines were unbounded then the previous
point is even worse and you have to introduce a number HUGE
which is unpleasant:

for i in range(HUGE):

- there is an extra array reference (lines[i]) which adds to
complexity

On the other hand this solution has one less variable than the
perlized python solution and the variable it eliminates is the
builtin register variable which is the one most onerous.

-- 
Lou Kates, louk@research.teleride.on.ca