Import content from filenames defined in an array

90 Views Asked by At

I can concatenate files read by import during compile time like this:

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

How can I get the concatenated result if I have the filenames 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.

Functional approach doesn't seem to 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

3

There are 3 best solutions below

1
On BEST ANSWER

I have found a solution that doesn't 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;
0
On

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)
0
On

@Tamas answer.

It could technically be wrapped into one function using static if which in my opinion looks cleaner.

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

Also technically

static if (a.length > 0)

could be

static if (a.length)

You could also account for uninitialized arrays like this

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

Usage would still be the same.

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