functional Rcpp implementation