Thread overview | |||||
---|---|---|---|---|---|
|
November 17, 2015 compatible types for chains of different lengths | ||||
---|---|---|---|---|
| ||||
I'd like to chain several ranges and operate on them. However, if the chains are different lengths, the data type is different. This makes it hard to use in a general way. There is likely an alternate way to do this that I'm missing. A short example: $ cat chain.d import std.stdio; import std.range; import std.algorithm; void main(string[] args) { auto x1 = ["abc", "def", "ghi"]; auto x2 = ["jkl", "mno", "pqr"]; auto x3 = ["stu", "vwx", "yz"]; auto chain1 = (args.length > 1) ? chain(x1, x2) : chain(x1); auto chain2 = (args.length > 1) ? chain(x1, x2, x3) : chain(x1, x2); chain1.joiner(", ").writeln; chain2.joiner(", ").writeln; } $ dmd chain.d chain.d(10): Error: incompatible types for ((chain(x1, x2)) : (chain(x1))): 'Result' and 'string[]' chain.d(11): Error: incompatible types for ((chain(x1, x2, x3)) : (chain(x1, x2))): 'Result' and 'Result' Is there a different way to do this? --Jon |
November 17, 2015 Re: compatible types for chains of different lengths | ||||
---|---|---|---|---|
| ||||
Posted in reply to Jon D | On Tuesday, 17 November 2015 at 22:47:17 UTC, Jon D wrote:
> I'd like to chain several ranges and operate on them. However, if the chains are different lengths, the data type is different. This makes it hard to use in a general way. There is likely an alternate way to do this that I'm missing.
>
> [snip]
>
> Is there a different way to do this?
>
> --Jon
One solution:
import std.stdio;
import std.range;
import std.algorithm;
void main(string[] args)
{
auto x1 = ["abc", "def", "ghi"];
auto x2 = ["jkl", "mno", "pqr"];
auto x3 = ["stu", "vwx", "yz"];
auto chain1 = chain(x1, (args.length > 1) ? x2 : []);
auto chain2 = chain(x1, x2, (args.length > 1) ? x3 : []);
chain1.joiner(", ").writeln;
chain2.joiner(", ").writeln;
}
|
November 18, 2015 Re: compatible types for chains of different lengths | ||||
---|---|---|---|---|
| ||||
Posted in reply to Brad Anderson | On Tuesday, 17 November 2015 at 23:22:58 UTC, Brad Anderson wrote:
>
> One solution:
>
> [snip]
>
Thanks for the quick response. Extending your example, here's another style that works and may be nicer in some cases.
import std.stdio;
import std.range;
import std.algorithm;
void main(string[] args)
{
auto x1 = ["abc", "def", "ghi"];
auto x2 = ["jkl", "mno", "pqr"];
auto x3 = ["stu", "vwx", "yz"];
auto y1 = (args.length > 1) ? x1 : [];
auto y2 = (args.length > 2) ? x2 : [];
auto y3 = (args.length > 3) ? x3 : [];
chain(y1, y2, y3).joiner(", ").writeln;
}
|
Copyright © 1999-2021 by the D Language Foundation