Re: projections in D

2014-11-24 Thread bearophile via Digitalmars-d-learn

Ramon:


example in C#:

class ProjectionWanted
{
  public int field1 { get; set; }
  public int field2 { get; set; }
  public int field3 { get; set; }
}

void Foo(ListProjectionWanted 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


Re: projections in D

2014-11-24 Thread Ramon via Digitalmars-d-learn

What is the difference between lazy and eager ranges?

(I guess, the lazy one has not yet queried the elements)


Re: projections in D

2014-11-24 Thread bearophile via Digitalmars-d-learn

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