How to Pipeline the Functions in C++?


As part of a data processing pipeline, complete the implementation of the makePipeline method:

The method should accept a vector of functions, and it should return a new function that accepts one parameter arg.
The returned function should call the first function in the makePipeline with the parameter arg, and call the second function with the result of the first function.
The returned function should continue calling each function in the makePipeline in order, following the same pattern, and return the value from the last function.

Write a C++ method/function e.g. makePipeLine that takes an array (vector) of functions and it should return a new function that accepts only 1 parameter (generic data type via template) and returns a value of a same type.

The makePipeLine will apply the parameter sequentially (pipeline the function calls) to the list of functions for example:

1
2
3
4
5
std::vector<std::function<int (int)>> functions;
functions.push_back([] (int x) -> int { return x * 2; });
functions.push_back([] (int x) -> int { return x - 1; });
functions.push_back([] (int x) -> int { return x + 2; });
std::function<int (int)> func = makePipeline(functions);
std::vector<std::function<int (int)>> functions;
functions.push_back([] (int x) -> int { return x * 2; });
functions.push_back([] (int x) -> int { return x - 1; });
functions.push_back([] (int x) -> int { return x + 2; });
std::function<int (int)> func = makePipeline(functions);

If we call func(1) the result is 1*2-1+2=3. The function makePipeline is implemented as follows where it returns a function that takes argument args which is of generic type const T& and it returns the same type T.

The funs (vector of std::function) should be captured by [&funcs] so it can be used inside the local/anonymous function in C++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <functional>
#include <vector>
 
template<class T>
std::function<T (T)> makePipeline(const std::vector<std::function<T (T)>>& funcs) {
    return [&funcs] (const T& arg) {
        T v = arg; // initial value
        for (const auto &f: funcs) {
            v = f(v); // sequentially apply a function.
        }
        return v;
    };
}
#include <iostream>
#include <functional>
#include <vector>

template<class T>
std::function<T (T)> makePipeline(const std::vector<std::function<T (T)>>& funcs) {
    return [&funcs] (const T& arg) {
        T v = arg; // initial value
        for (const auto &f: funcs) {
            v = f(v); // sequentially apply a function.
        }
        return v;
    };
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
412 words
Last Post: Count Numbers Less Than in a Sorted Vector using Binary Search (C++)
Next Post: How to Reverse Only Letters in a String?

The Permanent URL is: How to Pipeline the Functions in C++?

Leave a Reply