希望这个带有大量评论的完整示例很容易理解。如果您有任何问题,请回复。
您可以通过将其放入 Scala 解释器来执行此代码。
// Here's a trait encapsulating the definition your coworker sent.
trait Given {
def curry[A,B,C](f:(A,B) => C) : A => B => C
def uncurry[A,B,C](f:A => B => C): (A,B) => C
}
object Impl extends Given {
// I'm going to implement uncurry first because it's the easier of the
// two to understand. The bit in curly braces after the equal sign is a
// function literal which takes two arguments and applies the to (i.e.
// uses it as the arguments for) a function which returns a function.
// It then passes the second argument to the returned function.
// Finally it returns the value of the second function.
def uncurry[A,B,C](f:A => B => C): (A,B) => C = { (a: A, b: B) => f(a)(b) }
// The bit in curly braces after the equal sign is a function literal
// which takes one argument and returns a new function. I.e., curry()
// returns a function which when called returns another function
def curry[A,B,C](f:(A,B) => C) : A => B => C = { (a: A) => { (b: B) => f(a,b) } }
}
def add(a: Int, b: Long): Double = a.toDouble + b
val spicyAdd = Impl.curry(add)
println(spicyAdd(1)(2L)) // prints "3.0"
val increment = spicyAdd(1) // increment holds a function which takes a long and adds 1 to it.
println(increment(1L)) // prints "2.0"
val unspicedAdd = Impl.uncurry(spicyAdd)
println(unspicedAdd(4, 5L)) // prints "9.0"
一个较少数字的例子怎么样?
def log(level: String, message: String) {
println("%s: %s".format(level, message))
}
val spicyLog = Impl.curry(log) // spicyLog's type is String => Unit
val logDebug = spicyLog("debug") // This new function will always prefix the log
// message with "debug".
val logWarn = spicyLog("warn") // This new function will always prefix the log
// message with "warn".
logDebug("Hi, sc_ray!") // prints "debug: Hi, sc_ray!"
logWarn("Something is wrong.") // prints "warn: Something is wrong."
更新
您回答询问“编译器如何评估表达式,例如a => b => f(a,b)
。” 好吧,它没有。至少在您同事的代码段中定义事物的方式是无法编译的。不过,一般来说,如果您看到某种形式A => B => C
的意思是“一个以 A 作为参数的函数;它返回一个以 B 作为参数并返回 C 的函数。”