Why is the following Scala function called a closure?

本小妞迷上赌 提交于 2019-12-23 15:46:27

问题


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.


回答1:


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.




回答2:


I agree with @Malte as randList is not dependent on any variable declared outside the function. So this function is not a closure.




回答3:


To my understanding, a closure is a function that can reference state in another function. Look this thread for more details: What is a 'Closure'?.

In this problem, as randList doesn't reference any outer variables, it's not a closure...



来源:https://stackoverflow.com/questions/12615091/why-is-the-following-scala-function-called-a-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!