【发布时间】:2022-01-08 18:27:00
【问题描述】:
在 Scala 中称为 inc 的以下函数中执行增量操作。
def inc(more:Int) = {
def helper(x:Int) = x+more
helper _
}
无论何时调用 inc 函数,它都会返回另一个绑定传递给它的参数的函数。例如,inc(1) 将返回另一个 Int => Int 类型的函数,其中变量 more 与 1 绑定。
inc(1) // This is of type Int => Int
那么我们可以说 more 是返回函数的状态变量,当我们调用 inc(1) 时,会将 1 分配给 more?
这里有一些详细说明,
由于我来自 OO 编程范式,当我说状态时,我将它与类的实例相关联,该类在给定时间具有特定状态。让我们首先考虑 Java 中的一个类 IncHelper,如下所示:
class IncHelper{
private int more;
public IncHelper(int more){
this.more = more;
}
public int inc(int x){
return x+this.more;
}
}
如果我创建上述类的不同实例如下:
IncHelper inc1 = new IncHelper(1);
// This instance will always increase a value by 1
inc1.inc(10); // output will be 11
如果我创建上述类的不同实例如下:
IncHelper inc2 = new IncHelper(2);
// This instance will always increase a value by 2
inc2.inc(10); // output will be 12
因此,在上述两种情况下,两个实例 inc1 和 inc2 包含两个不同的状态变量值。我为 Scala 函数式编程给出的示例也是如此:
val inc1 = inc(1)
inc1(10) // Will return 11
如果我创建另一个值如下:
val inc2 = inc(2)
inc2(10) // Will return 12
所以在这两种情况下,即 OO 编程,当我创建 2 个 IncHelper 实例时,它会记住在构造它时传递的变量。同样,我们创建的两个函数字面量也是如此,其中在创建函数字面量时传递的两个变量 inc1 和 inc2 存储了值。
【问题讨论】:
标签: scala functional-programming closures