D: What is the difference between a card and each?

std.algorithm have two functions for iterating mapand each. I can not understand what is the difference?

+4
source share
3 answers

eachperforms a pending assessment, and mapperforms a lazy one. This means that when you apply each, each element is calculated immediately, and only mapcalculates its results when accessing them.

It also means eachunsuitable for endless streams.

+6
source

map , . (, , " " , - .)

each - map, , - . opApply , map .

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

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

each - , , , , (each , map ). map .

+6

maptakes a range and applies a function to each element in the range and returns a range with the results. A range is lazily evaluated, so you will not calculate any values ​​unless you do something else with the range, for example, apply to it foreach.

eachapplies the function to each element in the range with impatience. Therefore, it eachis single 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;
+4
source

All Articles