digitalmars.D.learn - compatible types for chains of different lengths
- Jon D (27/27) Nov 17 2015 I'd like to chain several ranges and operate on them. However, if
- Brad Anderson (15/22) Nov 17 2015 One solution:
- Jon D (16/18) Nov 17 2015 Thanks for the quick response. Extending your example, here's
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
Nov 17 2015
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? --JonOne 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; }
Nov 17 2015
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; }
Nov 17 2015