myrange.at(i) for myrange.dropExactly(i).front
Jonathan M Davis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Jul 25 18:13:05 PDT 2014
On Saturday, 26 July 2014 at 00:28:32 UTC, Ary Borenszweig wrote:
> On 7/25/14, 6:39 PM, Jonathan M Davis wrote:
>> On Friday, 25 July 2014 at 21:33:23 UTC, Timothee Cour via
>> Digitalmars-d-learn wrote:
>>> Is there a function for doing this?
>>> myrange.at(i)
>>> (with meaning of myrange.dropExactly(i).front)
>>> it's a common enough operation (analog to myrange[i]; the
>>> naming is from
>>> C++'s std::vector<T>::at)
>>
>> That would require a random access range, in which case you
>> can just
>> index directly. For a non-random access range, which you're
>> doing would
>> be the most direct way of doing it.
>>
>> - Jonathan M Davis
>
> No, the OP said the meaning was `myrange.dropExactly(i).front`,
> which is not a random access.
>
> Sometimes you *do* want the n-th element of a range even if the
> range is not a random access.
That is an inherently expensive operation, so it would be a very
bad idea IMHO to support it. The OP referenced vector, which has
random access, and that's a completely different ballgame.
In general, when operating on ranges, you should be trying to
iterate over them only once and to backtrack as little as
possible if you have backtrack. It's true that's not always
possible, but if at() were O(n), then it would make inefficient
code less obvious.
I'd argue against at() working on non-random access ranges for
the same reason that std.container doesn't support containers
with a length property of O(n) - because it's a function that
looks like it's O(1), and programmers will consistently think
that it's O(1) and misuse it. C++ has had that problem with
std::list' size function which is O(n). at() looks like it would
be O(1) (and it always is in C++), so it would be inappropriate
to have it in cases where it would need to be O(n), and since we
already have [], why add at()? It exists on vector in addition to
[] to give it range checking random-access. We already have that
in D with [].
myrange.dropExactly(i).front makes it much more obvious what
you're doing and that it's inefficient. It might be necessary in
some cases, but we don't want to give the impression that it's
cheap, which at() would do.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list