Skip to content
Prev 22564 / 398502 Next

Questions about lexical scope

Dear Joseph,


Did you get any answer about your problem ?

I have been toying with your examples and get a bit scared of what
is happening with lexical scoping...


I edited your function bv.integrate to have some informations about
what was going on.

bv.integrate <- function(f, a, b, n=100, rule=midpoint) {
  assign("count", 0, envir=.GlobalEnv)
  g <- function(y) {
    assign("count", get("count", envir=.GlobalEnv)+1, envir=.GlobalEnv
    fx <- function(x) f(x, y)
    rule(fx, a[2], b[2], n)
  }
  cat("# times in g:", get("count", envir=.GlobalEnv), "\n")
  rule(g, a[1], b[1])
}

my R sesssion gave the following:
# times in g: 0 
[1] 0.007080675
[1] 2
# times in g: 0 
[1] 0.773651
[1] 100


For some reason the function 'g' defined in bv.integrate is applied only
2 times when the rule is trapezoidal and 100 times when the rule is
midpoint (?!)... and the variable 'count' I defined in '.GlobalEnv' has
different values (depending on whether I am in '.GlobalEnv' or in
'bv.integrate'....


I must have missed something obvious somewhere... but where ?




L.