-
-
Notifications
You must be signed in to change notification settings - Fork 219
Closed
Description
A thought about how we could give the end user some more flexibility with respect to sugar (and additionally reimplement sugar with the more flexible functions). This is a proposal for an addition and not for changing any existing functionality. It goes something like this...If we add an include file that looks something like this:
namespace Rcpp
{
namespace algorithm
{
template< typename InputIterator >
typename std::iterator_traits< InputIterator >::value_type sum(InputIterator begin, InputIterator end)
{
typename std::iterator_traits< InputIterator >::value_type start = *begin++;
while (begin != end)
{
start += *begin++;
}
return start;
}
template< typename InputIterator >
typename std::iterator_traits< InputIterator >::value_type prod(InputIterator begin, InputIterator end)
{
typename std::iterator_traits< InputIterator >::value_type start = *begin++;
while (begin != end)
{
start *= *begin++;
}
return start;
}
template< typename InputIterator, typename OutputIterator >
void log(InputIterator begin, InputIterator end, OutputIterator out)
{
while (begin != end)
{
*out = std::log(*begin++);
++out;
}
}
}
}
Then we can write functions that look like this:
#include <Rcpp.h>
// [[Rcpp::export]]
double mySum(Rcpp::NumericVector v, int begin, int end)
{
return Rcpp::algorithm::sum(v.begin() + (begin - 1), v.begin() + end);
}
// [[Rcpp::export]]
double myProd(Rcpp::NumericVector v, int begin, int end)
{
return Rcpp::algorithm::prod(v.begin() + (begin - 1), v.begin() + end);
}
// [[Rcpp::export]]
Rcpp::NumericVector myLog(Rcpp::NumericVector v)
{
Rcpp::NumericVector x = Rcpp::clone(v);
Rcpp::algorithm::log(v.begin(), v.end(), x.begin());
return x;
}
Which produce output like this:
> library(Rcpp)
> sourceCpp("test.cpp")
> mySum(1:4, 1, 3)
[1] 6
> myProd(1:4, 2, 4)
[1] 24
> myLog(1:4)
[1] 0.0000000 0.6931472 1.0986123 1.3862944
>
Currently, most sugar functions only work on stuff that IS a Rcpp::Vector
. This excludes, for instance, Rcpp::Matrix::Row
. Creating range based algorithms would simply give more flexibility to the end user without removing any of the current functionality.
Metadata
Metadata
Assignees
Labels
No labels