I like the idea, but this would be nicer in a language with implicit currying so that your example could be:

for i in Range(1, N, (*2)):
...

Or in Haskell:

range' v a b f
| a == b = []
| otherwise = f a:range v a+v b f

range a b
| a > b = range' -1 a b
| a < b = range' 1 a b
| a == b = []

Since Python doesn't have this, the generator forms others showed would likely end up more concise.


On July 2, 2015 1:30:53 AM CDT, Pierre Quentel <pierre.quentel@gmail.com> wrote:
In languages such as Javascript, the incrementation of a for loop counter can be done by an operation, for instance :

for(i=1; i<N; i*=2)

would iterate on the powers of 2 lesser than N.

To achieve the same thing in Python we currently can't use range() because it increments by an integer (the argument "step"). An option is to build a generator like :

def gen(N):
    i = 1
    while i<=N:
        yield i
        i *= 2

then we can iterate on gen(N).

My proposal is that besides an integer, range() would accept a function as the "step" argument, taking the current counter as its argument and returning the new counter value. Here is a basic pure-Python implementation :

import operator

class Range:

    def __init__(self, start, stop, incrementor):
        self.start, self.stop = start, stop
        self.incrementor = incrementor
        # Function to compare current counter and stop value : <= or >=
        self.comp = operator.ge if self.stop>self.start else operator.le
        self.counter = None
   
    def __iter__(self):
        return self
   
    def __next__(self):
        if self.counter is None:
            self.counter = self.start
        else:
            self.counter = self.incrementor(self.counter)
        if self.comp(self.counter, self.stop):
            raise StopIteration
        return self.counter

Iterating on the powers of 2 below N would be done by :

for i in Range(1, N, lambda x:x*2)

I haven't seen this discussed before, but I may not have searched enough.

Any opinions ?



Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

--
Sent from my Android device with K-9 Mail. Please excuse my brevity.