[R] Lazy Evaluation?
Thomas Stabla
statho3 at web.de
Mon Jun 7 14:43:48 CEST 2004
Hello,
I've stumbled upon following problem, when trying to overload the methods
for group Math for an S4-class which contains functions as slots.
setClass("NumFunction", representation = list(fun = "function"))
NumFunction <- function(f) new("NumFunction", fun = f)
square <- function(x) x^2
NF <- NumFunction(square)
setMethod("Math",
"NumFunction",
function(x){
nfun <- function(n) callGeneric(x at fun(n))
tmp <- function(n) nfun(n)
NumFunction(tmp)
})
sinNF <- sin(NF)
sinNF at fun(sqrt(pi/2))
# works as expected, returns 1
# now a slightly different version of setMethod("Math", "NumFunction",
# ...), which dispenses the "unnecessary" wrapper function tmp()
setMethod("Math",
"NumFunction",
function(x){
nfun <- function(n) callGeneric(x at fun(n))
return(NumFunction(nfun))
})
sinNF <- sin(NF)
sinNF at fun(sqrt(pi/2))
# produces an error, namely:
# Error in typeof(fdef) : evaluation nested too deeply: infinite
# recursion / options(expression=)?
Replacing the generating function NumFunction() with corresponding
new(..) calls doesn't change the outcome.
When I call the newly defined functions nfun resp. tmp from within the
function body of setMethod(), e.g.
setMethod("Math",
"NumFunction",
function(x){
nfun <- function(n) callGeneric(x at fun(n))
cat(nfun(1))
NumFunction(nfun)
})
by tmp(1) resp. nfun(1), both versions "cat" correct output when called by
sin(NF).
If I don't return NumFunction(tmp) resp. NumFunction(nfun) but tmp resp.
nfun, both versions work just fine, i.e. sin(NF)(sqrt(pi/2)) returns 1.
Would someone explain me this behavior? (R Version 1.9.0)
Best regards,
Thomas Stabla
Sourcecode can be found at:
http://www.uni-bayreuth.de/departments/math/org/mathe7/DISTR/NumFun.R
More information about the R-help
mailing list