0
$\begingroup$

From the wikipedia of Free variables and bound variables

In computer programming, the term free variable refers to variables used in a function that are neither local variables nor parameters of that function. The term non-local variable is often a synonym in this context.

Since local variables and parameters are bound to particular invocation of the function. Can we say only global variables are the free variables?

asked Jan 8, 2024 at 7:41
$\endgroup$
3
  • 2
    $\begingroup$ The free variables of a function could be bound in an enclosing scope, e.g. a closure. $\endgroup$ Commented Jan 8, 2024 at 8:30
  • $\begingroup$ @Pseudonym "enclosing scope" keyword is infact use in the answer by Jorg. I am confused on what closure have to do with free variable. Looking for convincing rationale on this. $\endgroup$ Commented Jan 9, 2024 at 9:41
  • $\begingroup$ @tnhaxor See, for example, this: opendsa.cs.vt.edu/ODSA/Books/PL/html/FreeBoundVariables.html $\endgroup$ Commented Jan 9, 2024 at 13:51

1 Answer 1

2
$\begingroup$

Can we say only global variables are the free variables?

No.

Counterexample in ECMAScript:

function outerFn() {
 const outerVar = "Outer";
 function innerFn() {
 return outerVar;
 }
 // Could also be written:
 const innerFn2 = () => outerVar;
 return innerFn();
}
console.log(outerFn());

Counterexample in Python:

def outer_fn():
 outer_var = "Outer"
 def inner_fn():
 return outer_var
 return inner_fn()
print(outer_fn())

Counterexample in Ruby:

def outer_method
 outer_var = "Outer"
 inner_lambda = -> () { outer_var }
 inner_lambda.()
end
puts outer_method

Counterexample in Scala:

def outerMethod =
 val outerVar = "Outer"
 def innerFn = outerVar
 innerFn
println(outerMethod)

Counterexample in Java:

public class FreeVariablesInJava {
 static String outerMethod() {
 var outerVar = "Outer";
 
 java.util.function.Supplier<String> innerFn = () -> outerVar; 
 return innerFn.get();
 }
 public static void main(String args[]) {
 System.out.println(outerMethod());
 }
}
answered Jan 8, 2024 at 12:28
$\endgroup$
1
  • $\begingroup$ Why only closure, foo = lambda: bar is also a valid function. Though it will give reference error and that's the one of the rules of programming (not to be thought of computer science), all variables are bound one way or another. $\endgroup$ Commented Jan 9, 2024 at 9:50

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.