[R] expression evaluation during recursion

david.kaethner at gmail.com david.kaethner at gmail.com
Thu Oct 22 16:20:32 CEST 2015


Hello,

I’m trying to solve an exercise, where I want to walk through the search path recursively (http://adv-r.had.co.nz/Environments.html <http://adv-r.had.co.nz/Environments.html>). 

I’m puzzled by a certain behavior and hope somebody can give me an explanation.

This code works:

listenv <- function(env = parent.frame()) {
  if (identical(env, emptyenv())) {
    #stop("reached emptyenv", call. = FALSE)
    return(env)
  } else {
    print(env)
    listenv(parent.env(env))
  }
}

Here, the calling environment is determined with a default parameter in the function’s formals. 

However, if I want to assign the calling environment within the function’s body, I get the error message „infinite recursion“. Also, I never get actual environments (with attributes, that is), only memory addresses like this: <environment: 0x10da46630>. 

listenv <- function(env) {
  env <- parent.frame()
  if (identical(env, emptyenv())) {
    #stop("reached emptyenv", call. = FALSE)
    return(env)
  } else {
    print(env)
    listenv(parent.env(env))
  }
}

Any explanation of what’s going on here would be greatly appreciated. I suspect it has to do with when exactly the parent.frame()-expression is evaluated, but that’s not an actual explanation.
	[[alternative HTML version deleted]]



More information about the R-help mailing list