Combining vectorization and recursion in R?

I am trying to combine vectorization and recursion in this implementation of a factor function:

fac <- function(n) {
  ifelse(n == 1, 1, n * fac(n-1))
}

fac(6)      #720
fac(c(6,7)) #Error: evaluation nested too deeply: infinite recursion / options(expressions=)?
            #Error during wrapup: evaluation nested too deeply: infinite recursion / options(expressions=)?

Although ifelse is a vectorized version if this does not work (see errors).

My question is
1. Why does this not work?
2. How can I make it work?

Edit: I do not see a connection with the proposed duplicate, because the above function does not even work for a vector of two!

+4
source share
2 answers

Let's see what happens:

fac <- function(n) {
  ifelse(n == 1, 1, {message(paste(n-1, collapse = ",")); 
                     stopifnot(n > 0); n * fac(n-1)})
}

fac(4:5)
#3,4
#2,3
#1,2
#0,1
#-1,0
# Show Traceback
# 
# Rerun with Debug
# Error: n > 0 are not all TRUE 

As you can see, the condition is never TRUEfor all elements n, and therefore recursion never stops.

If all of the elements nare equal, it works:

fac(c(5,5))
#4,4
#3,3
#2,2
#1,1
#[1] 120 120

n:

fac <- function(n) {
  ifelse(n <= 1, 1, n * fac(n-1))
}
fac(1:5)
#[1]   1   2   6  24 120
+7

Vectorize

vfac <- Vectorize(fac)
vfac(c(6,7)) 
# [1]  720 5040
+3

Source: https://habr.com/ru/post/1588984/


All Articles