Exported and unexported functions
Functions that are decorated with the [[Rcpp::export]] special comment are made available to the R console. However, you typically don't want to export every function to R. Instead, some functions can be kept internal to C++. These are often lower-level calculation functions or utility functions.
Recall the function that calculates distance from a point in the 2d space to the origin:
double dist( double x, double y) {
return sqrt( x*x + y*y ) ;
}
Here, you'll update the code so that the dist function (that is exported) calls an unexported square function that just squares a double.
Diese Übung ist Teil des Kurses
Optimizing R Code with Rcpp
Anleitung zur Übung
- Complete the definition of
square()so that it accepts and returns adouble, … - that is equal to
xtimesx. - Update the definition of
dist()to usesquare(). That is, to return the square root of the sum of square ofxand the square ofy.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
#include
using namespace Rcpp;
// Make square() accept and return a double
___ square(___ x) {
// Return x times x
return ___ ;
}
// [[Rcpp::export]]
double dist(double x, double y) {
// Change this to use square()
return sqrt(___ + ___);
}