The Art of R Programming

(WallPaper) #1
Here’s an example:

>f
function(y) {
d<-8
return(h(d,y))
}
>h
function(dee,yyy) {
print(ls())
print(ls(envir=parent.frame(n=1)))
return(dee*(w+yyy))
}

> f(2)
[1] "dee" "yyy"
[1] "d" "y"
[1] 112

Withparent.frame(), the argumentnspecifies how many frames to go
up in the call chain. Here, we were in the midst of executingh(), which had
been called fromf(), so specifyingn=1gives usf()’s frame, and thus we get
its locals.

7.6.4 Functions Have (Almost) No Side Effects..........................


Yet another influence of the functional programming philosophy is that
functions do not change nonlocal variables; that is, generally, there are no
side effects. Roughly speaking, the code in a function has read access to its
nonlocal variables, but it does not have write access to them. Our code can
appear to reassign those variables, but the action will affect only copies, not
the variables themselves. Let’s demonstrate this by adding some more code
to our previous example.

>w<-12
>f
function(y) {
d<-8
w<-w+1
y<-y-2
print(w)
h <- function() {
return(d*(w+y))
}
return(h())
}

156 Chapter 7

Free download pdf