complement to $
Simen kjaeraas
simen.kjaras at gmail.com
Sat May 15 15:10:56 PDT 2010
On Sat, 15 May 2010 23:46:12 +0200, Walter Bright
<newshound1 at digitalmars.com> wrote:
> bearophile wrote:
>> 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.
>
> Sure you can:
>
> last_index = a.length - 1;
Ah, but if you then change the length of a, last_index is no longer
correct. Now, if we had a special index type...
enum slice_base {
START,
END
}
struct index {
ptrdiff_t pos;
slice_base base;
// Operator overloads here, returns typeof( this ) if +/-
// integral, ptrdiff_t if subtracted from
// typeof( this ).
}
immutable $ = index( 0, slice_base.END );
immutable ^ = index( 0, slice_base.START );
auto last_index = $ - 1;
auto third_index = ^ + 2;
These would then stay valid no matter what you
did to the container.
--
Simen
More information about the Digitalmars-d
mailing list