Any guide to stream (string) processing in D? | Re: Any python-like generator patterns in D?

bearophile bearophileHUGS at lycos.com
Thu Feb 21 08:52:10 PST 2013


Samuel Lampa:

> python has an even more compact syntax for creating generator 
> objects:

D doesn't have a generator syntax, but it's easy to do what you 
want using UFCS in D.


> gen_lines = (line.rstrip("\n") for line in open("infile.txt"))
> gen_uppercase_lines = (line.upper() for line in gen_lines)
> gen_final_lines = ("Line: " + line for line in gen_lines)
>
> # Drive the pipeline, one line at a time
> for line in gen_final_lines:
>     print line

==>

import std.stdio, std.algorithm, std.string;

void main() {
     auto gen = File("infile.txt")
                .byLine()
                .map!chomp
                .map!toUpper
                .map!(line => "Line: " ~ line);

     writefln("%-(%s\n%)", gen);
}


Bye,
bearophile


More information about the Digitalmars-d-learn mailing list