Environments and Closures.
我们一直强调在函数式编程中,All functions are values。那么这个“值”具体是什么呢?
- the code for the function.
- the environment that was current when we created the function.
也就是说,function value 包括 code 与定义时的 environment 两部分;这个 pair 被称为函数闭包 function closure 或者闭包 closure。闭包的定义也是符合词法作用域 lexical scope 的。
我们不能单独访问 pair 中的任意一部分,对于 function value,我们能够执行的操作只有调用 call。这其实也是一种 encapsulation。我们能够发现,the closure overall is closed —— it has everything it needs to produce a function result given a function argument.
1 | var x = 3 |
在上例中,the binding fun f y = x + y bound f to a closure.
- the code part is the function
fn y => x + y. - the environment part maps
xto 1.
在函数 f 闭包创建以后,无论在哪调用 f 最终返回的值都是 4。闭包保证了 evaluate 该函数的环境与调用它时的环境完全隔绝:这是对闭包的另一种理解。
注意,lexical scope 词法作用域是目前大多数编程语言遵循的 semantics;然而 closure 并不是所有语言都具有的;closure 是 function 的 value,因此其在函数式编程语言中是最常见的。