在R中实现ifLet功能
代码如下:在R中实现ifLet功能,r,metaprogramming,R,Metaprogramming,代码如下: setGeneric("ifLet", function(sym, x, body1, body2, ...) { standardGeneric("ifLet") }) setMethod("ifLet", signature(sym = "name", x = "ANY", body1 = "ANY", body2 = "ANY"), function(sym, x, body1, body
setGeneric("ifLet",
function(sym, x, body1, body2, ...) {
standardGeneric("ifLet")
})
setMethod("ifLet",
signature(sym = "name", x = "ANY", body1 = "ANY", body2 = "ANY"),
function(sym, x, body1, body2 = {}) {
e = new.env()
sym_str = deparse(substitute(sym))
ifLet(sym_str, x, body1, body2)
})
setMethod("ifLet",
signature(sym = "name", x = "ANY", body1 = "ANY", body2 = "ANY"),
function(sym, x, body1, body2 = {}) {
stopifnot(length(sym) == 1)
e = new.env()
assign(sym, x, envir = e)
if(e[[sym]]) {
eval(substitute(body1), e)
} else {
eval(substitute(body2), e)
}
})
ifLet("..temp..", TRUE, {print(paste("true.", as.character(..temp..)))},
{print(paste("false.", as.character(..temp..)))})
ifLet(..temp.., TRUE, {print(paste("true.", as.character(..temp..)))},
{print(paste("false.", as.character(..temp..)))})
“.temp..”版本工作正常,但.temp..
版本产生错误:
error in evaluating the argument 'sym' in selecting a method for function 'ifLet': Error: object '..temp..' not found
为什么会出现此错误?我如何解决此问题