Case Range Statement ..

bearophile bearophileHUGS at lycos.com
Thu Jul 9 08:41:27 PDT 2009


Bill Baxter:
> Python's are a little annoying in that, like D, you can't use
> them outside of indexing expressions.  Can't even use them in loops.
> In NumPy, the numerical library for Python, they've invented some
> quirky objects like numpy.r_ which you index to create a range
> literal.  Like
>   >>>   numpy.r_[0:4:0.5]
>   array([ 0. ,  0.5,  1. ,  1.5,  2. ,  2.5,  3. ,  3.5])
> You could do the same in D, but I don't think anyone in NumPy thinks
> of it as a particularly elegant way to make ranges (compared to matlab
> where just plain 0:4:0.5 gets you the same thing).  Also you'd most
> often like to have that 4.0 in there, so you have to tweak the range
> to be [0:4.5:0.5] to get that inclusivity, because python doesn't have
> inclusive ranges.  Not ideal.  So they also have

For other people here:

>>> class C(object):
...   def __getitem__(self, key): return key
...
>>> c = C() # creation
>>> c[10]
10
>>> c[10:20]
slice(10, 20, None)
>>> c[10:20:30]
slice(10, 20, 30)
>>> c[...]
Ellipsis

So inside __getitem__ (that's like opIndex) the key is turned into a slice object, or even into a built-in Ellipsis object :-)

Bye,
bearophile



More information about the Digitalmars-d mailing list