[R] strange output of cat function used in recursive function
Jan Kacaba
jan.kacaba at gmail.com
Sat Oct 1 17:44:50 CEST 2016
Hello Dear R-help
I tried to understand how recursive programming works in R. Bellow is
simple recursive function.
binary1 <- function(n) {
if(n > 1) {
binary(as.integer(n/2))
}
cat(n %% 2)
}
When I call binary1(10) I get 1010. I believe that cat function stores
value to a buffer appending values as recursion proceeds and at the
end it prints the buffer. Am I right?
I tried to modify the function to get some understanding:
binary2 <- function(n) {
if(n > 1) {
binary2(as.integer(n/2))
}
cat(n %% 2, sep=",")
}
With call binary2(10) I get also 1010. Why the output is not separated
by commas?
If I use in binary2 function cat(n %% 2, ",") on last line, the output
is separated. Outside recursive function the cat function prints
separated output in both cases e.g. cat(c(1:10), sep=",") and
cat(c(1:10), ",")
Derek
More information about the R-help
mailing list