DMD 0.177 release [Length in slice expressions]
Bill Baxter
dnewsgroup at billbaxter.com
Fri Dec 22 03:27:11 PST 2006
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".
For those cases a we could have a small extension to your proposal. Have
$b translate to b.length, yes, but also have $[3]b and $(1)b translate
to to b.length[3] and b.length(1), respectively. Seeing that, it makes
me think perhaps $ would be better as a post-fix unary operator. Then
we'd have b$ --> b.length and b$[3] --> b.length[3].
Then of course the next step is to have a parameter number automatically
passed to the length method given and expression like a[$-1,$-1] so that
a[$-1,$-1]
==> a[$[0]-1,$[1]-1]
==> a[a$[0]-1,a$[1]-1]
==> a[a.length[0],a.length[1]]
The compiler can decide whether to do indexing or not based on whether
.length results in an indexable value.
Finally, in general I think the choice of name 'length' is unfortunate
because of it's implication of linearity. But it's not too late. If $
becomes associated with .size rather than .length in user types then
everything will be ok. For built-in arrays .length can become a synonym
for .size, just as it is with std::string in C++. C++/STL got this one
right. For generic containers .size is a much better name.
--bb
More information about the Digitalmars-d-announce
mailing list