chaining chain Result and underlying object of chain
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Sep 14 08:22:41 PDT 2015
On Monday 14 September 2015 17:01, Laeeth Isharc wrote:
> auto chain1 = chain("foo", "bar");
> chain1 = chain(chain1, "baz");
>
> Realized that in this case it was much simpler just to use the
> delegate version of toString and sink (which I had forgotten
> about). But I wondered what to do in other cases. It may be
> that the type of chain1 and chain2 don't mix.
Yes, the types don't match. The result types of most range functions depend
on the argument types.
Let's say chain("foo", "bar") has the type ChainResult!(string, string).
Then chain(chain("foo", "bar"), "baz") has the type ChainResult!
(ChainResult!(string, string), string). Those are different and not
compatible.
You can get the same type by:
a) being eager:
----
import std.array: array;
auto chain1 = chain("foo", "bar").array;
chain1 = chain(chain1, "baz").array;
----
(At that point you could of course just work with the strings directly,
using ~ and ~=.)
b) being classy:
----
import std.range.interfaces;
InputRange!dchar chain1 = inputRangeObject(chain("foo", "bar"));
chain1 = inputRangeObject(chain(chain1, "baz"));
----
Those have performance implications, of course. Being eager means allocating
the whole thing, and possibly intermediate results. Being classy means
allocating objects for the ranges (could possibly put them on the stack),
and it means indirections.
More information about the Digitalmars-d-learn
mailing list