I\'m currently learning to call compiled C code in R. Yesterday I created a function for the infinite pi series that when run in R returns a length 1 numeric vector (pi), w
You could load Rcpp just to get access to its Rcpp Attributes functionality. It permits you to write this as (expanded to two lines for display; it really fits on one line):
R> cppFunction('double fib(double n) { if (n<2) return(n);
+ else return fib(n-1) + fib(n-2);}')
R> fib(10)
[1] 55
R>
If you run cppFunction(..., verbose=TRUE)
you get to see the file it creates.
In general, avoid the .C()
interface and concentrate in .Call()
. This is the very clear recommendation in the NEWS file of the most recent R release:
* .C(DUP = FALSE) and .Fortran(DUP = FALSE) are now deprecated, and may be disabled in future versions of R. As their help has long said, .Call() is much preferred.
Let's stress the .Call()
is much preferred one more time. See eg Hadley's Advanced R Programming draft for more on getting going with .Call()
. His advice too is to straight to Rcpp.
fibonacci
is declared to take two pointers as arguments, and it doesn't return anything. But in your else
block, you're trying to call it with a single integer argument and capture a return value from it.
Try something like this in your else
block:
int n1 = *n - 1;
int n2 = *n - 2;
int ans1;
int ans2;
fibonacci(&n1, &ans1);
fobonacci(&n2, &ans2);
*ans = ans1 + ans2;
Also, in your else if
block, that should be (*n == 0)
.
You already know the errors in the following line.
*ans = fibonacci(n - 2) + fibonacci(n - 1); # tried 'ans' in args here,
I think, you should write a helper function that does all the work, simplifying both in the process.
int fibonacci_helper(n)
{
if(n == 1 || n == 2){
return 1;
} else if(n == 0){
return 0;
} else {
return fibonacci_helper(n-1) + fibonacci_helper(n-2);
}
}
void fibonacci(int *n, int *ans)
{
*ans = fibonacci_helper(*n);
}