1

I'm reading Hadley Wickham's materials about function, in the part of lazy evaluation. I can't understand the example. I search the stackoverflow and find someone ask a familiar question. But my question is different from it. Let me quote that bit:

add <- function(x) {
  function(y) x + y
}
adders <- lapply(1:10, add)
adders[[1]](10)
adders[[10]](10)

I don't understand the variable y. Nobody gives values to y. But the "add" can still work. So I do some test. 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 

so the value of "y" seem to have relation to the content inside "()"

4)

> x1 <- 2
> add(x1)
function(y){
        cat("y =",y,",x =",x,"\n")
        x + y
    }
<environment: 0x0000000009c90c30>
> 

I want to understand where does y get the value from? Thx in advance. And I also define another function as follows: 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>
>  

under what condition can I use add2()?

Community
  • 1
  • 1
ChaoXu
  • 11
  • 1

0 Answers0