Import content from file names defined in an array

I can merge the files read importat compile time as follows:

enum string a = import("a.txt");
enum string b = import("b.txt");
enum string result = a ~ b;

How can I get concatenated resultif I have file names in an array?

enum files = ["a.txt", "b.txt"];
string result;
foreach (f; files) {
  result ~= import(f);
}

This code returns with an error Error: variable f cannot be read at compile time.

The functional approach does not work either:

enum files = ["a.txt", "b.txt"];
enum result = reduce!((a, b) => a ~ import(b))("", files);

It returns with the same error: Error: variable b cannot be read at compile time

+4
source share
3 answers

I found a solution that does not use string mixins:

string getit(string[] a)() if (a.length > 0) {
    return import(a[0]) ~ getit!(a[1..$]);
}

string getit(string[] a)() if (a.length == 0) {
    return "";
}

enum files = ["a.txt", "b.txt"];
enum result = getit!files;
+3
source

Maybe using string mixins?

enum files  = ["test1", "test2", "test3"];

// There may be a better trick than passing the variable name here
string importer(string[] files, string bufferName) {
    string result = "static immutable " ~ bufferName ~ " = ";

    foreach (file ; files[0..$-1])
        result ~= "import(\"" ~ file ~ "\") ~ ";
    result ~= "import(\"" ~ files[$-1] ~ "\");";

    return result;
}

pragma(msg, importer(files, "result"));
// static immutable result = import("test1") ~ import("test2") ~ import("test3");

mixin(importer(files, "result"));
pragma(msg, result)
+5
source

@Tamas .

, static if, , , .

string getit(string[] a)() {
    static if (a.length > 0) {
        return import(a[0]) ~ getit!(a[1..$]);
    }
    else {
        return "";
    }
}

static if (a.length > 0)

static if (a.length)

,

string getit(string[] a)() {
    static if (a && a.length) {
        return import(a[0]) ~ getit!(a[1..$]);
    }
    else {
        return "";
    }
}

.

enum files = ["a.txt", "b.txt"];
enum result = getit!files;
+3

Source: https://habr.com/ru/post/1610394/


All Articles