Converting from DirIterator to string[] without a loop

Dave Chapman via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jan 13 16:29:05 PST 2017


I would like to do something like the code shown below but I 
can't figure out how to do
it without loops inside the if statement.
When I use auto and print out the type of b it is  something like
args.main.FilterResult!(__lambda2, DirIterator).FilterResult and 
for the "if" version of
b and args.main.FilterResult!(__lambda3, 
DirIterator).FilterResult for the "else" version
so they are really different types. I have tried making b an 
array of DirEntry and an
array of strings but that doesn't compile. Both expressions for b 
compile and run.

I can put a foreach loop inside the if statement and convert b to 
an array of strings but that
seems clumsy and not idiomatic D. Is there a way to do this 
without the conversion loop
inside both branches of the if - else stament? Is there a way to 
use to!string or cast?

// Is it possible to make this work?
theResultType b;

if (some_contition) {
   b = dirEntries("directory", SpanMode.shallow).filter!(f => 
(f.name == "file_name.txt") );
} else {
   b = dirEntries("directory", SpanMode.shallow).filter!(f => 
(f.name.endsWith(".d") )'
}

foreach(file; b) {
    do some stuff
}


// This works but seems clumsy and not idiomatic D
string[] c = "";

if (some_contition) {
   auto b = dirEntries("directory", SpanMode.shallow).filter!(f => 
(f.name == "file_name.txt") );
   foreach (file; b) {
     c = c ~ file;
   }
} else {
   auto b = dirEntries("directory", SpanMode.shallow).filter!(f => 
(f.name.endsWith(".d") )'
     foreach (file; a) {
       c = c ~ file;
     }
}

foreach(file; c) {
    do some stuff
}



More information about the Digitalmars-d-learn mailing list