DMD 0.177 release [Length in slice expressions]

Bill Baxter wbaxter at gmail.com
Fri Dec 22 13:53:16 PST 2006


Andrei Alexandrescu (See Website for Email) wrote:
> Bill Baxter wrote:
> 
>> Andrei Alexandrescu (See Website For Email) wrote:
>>
>>> But if we made "$" into an operator identifying the last element of 
>>> _any_ array, which could refer to the last element of _the left-hand 
>>> side_ array if we so want, then all of a sudden it becomes useful in 
>>> a myriad of situations:
>>>
>>> int i = a[$ - 1]; // get last element
>>> int i = a[$b - 1]; // get a's element at position b.length - 1
>>> if (a[$ - 1] == x) { ... }
>>> if ($a > 0) { ... }
>>> if ($a == $b) { ... }
>>> swap(a[0], a[$ - 1]); // swap first and last element
>>
>>
>> Please give some thought to the case where a and b are of types not 
>> easily characterized by a single '.length'.  Matrix classes, or more 
>> generally multidimensional array classes being the canonical examples. 
>>  For those cases it is desirable to be able to have a '$' with 
>> different meaning "per axis".
> 
> 
> I did. The thing with language design is that it's easy to either
> underdo or overdo it, and that where underdoing or overdoing starts is
> highly subjective.
> 
> IMHO the current meaning of "$" is a good example of underdoing. The
> "$expression" meaning "(expression).length" is (again IMHO) just right. I
> use collection.size() all the time in C++, and scalar(@array) or $#array
> all the time in Perl, inside and outside index expressions. So I'd be
> happy to have that. Taking it to the next step of meaning any
> subdimension of a multidimensional (or fractal, heh) structure is, IMHO,
> overdoing because I can think of few use examples that are both frequent
> enough and interesting enough.

Maybe so.  Multidimensional arrays seem as common as air from where I 
sit, but I can see that not everyone works with such things every day.

If $ really did become synonymous with .length (or preferably .size) 
then one could have .length return an array rather than a simple number. 
  In that case multi-dim'ers could have
    M[5..$[0]-1, 0..$[1]-5].
Eh.  Not so pretty.  For comparison, in Python that would be M[5:,:-5], 
and in Matlab that would be M(6:end, 1:end-4).  Both of those look much 
better to me.  If the index to go with $ could be supplied automatically 
by the compiler then D could have M[5..$-1, 0..$-5].

Taking a different tack, I wonder if repeated indexing can be made as 
efficient (or nearly) as a single multi-index?
     M[5..$-1][0..$-5]

That's much easier to look at than M[5..$[0]-1, 0..$[1]-5], at least. 
And it's more general in the sense that from looking at the expression, 
M looks just like a standard Type[][] array.

Hmm.  I'll play with that.  I think it's at least technically possible, 
now that D has the ability to override opAssign.

--bb



More information about the Digitalmars-d-announce mailing list