Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: how to do "map" of Scheme

Below is a sample code of Scheme (correct me if i'm wrong):

(define (translate points delta)
    (map 
        (lambda (x)
            (+ x delta)
        )
        points 
    )
)

basically it defines a lambda function that add delta to input x, then apply it to each item of points.

I found such feature quite interesting that it omits all the iterators and etc.

Is it possible to do such "map" in C++, in an elegant way?

Update according to the reply:

To be more specific, is there a way to implement such "map" function of Scheme, in C++, so that it could be used elegantly? Maybe a template function named "map" that accept function pointer / functor, and a container?

like image 224
athos Avatar asked Mar 18 '23 12:03

athos


2 Answers

The closest translation of your code in idiomatic C++ would be using std::transform with a std::back_inserter:

std::vector<point> points{…};
std::vector<point> output;
// optional, may improve performance:
output.reserve(points.size());

auto lambda = [=](point x) { return x + delta; };
std::transform(begin(points), end(points), std::back_inserter(output), lambda);

Here, lambda captures its surrounding scope by value – this is indicated by the [=] prefix. This makes it possible to use delta inside it.

However, for T -> T transformations you would usually use an in-place variant instead of pushing values into a new container:

std::vector<point> points{…};

auto lambda = [=](point x) { return x + delta; };
std::transform(begin(points), end(points), begin(points), lambda);
like image 149
Konrad Rudolph Avatar answered Mar 31 '23 04:03

Konrad Rudolph


The C++ version is called std::transform.

like image 30
n. m. Avatar answered Mar 31 '23 06:03

n. m.