std.v2020.algorithm etc[ WAS: Is run.d going to be expand for runtime and the phobos library?]

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Jun 23 04:48:28 UTC 2020


On Saturday, June 20, 2020 6:07:29 PM MDT Andrei Alexandrescu via Digitalmars-
d wrote:
> On 6/20/20 1:02 PM, Avrina wrote:
> > Most of the algorithms in Phobos don't call front() multiple times and
> > they make a copy.
>
> Interesting. They should be easy to fix then. Got a few examples?

Part of the problem is that sometimes, you very much want to be calling
front only once and storing the result, because front is calculated every
time that it's called (e.g. map calculates front on every call), whereas
other times, you want to call front multiple times so that you can avoid
copying the return value. To make matters worse, in the case of something
like map, while you might get equivalent values on each call to front, you
won't necessarily get exactly the same value with each call to front (e.g.
if map's predicate calls new). So, there's a strong argument to be made that
it's more correct and likely more efficient to call front only once even if
that means copying the return value. However, AFAIK, there isn't really
consensus on what the correct approach is for generic code, and I don't know
what the more common approach is in Phobos. I suppose that code could do
introspection on front to see whether it returned by ref such that it called
front multiple times if it returned by ref and avoided calling it multiple
times if it didn't, but I rather doubt that much of anyone is going to do
something like that in practice.

Obviously, if non-copyable types were to be supported, then it needs to be
the norm to avoid copying the return value of front, but non-copyable types
are a bit of a disaster with ranges anyway, since it's so trivial for them
to result in the range itself being non-copyable (at which point, it doesn't
even work with foreach), and it's very common for algorithms to assume that
a range's elements are copyable. It also risks having to have code test for
copyability rather than assuming that it's possible, which will add yet
another stray ability that range-based code will have to test for.
Personally, I don't think that supporting non-copyable types is worth it and
that isInputRange should just ban them, but obviously, some folks want
non-copyable types to be supported. However, isForwardRange does currently
ban them (though I don't know if it's on purpose on just a happy accident).
So, there's that.

- Jonathan M Davis





More information about the Digitalmars-d mailing list