taskPool.map() and taskPool.amap()

In this lesson, you will learn the use of map() and amap() functions.

We'll cover the following

taskPool.map()

It helps to explain map() from the std.algorithm module before explaining taskPool.map(). std.algorithm.map is an algorithm commonly found in many functional languages. It calls a function with the elements of a range one-by-one and returns a range that consists of the results of calling that function with each element. It is a lazy algorithm, meaning it calls the function as needed. (There is also std.algorithm.each, which is for generating side effects for each element, as opposed to producing a result from it.)

The fact that std.algorithm.map operates lazily is very powerful in many programs. However, if the function needs to be called with every element anyway and the operations on each element are independent from each other, laziness may be slower than parallel execution. taskPool.map() and taskPool.amap() from the std.parallelism module take advantage of multiple cores and run faster in many cases. Let’s compare these three algorithms using the Student example. Let’s assume that Student has a member function that returns the average grade of the student. To demonstrate how parallel algorithms are faster, let’s again slow this function down with Thread.sleep().

std.algorithm.map takes the function as its template parameter, and the range as its function parameter. It returns a range that consists of the results of applying that function to the elements of the range:

auto result_range = map!func(range);

The function may be specified by the => syntax as a lambda expression as we have seen in earlier chapters. The following program uses map() to call the averageGrade() member function on each element:

Get hands-on with 1200+ tech skills courses.