Skip to content

Instantly share code, notes, and snippets.

@ShawnMcCool
Last active August 29, 2015 14:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShawnMcCool/c1e7b62e94ab58f6e8d0 to your computer and use it in GitHub Desktop.
Save ShawnMcCool/c1e7b62e94ab58f6e8d0 to your computer and use it in GitHub Desktop.
Why a closure is called a closure.
// An anonymous function written in lambda syntax:
x => x + 1
val func = x => x + 1
func(3) // returns 4
// In this case, the lambda `x => x + 1` relies on NO external data.
// It's fundamentally complete. X is provided as an argument to the function.
// It's considered a 'closed term', term meaning more or less a 'bit of source'.
// Then, consider this function:
x => x + y
// Here, the term is open because the function relies on values that do not
// exist within the function. Of course, you won't be able to compile this function
// without y being in scope. So, imagine this code:
val y = 3
val func = x => x + y
func(4) // returns 7
// What happens is that the moment the function is assigned to the value, the term
// is closed. The compiler looks at all of the available variables in scope and binds
// the necessary references to the val func.
// The value `func` is the closure.
// NOT the function declaration itself.
// You could move the value func to another part of the application in which `y` is
// entirely outside of scope and it'd still refer to the original value y that was in
// scope when the function was closed.
// So, that's why the value `func` is a closure. It's the opposite of an opening, it's
// a closing, but in English it's a closure.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment