map

auto map(Range)(Range r) if (isInputRange!(Unqual!Range));

Implements the homonym function (also known as transform) present in many languages of functional flavor. The call map!(fun)(range) returns a range of which elements are obtained by applying fun(a) left to right for all elements a in range. The original ranges are not changed. Evaluation is done lazily.

template map(fun...)
map
(
Range
)
(
Range r
)
if (
isInputRange!(Unqual!Range)
)
if (
fun.length >= 1
)

Parameters

fun

one or more transformation functions

r

Return Value

a range with each fun applied to all the elements. If there is more than one fun, the element type will be Tuple containing one element for each fun.

Examples

1 import std.algorithm.comparison : equal;
2 import std.range : chain;
3 int[] arr1 = [ 1, 2, 3, 4 ];
4 int[] arr2 = [ 5, 6 ];
5 auto squares = map!(a => a * a)(chain(arr1, arr2));
6 assert(equal(squares, [ 1, 4, 9, 16, 25, 36 ]));

Multiple functions can be passed to map. In that case, the element type of map is a tuple containing one element for each function.

1 auto sums = [2, 4, 6, 8];
2 auto products = [1, 4, 9, 16];
3 
4 size_t i = 0;
5 foreach (result; [ 1, 2, 3, 4 ].map!("a + a", "a * a"))
6 {
7     assert(result[0] == sums[i]);
8     assert(result[1] == products[i]);
9     ++i;
10 }

You may alias map with some function(s) to a symbol and use it separately:

1 import std.algorithm.comparison : equal;
2 import std.conv : to;
3 
4 alias stringize = map!(to!string);
5 assert(equal(stringize([ 1, 2, 3, 4 ]), [ "1", "2", "3", "4" ]));

See Also

Meta