Suliman
Suliman

Reputation: 1499

D: What difference between map and each?

std.algorithm have two function for iteration map and each. I can't understand what is the difference?

Upvotes: 4

Views: 204

Answers (3)

w0rp
w0rp

Reputation: 686

map takes a range and applies a function to every element in the range, and returns a range with the results. The range is lazily evaluated, so you wont compute any values unless you do something else with the range, like apply foreach to it.

each applies a function to every element in a range eagerly. So each is like a one-line foreach.

// Do some pointless application of map.
// The map won't be run here.
auto range = iota(0, 10).map!(x => cast(float) x);

// Now write all of them to stdout.
// This will be evaluated.
range.each!writeln;

Upvotes: 5

Adam D. Ruppe
Adam D. Ruppe

Reputation: 25595

map isn't for iteration, it is a transforming function. (Indeed, applying map to a range doesn't iterate over it at all; "evaluation is done lazily" in its docs mean you are still responsible for iterating over the result yourself.)

each is a variant of map that does do the iteration automatically, while transforming in the process. It also works on the opApply style of iteration, whereas map doesn't.

http://dlang.org/phobos/std_algorithm_iteration.html#.each

http://dlang.org/phobos/std_algorithm_iteration.html#.map

each is something you'd do at the end of a series of transformations, when you are ready to process the result and possibly save the changes back to the original range (each can save changes in-place, whereas map just returns the changes). map is an intermediate tool.

Upvotes: 6

lodo
lodo

Reputation: 2383

each performs an eager evaluation, while map performs a lazy one. This means that when you apply each, every element is calculated immediately, while map calculates its results only when you access them.

This also means that each is unsuitable for infinite streams.

Upvotes: 6

Related Questions