-2

假设我有以下代码:

val someNumbers = List(-11, -10, -5, 0, 5, 10)

someNumbers.foreach( println _ )

val j = 10

(x: Int) => x + j

我的问题是Scala 中的部分应用函数和闭包是正交的吗? 该演示文稿似乎表明它们是。


编辑:2014 年 7 月 13 日 [以上代码已更改]

4

2 回答 2

0

当您进入 repl 时,很容易看到返回的内容:

scala> type IntPairPred = (Int, Int) => Boolean
defined type alias IntPairPred

scala> val gt: IntPairPred = _ > _
gt: IntPairPred = <function2>

scala> gt(2,3)
res3: Boolean = false

什么gtfunction2ie 一个接受 2 个参数的函数

这是另一个例子:

scala> def fn(a: Int, b: Int) = () => a + b
fn: (a: Int, b: Int)() => Int

scala> val a = fn(2,3)
a: () => Int = <function0>

fn返回的是一个不function0带任何参数的函数

于 2014-07-11T16:13:40.867 回答
0

Sorry but your example doesn't seem to refer to partial application, at least to me.

You're just using some shortcut syntax to define regular functions.

Actually gt, ge, ... definitions are expanded to something pretty like

val gt: IntPairPred = (x: Int, y: Int) => x > y
val gt: IntPairPred = (x: Int, y: Int) => x >= y
//and so on...

Regular functions support modification of its arguments, but this is not what you're looking for, I presume.

To define a closure, you should define a partial function referring to a variable in the outer scope, like

var one = 1
val gt1 = gt(1, _: Int)

assert(gt1(0))  //ok
assert(!gt1(1)) //ok

one = 2 //weirdo!
assert(gt1(0))  //ok
assert(gt1(1)) //ok
assert(!gt1(2)) //ok

So the point is not in functions definition or partial application. The point is if, at definition time, you're using variables from the closing scope within your function. In this case your function is influenced by the variable you closed over.

Is this what you were after?

于 2014-07-11T16:46:26.557 回答