www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - projections in D

reply "Ramon" <midiway midi.rs> writes:
what range/algorithm allows me to make projections from one 
sequence to another?


(http://msdn.microsoft.com/en-us/library/vstudio/bb548891%28v=vs.100%29.aspx)



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
}

So how would I make it in D? First yet, does D supports creating 
anonymous type for the projection? Or maybe I need to declare the 
class/struct that I want to be projected?
Nov 24 2014
parent reply "bearophile" <bearophileHUGS lycos.com> writes:
Ramon:



 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
Nov 24 2014
parent reply "Ramon" <midiway midi.rs> writes:
What is the difference between lazy and eager ranges?

(I guess, the lazy one has not yet queried the elements)
Nov 24 2014
parent "bearophile" <bearophileHUGS lycos.com> writes:
On Monday, 24 November 2014 at 15:44:02 UTC, Ramon wrote:
 What is the difference between lazy and eager ranges?

 (I guess, the lazy one has not yet queried the elements)
The lazy returns a range that once iterated gives the results one at a time (so the function allocates no heap memory). The eager version creates an array of the results in heap memory. Bye, bearophile
Nov 24 2014