我正在阅读Hadley Wickham关于功能的材料,在懒惰的评估中。我无法理解这个例子。我搜索stackoverflow并找到有人问familiar question。但我的问题与此不同。让我引用一点:
add <- function(x) {
function(y) x + y
}
adders <- lapply(1:10, add)
adders[[1]](10)
adders[[10]](10)
我不明白变量y。没有人给y赋值。但“添加”仍然有效。所以我做了一些测试。 1)
> add <- function(x) {
+ function(y){
+ cat("y =",y,",x =",x,"\n")
+ x + y
+ }
+ }
> adders <- lapply(1:10, add)
> adders[[1]](10)
y = 10 ,x = 10
[1] 20
> adders[[10]](10)
y = 10 ,x = 10
[1] 20
>
2)
> adders <- lapply(1:17, add)
> adders[[1]](10)
y = 10 ,x = 17
[1] 27
> adders[[10]](10)
y = 10 ,x = 17
[1] 27
3)
> adders[[1]](12)
y = 12 ,x = 17
[1] 29
> adders[[1]](13)
y = 13 ,x = 17
[1] 30
> adders[[2]](12)
y = 12 ,x = 17
[1] 29
> adders[[2]](13)
y = 13 ,x = 17
因此“y”的值似乎与“()”
中的内容有关4)
> x1 <- 2
> add(x1)
function(y){
cat("y =",y,",x =",x,"\n")
x + y
}
<environment: 0x0000000009c90c30>
>
我想知道y从哪里获得价值? Thx提前。 我还定义了另一个函数如下: 5)
> add2 <- function(x) {
+ function(y){
+ function(z){
+ cat("z =",z,"y =",y,",x =",x,"\n")
+ x + y + z
+ }
+ }
+ }
> adders2 <- lapply(1:17, add2)
> adders2[[1]](12)
function(z){
cat("z =",z,"y =",y,",x =",x,"\n")
x + y + z
}
<environment: 0x0000000009da0378>
> adders2[[1]](13)
function(z){
cat("z =",z,"y =",y,",x =",x,"\n")
x + y + z
}
<environment: 0x0000000009dbabf0>
> adders2[[2]](12)
function(z){
cat("z =",z,"y =",y,",x =",x,"\n")
x + y + z
}
<environment: 0x0000000009dc71c0>
> adders2[[2]](13)
function(z){
cat("z =",z,"y =",y,",x =",x,"\n")
x + y + z
}
<environment: 0x0000000009dd39c8>
>
在什么条件下我可以使用add2()?