Thread overview | ||||||
---|---|---|---|---|---|---|
|
November 24, 2014 projections in D | ||||
---|---|---|---|---|
| ||||
what range/algorithm allows me to make projections from one sequence to another? that is, in C#, this is the Select method (http://msdn.microsoft.com/en-us/library/vstudio/bb548891%28v=vs.100%29.aspx) 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 } 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? |
November 24, 2014 Re: projections in D | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ramon | 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
|
November 24, 2014 Re: projections in D | ||||
---|---|---|---|---|
| ||||
Posted in reply to bearophile | What is the difference between lazy and eager ranges? (I guess, the lazy one has not yet queried the elements) |
November 24, 2014 Re: projections in D | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ramon | 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
|
Copyright © 1999-2021 by the D Language Foundation