std.v2020.algorithm etc[ WAS: Is run.d going to be expand for runtime and the phobos library?]
Steven Schveighoffer
schveiguy at gmail.com
Tue Jun 23 12:33:28 UTC 2020
On 6/22/20 11:12 PM, H. S. Teoh wrote:
> On Mon, Jun 22, 2020 at 10:54:08PM +0000, Jon Degenhardt via Digitalmars-d wrote:
>> On Monday, 22 June 2020 at 02:52:57 UTC, Andrei Alexandrescu wrote:
>>> On 6/21/20 10:47 AM, Andrei Alexandrescu wrote:
>>> One more thing before I forget - we should drop classes that are
>>> ranges. They add too much complication. The functionality would
>>> still be present by wrapping a polymorphic implementation in a
>>> struct.
>>
>> I have used class-based ranges quite a bit to implement ranges with
>> reference semantics. Classes are very convenient for this because the
>> implementation is structurally very similar to a struct based
>> implementation. Typically, replace 'struct' with 'final class' and
>> modify a helper function constructing the range to use 'new'. It's
>> amazingly easy.
> [...]
>
> Yeah, I rely on class ranges on occasion too, when runtime polymorphism
> is required. They *are* cumbersome to use, though, I'll give you that.
> If we're going to remove class-based ranges, then whatever replaces them
> better have good support for runtime polymorphism, otherwise it's not
> gonna fly.
>
> This may be more common than people think. For example, sometimes I have
> a range helper:
>
> auto myFunc(R)(R r, bool cond)
> {
> if (cond)
> return r.map!someFunc;
> else
> return r.filter!someFilter.map!someFunc;
> }
>
> There is no way to make this compile (cond is only known at runtime),
> because the return statements return diverse types, except to wrap it in
> an InputRangeObject.
You don't need polymorphism for that (necessarily), just function
pointers/delegates. I've also done this kind of stuff with iopipes using
tagged unions:
https://github.com/schveiguy/httpiopipe/blob/a04d87de3aa3836c07d181263c399416ba005e7c/source/iopipe/http.d#L245-L252
Such a thing is also generalized in phobos:
https://dlang.org/phobos/std_range.html#choose
And can probably be extended further (not sure why the args aren't lazy).
Your example rewritten:
auto myFunc(R)(R r, bool cond)
{
return choose(cond, r.map!someFunc, r.filter!someFilter.map!someFunc);
}
-Steve
More information about the Digitalmars-d
mailing list