How can I define a sequence of recursive functions?

Viewed 42

I tried to define the following function but failed. Any suggestions will be welcome.

H = list()
H[[1]] = function(x) 1
for(i in 2:4) H[[i]] = function(x) H[[i-1]](x)*x+1

> H
[[1]]
function (x) 
1
[[2]]
function (x) 
H[[i - 1]](x) * x + 1
[[3]]
function (x) 
H[[i - 1]](x) * x + 1
[[4]]
function (x) 
H[[i - 1]](x) * x + 1

> H[[1]](1)
 1  
> H[[2]](1)
 Too Deep Nesting
1 Answers

Instead of defining a set of functions recursively, define a single recursive function:

H <- function(x, n) {
  if (n == 1) 1 else H(x, n-1) * x + 1
} 

Then, H(x, n) returns the same as your H[[n]](x).

For completeness sake: your approach with the for loop does not work because each function depends on the specific value which was assigned to i at the moment the function was generated. At the end of the loop i is set to 4. When you call H[[2]](10) R tries to compute H[[i-1]](10) * 10 + 1 = H[[3]](10) * 3 + 1 = ... which end in an infinite recursion. Simply put, R does not remember that at the moment H[[2]] was defined i was equal to 2.

Related