为什么以下Scala函数称为闭包? [英] Why is the following Scala function called a closure?
问题描述
对于以下问题: http://pastie.org/4825115 ,这是我的代码: http://pastie.org/private/n22zohyshn2ymqrbrb3g
def randList(len:Int,n:Int):List [Int] = len match {
case 0 => List()
case len => scala.util.Random.nextInt(n):: randList(len-1,n)
}
但是我不知道为什么randList被称为闭包。
根据我的理解 randList
绝对不是不是闭包(维基百科似乎同意),因为-在您提供的代码段中-它仅取决于局部变量(参数也被视为局部变量)。考虑到 randList
的主体,没有所谓的 free变量,即没有从当前词法范围中获取其值的变量,后者是方法主体本身。 len
和 n
都是当前词法范围的变量,因为它们都是<$ c的封闭定义的参数$ c> randList 。
请考虑以下示例:
var n = 10
val f =(x:Int)=> x + n
println(f(1))// 11
n = 20
println(f(1))// 21
函数 f
是一个闭包,因为它不仅依赖于
它的参数,也可以在其自身的词法作用域(即 n
)之外声明的变量上使用。
Wikipedia文章提到闭包由函数定义,并带有声明自由参数的词法范围。下一个示例说明了这一点:
// n == 20
// f如
def foo(g:Int = >> Int)= {
val n = 100
g(1)
}
println(foo(f) )// 21
foo(f)$ c的结果$ c>仍然是
21
,尽管 foo
定义了自己的局部变量 n
,并且可能会假定 f
现在使用此 n
。但是,闭包 f
与其声明周围的词法范围相关,这是 n
的值所在的地方。取自 f
的评估时间。
For the following question: http://pastie.org/4825115, here is my code: http://pastie.org/private/n22zohyshn2ymqrbrb3g
def randList(len: Int, n: Int): List[Int] = len match {
case 0 => List()
case len => scala.util.Random.nextInt(n) :: randList(len-1, n)
}
but I don't know why randList is called a closure.
According to my understanding randList
is definitely not a closure (Wikipedia seems to agree) , since - in the snippet of code you provided - it only depends on local variables (parameters are also considered local variables). Considering the body of randList
, there is no so-called free variable, i.e., a variable that does not get its value from the current lexical scope, where the latter is the method body itself. len
and n
are both variables of the current lexical scope since they are both parameters of the enclosing definition of randList
.
Consider this example:
var n = 10
val f = (x: Int) => x + n
println(f(1)) // 11
n = 20
println(f(1)) // 21
The function f
is a closure because it does not only depend on its parameters, but also on a variable that is declared outside of its own lexical scope (namely n
).
The Wikipedia article mentions that a closure is defined by a function together with a lexical scope that declares the free arguments. The next example illustrates this:
// n == 20
// f as above
def foo(g: Int => Int) = {
val n = 100
g(1)
}
println(foo(f)) // 21
The result of foo(f)
is still 21
although foo
defines its own local variable n
, and one might assume that f
now uses this n
. However, the closure f
is coupled to the lexical scope that surrounds its declarations, which is where the value of n
is take from when f
is evaluated.
这篇关于为什么以下Scala函数称为闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!