array slicing currently does not support steps?

Simen Kjærås simen.kjaras at gmail.com
Tue Aug 4 07:39:04 UTC 2020


On Monday, 3 August 2020 at 23:32:29 UTC, mw wrote:
> Hi,
>
> I just noted that D array slice does not support steps?
>
> https://dlang.org/articles/d-array-article.html
>
>
> Ever since Python 1.4, the slicing syntax has supported an 
> optional third ``step'' or ``stride'' argument. For example, 
> these are all legal Python syntax: L[1:10:2], L[:-1:1], 
> L[::-1]. This was added to Python at the request of the 
> developers of Numerical Python, which uses the third argument 
> extensively.
>
> https://docs.python.org/2.3/whatsnew/section-slices.html
>
>>>> L = range(10)
>>>> L[::2]
> [0, 2, 4, 6, 8]
>
>
> Shall we add a DIP for this?

Since D slices are just views of memory, this would either change 
how slicing works (copy the data when using stride), or change 
the memory layout of slices.

Currently, a slice is essentially a (ptr, length) struct, and 
adding stride to the mix would require adding another field to 
every slice. This would break all D code ever, so we can 
disregard that solution.

Copying the data doesn't actually break any code, since the 
no-stride case would be unaffected, and is the only case 
currently in use. However, having a different behavior here would 
break the principle of least astonishment.

Lastly, there's std.range.stride, which is an excellent 
workaround with none of these drawbacks.

All in all, a DIP is very unlikely to be accepted given the above.

--
   Simen


More information about the Digitalmars-d mailing list