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

Reply via email to