Output range of ranges to single buffer

Jacob Carlborg via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 13 13:15:03 PST 2016


Is it possible to somehow output a range of ranges to a single string 
buffer? For example, converting an array of integers to a string with 
the same representation as the source code.

import std.algorithm;
import std.conv;
import std.string;

void main()
{
     auto a = [1, 2, 3, 4, 5];
     auto b = '[' ~ a.map!(e => e.to!string).join(", ") ~ ']';
     assert(b == "[1, 2, 3, 4, 5]");
}

The above code is straight forward. But I would like to avoid creating 
the intermediate strings, "e.to!string", and instead put the converted 
integer and the result of join directly in the same buffer.

A bit more complex example:

struct Foo
{
     int a;
     string b;
     int c;

     string toString()
     {
         auto values = [a.to!string, b, c.to!string].join(", ");
         return "Foo(" ~ values ~ ')';
     }
}

void main()
{
     auto a = [
         Foo(1, "foo", 2),
         Foo(3, "bar", 4)
     ];

     auto b = '[' ~ a.map!(e => e.to!string).join(", ") ~ ']';
     assert(b == "[Foo(1, foo, 2), Foo(3, bar, 4)]");
}

-- 
/Jacob Carlborg


More information about the Digitalmars-d-learn mailing list