Table of contents
1.
Introduction
2.
What is Scope in Programming?
3.
Lexical Scoping
4.
Dynamic Scoping
5.
Differences between Lexical and Dynamic Scoping
6.
Frequently Asked Questions
6.1.
What is the default scoping mechanism in R?
6.2.
Which scoping mechanism is generally recommended in R programming?
6.3.
How does the local() function help in scoping in R programming?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lexical Scoping vs Dynamic Scoping in R

Author Aayush Sharma
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Have you ever wondered how different programming languages handle the access of multiple variables in functions? In programming, this process is known as Scoping. Scoping defines how variables are resolved in our code which changes the output of our programs.

lexical scoping vs dynamic scoping in R

In this article, we will discuss concepts of scoping in the R programming language. We will also discuss Lexical and Dynamic Scoping and see the significant differences between Lexical Scoping and Dynamic Scoping in R. First, let us understand the concept of Scope in detail along with examples.

What is Scope in Programming?

In programming we use Scope to refer to a particular section of code in which a certain variable is accessible. Scope determines the lifespan of a variable and code section in which it is visible to the program. Let us understand scope in more detail with the help of an example.

Code:

# Global variable
global_variable <- 20

func <- function() {

	# Local variable
	local_variable <- 10
	print(local_variable)
	print(global_variable)  
}

func()

 

Output:

console output

Explanation:

In the above example, we have defined a global variable named "global_variable", a function named "func" and a local variable "local_variable" inside the function.

If we execute the function that displays the values of the two variables it contains, both variables are correctly printed.

 

Code: 
 

# Global variable
global_variable <- 20

func <- function() {

	# Local variable
	local_variable <- 10
}

func()

print(global_variable)  
print(local_variable)

 

Output:

console output

Explanation: 

Why does the local variable produce an error in this case while the value of the global variable is reported correctly?

This is due to the fact that the global variable's scope covers the whole program, allowing for unlimited access from anywhere. Local variables' range, however, is controlled by the function or code block in which they are declared. Beyond that, attempting to utilize the local variable results in an error.

Lexical Scoping

Lexical Scoping is one of the scoping mechanisms used by programming languages. This mechanism is also present in the R programming language. Lexical Scoping is the default scoping mechanism in the R programming language. In lexical scoping, the variable's Scope is defined by its surrounding environment (code blocks and functions).

lexical scoping

In the lexical scoping mechanism, the program first looks for the variable in the current Scope whenever a variable is needed. If the variable is found in that Scope, its value is captured. Otherwise, it moves to the next outer block until it reaches the global Scope. In the case of two variables with the same name, the variable in the nearest Scope is considered. This process is known as scope resolution in programming.

Let us understand the mechanism behind lexical scoping in a better way using code examples.

Code: 

# Outer function
func <- function(a) {

	# Inner function
	increment <- function() {
		a+1  
	}
 
	increment()
}

result <- func(10)
print(result)

 

Output:

console output

Explanation: 

In the above example, we have created a simple function to increment the number by one. We can observe that even if we don't provide the variable "a" to the inner function, it searches the scope blocks progressively and gets the value from the nearest block.

Lexical Scoping is used in most of the programming languages due to its many advantages. These advantages include:

  • Easy Readability
     
  • Easy Debugging
     
  • Better Efficiency
     
  • Predictable Behavior
     

However lexical scoping lacks dynamism. The scoping structure is fixed in lexical scoping, which makes it impossible to change the scoping order. In the next section we will discuss another form of scoping known as dynamic scoping.

Dynamic Scoping

Dynamic scoping is also one of the scoping mechanisms used in programming languages. Dynamic Scoping is not a very popular scoping mechanism, but it is still used by languages like Perl, Lisp, Bash, etc.

dynamic scoping

Unlike Lexical Scoping, the Scope of a variable is not dependent on the program's structure; instead, it depends on the order of the function calls. Hence it is called dynamic scoping, as the Scope can change dynamically depending on the order of the function calls.

Whenever a variable is referenced, the scoping searches for the most recent called function, which also contains the variable. This process is continued until it finds the variable or the Scope reaches the global Scope.Let us understand Dynamic Scoping better using a code example.

Code: 

# global variable
var1 <- 10

# function1
	func1 <- function() {
	print(var1)
}

# function2
func2 <- function() {
	func1()
}

# function3
func3 <- function() {
	var1 <<- 20
	func2()
}

func3()

 

Output:

console output

Explanation:

The func3() function references the globally declared variable var1 in the above example. Since R does not support lexical scoping, we use the global assignment operator "<<-" instead.

Since Dynamic scoping depends on the sequence in which functions are called, the value of var1 becomes 20. This is because func3 is called first, hence it becomes the inner scope and changes the value to 20.

Dynamic Scoping allows us to use a more flexible approach for scoping. We can change the scope of variables dynamically on runtime. This feature is not available in lexical scoping.

But dynamic scoping also has some disadvantages. Some of these disadvantages include:

  • Increased complexity
     
  • Undefined Behavior
     
  • Difficult to Debug
     
  • Limited Support
     

All of the above factors make dynamic scoping a rarely used scoping mechanism in programming languages.

Differences between Lexical and Dynamic Scoping

Now that we have discussed both lexical and dynamic scoping, we will discuss the critical differences between lexical scoping vs. dynamic scoping in R.

difference between lexical scoping and dynamic scoping

The main differences between lexical scoping vs. dynamic scoping in R are listed in the table below.

Lexical Scoping

Dynamic Scoping

Lexical scoping is a type of scoping in which the program's structure defines the Scope of a variable.

Dynamic scoping is a type in which the variable Scope is defined by the calling sequence of functions in the program.

In lexical scoping, the variables are accessed based on their enclosing function.

The variables are accessed in dynamic scoping based on the current execution sequence.

Lexical scoping has more predictable behaviors, making it a better choice.

Dynamic scoping can result in unexpected behavior and makes the program harder to understand.

Lexical scoping is generally the default scoping mechanism in most languages.

Due to its complex mechanism, dynamic scoping is only used in some languages.

It offers better performance as the Scope is determined at compile time.

It has additional overhead because of runtime scope resolution.

Lexical Scoping is used in most programming languages, such as C++, Java, R, Python etc.

Dynamic Scoping is used in a few programming languages like Perl, Lisp, and Bash.

Frequently Asked Questions

What is the default scoping mechanism in R?

In the R programming language, lexical scoping is the default scoping mechanism. In the Lexical scoping tool, a variable's lifespan and Scope depend on its scope environment, defined at its creation time.

Which scoping mechanism is generally recommended in R programming?

Generally, Lexical Scoping is recommended in R programming. Lexical Scoping has predictable behavior, better variable access, and helps to reduce ambiguity with variable names. It is advised not to use Dynamic Scoping unless it is necessary.

How does the local() function help in scoping in R programming?

The local() function creates a temporary local environment in R programming. This helps to dynamically scope program variables by temporarily changing the environment. The local() function creates a temporary local environment in R programming, allowing for dynamic scoping of program variables.

Conclusion

In this article, we discussed lexical and dynamic scoping R Programming Language in detail. We discussed scoping in general with some code examples. Then we discussed Lexical Scoping and Dynamic Scoping in R, along with frequently asked questions. So now that you have learned about Lexical Scoping vs. Dynamic Scoping in R, you can refer to similar articles.

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSA, Competitive Programming, System Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning, Ninja!

Live masterclass