efrey
efrey

Reputation: 399

What are the distinctions between lexical and static scoping?

In R programing for those coming from other languages John Cook says that

R uses lexical scoping while S-PLUS uses static scope. The difference can be subtle, particularly when using closures.

I found this odd because I have always thought lexical scoping and static scoping where synonymous.

Are there distinct attributes to lexical and static scoping, or is this a distinction that changes from community to community, person to person? If so, what are the general camps and how do I tell them apart so I can better understand someones meaning when they use these words.

Upvotes: 12

Views: 1339

Answers (2)

zhanxw
zhanxw

Reputation: 3279

R official documentation also addresses differences of scope between R and S-plus: http://cran.r-project.org/doc/manuals/R-intro.html#Scope

The example given from the link can be simplified like this:

 cube <- function(n) {
   sq <- function() n*n
   n*sq()
 }

The results from S-Plus and R are different:

 ## first evaluation in S
 S> cube(2)
 Error in sq(): Object "n" not found
 Dumped
 S> n <- 3
 S> cube(2)
 [1] 18
 ## then the same function evaluated in R
 R> cube(2)
 [1] 8

I personally think the way of treating variable in R is more natural.

Upvotes: 4

torek
torek

Reputation: 487993

Wikipedia (and I) agree with you that the terms "lexical scope" and "static scope" are synonymous. This Lua discussion tries to make a distinction, but notes that people don't agree as to what that distinction is. :-)

It appears to me that the attempted distinction has to do with accessing names in a different function-activation-record ("stack block", if you will) than the most-current-execution record, which mainly (only?) occurs in nested functions:

function f:
    var x
    function h:
        var y
        use(y)  -- obviously, accesses y in current activation of h
        use(x)  -- the question is, which x does this access?

With lexical scope, the answer is "the activation of f that called the activation of h" and with dynamic scope it means "the most recent activation that has any variable named x" (which might not be f). On the other hand, if the language forbids the use of x at all, there's no question about "which x is this" since the answer is "error". :-) It looks as though some people use "static scope" to refer to this third case.

Upvotes: 10

Related Questions