Smart slicing

Bill Baxter dnewsgroup at billbaxter.com
Thu Mar 20 18:39:59 PDT 2008


bearophile wrote:
> Hello, I have discussed this topic a bit on the IRC #D channel too.
> 
> Array slicing is a very useful feature of D. In Python the array (list) slicing is even more powerful, because array indexes can be negative (they wrap around, so -1 equals to $-1 in D, but I like the D solution too, it's faster too), and it has a third optional parameter (stride) that can be a negative number too:
> 

>>>> "abcdefghilmn"[2:30]
> 'cdefghilmn'
>>>> "abcdefghilmn"[30:50]
> ''
> 
> (I presume D has used .. instead of : because : is used by AAs, and {} can't be used to denote AAs because it's used already in the C syntax).
> I don't miss all those features in D (D arrays have .reverse that replaces the common case of stride=-1), but I miss the feature you can see in the last two examples, that is the overflowing index is put back to the actual max-min index bound of the array.

I had no idea you could do that in Python.  I'd much rather get an error 
there.  My guess is that most cases where you aren't sure how much to 
slice out are covered by end-relative indexes, like stuff[30:] or 
stuff[30:-1].  In D syntax stuff[30..$] and stuff[30..$-1].

For safe-to-go-out-of-bounds slicing like you're talking about, I'd 
rather implement that as a function call, something like your
   stuff.slice(2,30)
or you can probably get this syntax with current D
   stuff.slice[2..30]

It's not something that I'd want to use most of the time, and when I do, 
I'd want to make it clear that I'm relying on automatic bounds trimming.

--bb



More information about the Digitalmars-d mailing list