Using "reduce" with user types

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Feb 7 08:26:31 PST 2015


On Saturday, 7 February 2015 at 13:38:00 UTC, Kadir Erdem Demir 
wrote:
> How can I imagine what "map" does in my mind, because it 
> doesn't matches with the transform concept in my mind?

You can think of map as taking a range of something (in this 
case, an array of A), and calling a user-supplied function on 
each element in that range. The user-supplied function is a 
function that describes how to "map" each value in the range to a 
result. In your case, the function defines how to map from an A 
to its `count` member variable (it is a function of type A->int).

All "aArr.map!`a.count`" means is that for each A in aArr, return 
its `count` member. map!`a.count` is some syntax sugar D has to 
make function calls shorter; It expands to the following:

aArr.map!((A a) {
     return a.count;
})

The main difference between `map` in D and `transform` in C++ is, 
I believe, twofold. First off, `transform` is eager, meaning it 
does as much work as possible as son as possible. On the other 
hand, `map` does as little work as possible as late as possible. 
For the following code:

iota(10).map!(n => writeln(n)).take(5).array

Only "0 1 2 3 4" will be printed, as map is lazy and will not do 
work it doesn't have to.

Second of all, map returns a range that is the result of applying 
the supplied function to each element of aArr. C++'s tranform 
copies the result to another user-supplied range. If you wanted 
the equivalent of transform in C++, you could do this:

auto result = new int[](10);
iota(10).map!(n => n + 1).copy(result)

And result will be filled with the results of map.


More information about the Digitalmars-d-learn mailing list