Friday, October 2, 2015

Lexical Scoping in R

Lexical Scoping in R

 ---------------------------------- What is the output? -----------------------

y = "World!"

f = function(x) {
  y = "Weird!"

g = function(x) {
  cat(x, y)



 > search()
 [1] ".GlobalEnv"        "package:RMySQL"    "package:DBI"    
 [4] "tools:rstudio"     "package:stats"     "package:graphics"
 [7] "package:grDevices" "package:utils"     "package:datasets"
 [10] "package:methods"   "Autoloads"         "package:base"

R, like Perl, Python and Lisp, is lexical(static) scoping. It searches for free variables in various environments with a specific order.

In this case, y is the free variable of function g(x).

The search order is:

 1, The environment where g(x) is defined: Global environment
 2, Parent environment (package, namespace, import)
 3, Repeat 2 till it reaches the top level
 4, Empty environment, error.

 Empty environment has not parent.

Here is a function closure in R:

lcg<-function(a,c,m) {
return( function(x) {
(a*x+c) %% m
my_runif=lcg(214013,2531011, 2^32)


 A well known question: "Does all computer languages converge to LISP?"