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?

$\endgroup$
3
  • 2
    $\begingroup$ The free variables of a function could be bound in an enclosing scope, e.g. a closure. $\endgroup$
    – Pseudonym
    Jan 8 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
    Jan 9 at 9:41
  • $\begingroup$ @tnhaxor See, for example, this: opendsa.cs.vt.edu/ODSA/Books/PL/html/FreeBoundVariables.html $\endgroup$
    – Pseudonym
    Jan 9 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());
    }
}
$\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$
    – tbhaxor
    Jan 9 at 9:50

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.