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?
-
2$\begingroup$ The free variables of a function could be bound in an enclosing scope, e.g. a closure. $\endgroup$Pseudonym– Pseudonym ♦2024年01月08日 08:30:05 +00:00Commented 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$tbhaxor– tbhaxor2024年01月09日 09:41:20 +00:00Commented Jan 9, 2024 at 9:41
-
$\begingroup$ @tnhaxor See, for example, this: opendsa.cs.vt.edu/ODSA/Books/PL/html/FreeBoundVariables.html $\endgroup$Pseudonym– Pseudonym ♦2024年01月09日 13:51:40 +00:00Commented Jan 9, 2024 at 13:51
1 Answer 1
Can we say only global variables are the free variables?
No.
function outerFn() {
const outerVar = "Outer";
function innerFn() {
return outerVar;
}
// Could also be written:
const innerFn2 = () => outerVar;
return innerFn();
}
console.log(outerFn());
def outer_fn():
outer_var = "Outer"
def inner_fn():
return outer_var
return inner_fn()
print(outer_fn())
def outer_method
outer_var = "Outer"
inner_lambda = -> () { outer_var }
inner_lambda.()
end
puts outer_method
def outerMethod =
val outerVar = "Outer"
def innerFn = outerVar
innerFn
println(outerMethod)
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());
}
}
-
$\begingroup$ Why only closure,
foo = lambda: baris 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$tbhaxor– tbhaxor2024年01月09日 09:50:07 +00:00Commented Jan 9, 2024 at 9:50
Explore related questions
See similar questions with these tags.