projections in D

bearophile via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 24 06:09:44 PST 2014


Ramon:

> example in C#:
>
> class ProjectionWanted
> {
>   public int field1 { get; set; }
>   public int field2 { get; set; }
>   public int field3 { get; set; }
> }
>
> void Foo(List<ProjectionWanted> list)
> {
>   var list_projected = list.Select(l => new { l.field1, 
> l.field2 });
>   // list_projected elements now contain only field1 and field2
> }

Here I have defined ProjectionWanted as a struct.

//--------------
import std.stdio, std.algorithm, std.typecons;

struct ProjectionWanted {
     public int a, b, c;
}

auto foo(ProjectionWanted[] seq) pure nothrow @safe @nogc {
     return seq.map!(p => tuple(p.a, p.b));
}

void main() {
     [ProjectionWanted(1, 2, 3), ProjectionWanted(4, 5, 6)]
     .foo
     .writeln;
}
//--------------

Note that foo() returns a lazy range. If you need an eager one 
you can append an ".array":

     return seq.map!(p => tuple(p.a, p.b)).array;

And you have to import std.array too.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list