As many thanks As possible to who crates D and UFCS feature

cym13 via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 12 04:41:57 PDT 2017


On Friday, 12 May 2017 at 11:10:01 UTC, k-five wrote:
> I was waiting for a stable version of C++17 ( standard library 
> ) to add some features of fileSystem in C++17 to my program 
> that wants to iterate through all files in a directory 
> recursively.
>
> I was thinking how could I do for implementing that and add it 
> to my program.
>
> Now after starting to learn D ( nearby 2 weeks so far ). I can 
> do it in 6 lines!
>
> void main( string[] args ){
> 	
> 	string[] all_file_name =  dirEntries( ".", SpanMode.depth, 
> false )
>          .filter!( file => !file.name.matchFirst( regex( args[ 
> 1 ] ) ).empty() )
>          .filter!( file => ( args[ 2 ] == "-f" || args[ 2 ] == 
> "-d"  ? ( args[ 2 ] == "-f" ? !file.isDir : !file.isFile ) : ( 
> !file.isSymlink ) ) )
> 	 .map!( file => file.name )
> 	 .array;
> 	foreach( string item; all_file_name ) writeln( item );
> 	
> }
>
> ./bin-file '[A-Z]$' -f   ---> print all files that are matched 
> against [A-Z]$
>
> ./bin-file '[A-Z]$' -d   ---> print all directory that are 
> matched against [A-Z]$
>
> ./bin-file '[A-Z]$' "anything-else"  ---> print both files and 
> directory that are matched against [A-Z]$
>
> I am so happy since after more than one year practicing in C++ 
> and putting a collection more than 2000 examples of C++ on my 
> github, I was not sure I could do it in 6 lines.
>
> May it is a Spam but I think it is worth it.

Shorter:

void main( string[] args ){
	dirEntries( ".", SpanMode.depth, false )
          .filter!( file => !file.name.matchFirst( regex( args[ 1 
] ) ).empty() )
          .filter!( file => ( args[ 2 ] == "-f" || args[ 2 ] == 
"-d"  ? ( args[ 2 ] == "-f" ? !file.isDir : !file.isFile ) : ( 
!file.isSymlink ) ) )
	 .map!( file => file.name )
	 .each!(string item => writeln( item ));
}

It's more memory efficient too because at no point the actual 
list is stored.


More information about the Digitalmars-d-learn mailing list