Thread overview
Chainable template mixin and opCat()
Jun 01, 2015
Per Nordlöw
Jun 01, 2015
Per Nordlöw
Jun 01, 2015
w0rp
Jun 01, 2015
Per Nordlöw
Jun 01, 2015
Per Nordlöw
Jun 01, 2015
Timon Gehr
June 01, 2015
I just stumbled upon the following very interested idea:

http://forum.dlang.org/thread/bug-6043-3@http.d.puremagic.com%2Fissues%2F

1. Add the following (where?)

template Chainable() {
       Chain!(typeof(this), Range) opCat(Range)(Range r) {
           return chain(this, r);
       }
}

2. Then in the body of a lazy range both Phobos ones like map, filter, zip, iota, and so on, and user-defined ones, you may add:

mixin Chainable;

This allows to write more natural and readable code like:

    iota(5) ~ filter!q{a}([1,0,3])
    map!abs([1,2,-5]) ~ [10, 20]

instead of more noisy:

    chain(iota(5), filter!q{a}([1,0,3]))
    chain(map!abs([1,2,-5]), [10, 20])

See also bug 5638 for a useful optimization.

I'd be glad to work on Phobos PR for this :)
June 01, 2015
On Monday, 1 June 2015 at 11:20:52 UTC, Per Nordlöw wrote:
> template Chainable() {
>        Chain!(typeof(this), Range) opCat(Range)(Range r) {
>            return chain(this, r);
>        }
> }

Would it suffice to restrict `opCat` as

    Chain!(typeof(this), Range) opCat(Range)(Range r)
    if (isInputRange!Range && is(CommonElementType!(typeof(this), Range)))

?

given that

template CommonElementType(Rs...)
{
    alias CommonElementType = CommonType!(staticMap!(ElementType, Rs));
}

In general, should we let `Chain` do the error checking or should we copy its retrictions into `opCat`s restrictions?
June 01, 2015
I think my only complaint for this is that it wouldn't work for all ranges, so you'd be able to use the operator some times, but not others. This is because you have to define the operators inside of the structs or classes, and you can't write operators as free functions. (Which is a good feature in general.)
June 01, 2015
On Monday, 1 June 2015 at 11:47:43 UTC, w0rp wrote:
> I think my only complaint for this is that it wouldn't work for all ranges, so you'd be able to use the operator some times,

I still think the simplicity of

    mixin Chainable;

and it's effect on usability is short enough to be worth the effort :)
June 01, 2015
On Monday, 1 June 2015 at 12:13:51 UTC, Per Nordlöw wrote:
> I still think the simplicity of
>
>     mixin Chainable;
>
> and it's effect on usability is short enough to be worth the effort :)

https://github.com/D-Programming-Language/phobos/pull/3353

Destroy!
June 01, 2015
On 06/01/2015 01:47 PM, w0rp wrote:
> you can't write operators as free functions. (Which is a good feature in
> general.)

No, it is a pointless non-uniformity in function call syntax.