Arithmetic sequences in Python
Tom Anderson
twic at urchin.earth.li
Mon Jan 16 20:20:14 EST 2006
On Mon, 16 Jan 2006, Gregory Petrosyan wrote:
> Please visit http://www.python.org/peps/pep-0204.html first.
>
> As you can see, PEP 204 was rejected, mostly because of not-so-obvious
> syntax. But IMO the idea behind this pep is very nice.
Agreed. Although i have to say, i like the syntax there - it seems like a
really natural extension of existing syntax.
> So, maybe there's a reason to adopt slightly modified Haskell's syntax?
Well, i do like the .. - 1..3 seems like a natural way to write a range.
I'd find 1...3 more natural, since an ellipsis has three dots, but it is
slightly more tedious.
The natural way to implement this would be to make .. a normal operator,
rather than magic, and add a __range__ special method to handle it. "a ..
b" would translate to "a.__range__(b)". I note that Roman Suzi proposed
this back in 2001, after PEP 204 was rejected. It's a pretty obvious
implementation, after all.
> Something like
>
> [1,3..10] --> [1,3,5,7,9]
> (1,3..10) --> same values as above, but return generator instead of
> list
> [1..10] --> [1,2,3,4,5,6,7,8,9,10]
> (1 ..) --> 'infinite' generator that yield 1,2,3 and so on
> (-3,-5 ..) --> 'infinite' generator that yield -3,-5,-7 and so on
-1. Personally, i find the approach of specifying the first two elements
*absolutely* *revolting*, and it would consistently be more awkward to use
than a start/step/stop style syntax. Come on, when do you know the first
two terms but not the step size?
> 1) "[]" means list, "()" means generator
Yuck. Yes, i know it's consistent with list comps and genexps, but yuck to
those too!
Instead, i'd like to see lazy lists used here - these look like lists, and
can be used exactly like a list, but if all you want to do is iterate over
them, they don't need to instantiate themselves in memory, so they're as
efficient as an iterator. The best of both worlds! I've written a sketch
of a generic lazy list:
http://urchin.earth.li/~twic/lazy.py
Note that this is what xrange does already (as i've just discovered).
tom
--
Socialism - straight in the mainline!
More information about the Python-list
mailing list