Bug 4468 – std.string.join() for lazy iterable of strings

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2010-07-15T17:24:00Z
Last change time
2011-12-21T10:33:37Z
Assigned to
andrei
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2010-07-15T17:24:25Z
This Python code generates a lazy sequence of the first 20 integers (starting from 0), then maps them lazily to strings, and then joins them in a single string: from itertools import imap r = imap(str, xrange(20)) result = "".join(r) print result The same code can be written in D2: import std.stdio, std.algorithm, std.conv, std.range, std.string; void main() { auto r = map!("to!string(a)")(iota(20)); //string result = join(array(r), ""); // OK string result = join(r, ""); // error writeln(result); } But I'd like a std.string.join() able to accept a Range too, so I can use join(r, "") instead of join(array(r), ""), because it's shorter, simpler, natural enough and reduces memory used (and probably increases code performance too). When the total size of the resulting string is not known because the input is a lazy sequence of strings, then probably join() has to use something like appender() to improve its performance.
Comment #1 by bearophile_hugs — 2011-02-07T14:33:28Z
See also bug 5542
Comment #2 by bearophile_hugs — 2011-07-30T06:54:17Z
This is a very common need. Another example: import std.range; void main() { auto aa = [1:["hello", "red"], 2:["blue", "yellow"]]; auto r1 = join(aa.values); // OK auto r2 = join(aa.byValue()); // error }
Comment #3 by bearophile_hugs — 2011-12-21T10:33:37Z
Now in DMD 2.057 this works: import std.stdio, std.algorithm, std.conv, std.range, std.string; void main() { auto r = map!("to!string(a)")(iota(20)); //string result = join(array(r), ""); // OK string result = join(r, ""); // error writeln(result); } This line: auto r = map!("to!string(a)")(iota(20)); is also better written: auto r = map!text(iota(20)); But this doesn't work still: import std.range; void main() { auto aa = [1:["hello", "red"], 2:["blue", "yellow"]]; auto r2 = join(aa.byValue()); // error } To make this work there are two solutions: 1) Change byValue() to return a Range. 2) Change join() to accept an opApply too. The first solution allows to use byValue in many other cases, so I think join() is OK, and I close this bug report.