[R] static vs. lexical scope

Richard O'Keefe r@oknz @end|ng |rom gm@||@com
Thu Sep 26 15:44:48 CEST 2019


Actually, R's scope rules are seriously weird.
I set out to write an R compiler, wow, >20 years ago.
Figured out how to handle optional and keyword parameters efficiently,
figured out a lot of other things, but choked on the scope rules.
Consider

> x <- 1
> f <- function () {
+   a <- x
+   x <- 2
+   b <- x
+   c(a=a, b=b)
+ }
> f()
a b
1 2
> x
[1] 1

It's really not clear what is going on here.
However, ?assign can introduce new variables into an environment,
and from something like
  with(df, x*2-y)
it is impossible for a compiler to tell which, if either, of x and y is to
be obtained from df and which from outside.  And of course ?with
is just a function:

> df <- data.frame(y=24)
> w <- with
> w(df, x*2-y)
[1] -22

So you cannot in general tell *which* function can twist the environment
in which its arguments will be evaluated.

I got very tired of trying to explore a twisty maze of documentation and
trying to infer a specification from examples.  I would come up with an
ingenious mechanism for making the common case tolerable and the
rare cases possible, and then I'd discover a bear trap I hadn't seen.
I love R, but I try really hard not to be clever with it.




So while R's scoping is *like* lexical scoping, it is *dynamic* lexical
scoping, to coin a phrase.

On Thu, 26 Sep 2019 at 23:56, Martin Møller Skarbiniks Pedersen
<traxplayer using gmail.com> wrote:
>
> On Wed, 25 Sep 2019 at 11:03, Francesco Ariis <fa-ml using ariis.it> wrote:
> >
> > Dear R users/developers,
> > while ploughing through "An Introduction to R" [1], I found the
> > expression "static scope" (in contraposition to "lexical scope").
> >
> > I was a bit puzzled by the difference (since e.g. Wikipedia conflates the
> > two) until I found this document [2].
>
>
> I sometimes teach a little R, and they might ask about static/lexical scope.
> My short answer is normally that S uses static scoping and R uses
> lexical scoping.
> And most all modern languages uses lexical scoping.
> So if they know Java, C, C# etc. then the scoping rules for R are the same.
>
> I finally says that it is not a full answer but enough for most.
>
> Regards
> Martin
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list