A first lambda function with C++11 and Rcpp

January 10, 2013
By

(This article was first published on Rcpp Gallery, and kindly contributed to R-bloggers)

Yesterday’s post started to explore the nice additions which the new C++11 standard is bringing to the language. One particularly interesting feature are lambda functions which resemble the anonymous functions R programmers have enjoyed all along. This shows a simple example.

First, we again make sure the compiler knows that we want C++11:

Sys.setenv("PKG_CXXFLAGS"="-std=c++11")

We will revisit an earlier example on stl::transform but use a lamba function

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
std::vector<double> transformEx(const std::vector<double>& x) {
    std::vector<double> y(x.size());
    std::transform(x.begin(), x.end(), y.begin(), 
                   [](double x) { return x*x; } );
    return y;
}

In this example, the function being swept over all elements of x does not have to be declared as a separate function as we did here but can be defined inline as we would in R. The return type is deduced automatically, similar to the use auto auto in the previous C++11 example. We can run the example:

x <- c(1,2,3,4)
transformEx(x)
[1]  1  4  9 16

Unsurprisingly, the result is the same. We can also retake the second example from the previous post:

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector transformEx2(NumericVector x, NumericVector y) {
    NumericVector z(x.size());
    std::transform(x.begin(), x.end(), y.begin(), z.begin(), 
                   [](double x, double y) { return sqrt(x*x + y*y); } );
    return z;
}

It also matches the previous result.

x <- c(1,2,3,4)
y <- c(2,2,3,3)
transformEx2(x,y)
[1] 2.236 2.828 4.243 5.000

Once again, we need to remind the reader that this still requires setting the -std=c++11 option for g++, and that CRAN will not allow this in uploads, at least not yet. In the meantime, C++11 can of course be used for non-CRAN projects.

To leave a comment for the author, please follow the link and comment on his blog: Rcpp Gallery.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.