michael
michael

Reputation: 84

what is the formal defenition of closure? and does it depend on the programming languege?

According to my professor, closure is the value of a function in a functional programming language. But when I googled it, I saw another definition that said:

A closure is a function having access to the parent scope, even after the parent function has closed.

Which one is correct?

Upvotes: 0

Views: 297

Answers (1)

slouc
slouc

Reputation: 9698

Definition that you found online is correct.

Here's some pseudocode:

i = 1

def foo(j: Int) = {
  k = 2
  return i + j + k
}

foo(42) // returns 45; value of "i" is preserved inside the function

Function foo adds the values of variables i, j and k. Variable j is a function argument, and variable k is a local variable defined inside the body of a function. But variable i comes from the "outside", and is called a free variable.

A closure is any function that "closes over" one or more free variables. Local variables and function arguments are no longer needed once a function has finished, which means that the whole stack frame on which the function kept its variables can be popped. But having a free variable means that the stack frame needs to be kept in RAM for future use.

In some languages, changing the value of the free variable doesn't effect the locally memoized state of the corresponding closures, whereas in other languages the change is visible. Using the i and foo from earlier:

// some languages, e.g. Javascript:
foo(42) // 45
i = 2
foo(42) // 45

// other languages, e.g. Scala:
foo(42) // 45
i = 2
foo(42) // 46

I don't know what your teacher meant by "value of a function". In functional programming, functions are so called "first class citizens", which means that every function is a value (it can be taken as a function parameter, returned from a function, kept inside collections etc.).

Upvotes: 2

Related Questions