complement to $

bearophile bearophileHUGS at lycos.com
Sat May 15 14:40:03 PDT 2010


KennyTM~:
> auto a = new OrderedDict!(int, string);
> a[-3] = "negative three";
> a[-1] = "negative one";
> a[0] = "zero";
> a[3] = "three";
> a[4] = "four";
> assert(a[0] == "zero");
> return a[0..4]; // which slice should it return?

D slicing syntax and indexing isn't able to represent what you can in Python, where you can store the last index in a variable:

last_index = -1
a = ['a', 'b', 'c', 'd']
assert a[last_index] == 'd'

In D you represent the last index as $-1, but you can't store that in a variable.
If you introduce a symbol like ^ to represent the start, you can't store it in a variable.

Another example are range bounds, you can omit them, or exactly the same, they can be None:

a = ['a', 'b', 'c', 'd']
>>> assert a[None : 2] == ['a', 'b']
>>> assert a[ : 2] == ['a', 'b']
>>> assert a[0 : 2] == ['a', 'b']
>>> idx = None
>>> assert a[idx : 2] == ['a', 'b']
>>> assert a[2 : None] == ['c', 'd']
>>> assert a[2 : ] == ['c', 'd']
>>> assert a[2 : len(a)] == ['c', 'd']

You can store a None in a Python variable, so you can use it to represent the empty start or end of a slice. 
But currently D indexes are a size_t, so they can't represent a null.

Bye,
bearophile


More information about the Digitalmars-d mailing list