Scala 中的柯里化示例 [英] Currying Example in Scala
问题描述
以下是柯里化的好例子吗?
Is the following a good example of currying?
def sum(a: Int, b: Int) : (Int => Int) = {
def go(a: Int) : Int = {
a + b;
}
go
}
我对下面的结果有点理解,但是我怎么能用咖喱的方式写(或者我应该怎么写)sum()
?
I half understand the below results, but how could I write (or maybe how I should've written) sum()
in a curried way?
scala> sum(3,4) res0: Int => Int = <function1>
scala> sum(3,4).apply(2) res1: Int = 6
scala> sum(3,4).apply(3) res2: Int = 7
推荐答案
在 Scala 中引入了柯里化机制来支持类型推断.例如标准库中的 foldLeft
函数:
Currying mechanism was introduced in Scala to support type inference. For example foldLeft
function in the standard lib:
def foldLeft[B](z: B)(op: (B, A) => B): B
在不柯里化的情况下,您必须明确提供类型:
Without currying you must provide types explicitly:
def foldLeft[B](z: B, op: (B, A) => B): B
List("").foldLeft(0, (b: Int, a: String) => a + b.length)
List("").foldLeft[Int](0, _ + _.length)
柯里化函数的三种写法:
There are three ways to write a curried function:
1) 写成柯里化形式:
1) Write it in currying form:
def sum(a: Int)(b: Int) = a + b
这只是语法糖:
def sum(a: Int): Int => Int = b => a + b
2) 在函数对象 (sum _).curried
上调用 curried
并检查类型:
2) Call curried
on the function object (sum _).curried
and check the types:
sum: (a: Int, b: Int)Int
res10: Int => (Int => Int) = <function1>
在您的示例中,您可以使用 Scala 类型推断来减少代码量并更改您的代码:
In your example, you can use Scala type inference to reduce the amount of code and change your code:
def sum(a: Int, b: Int) : (Int => Int) = {
def go(a: Int) : Int = {
a + b;
}
go
}
进入:
def sum(a: Int, b: Int) : (Int => Int) = c => a + b + c
语义上这些是相同的,因为您明确提供了返回类型,因此 Scala 知道您将返回一个带有 Int
参数的函数并返回一个 Int
semantically these are the same, because you explicitly provided the return type, so Scala knows that you will return a function wich takes an Int
argument and return an Int
关于curring的更完整的答案是由retronym
Also a more complete answer about curring was given by retronym
这篇关于Scala 中的柯里化示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!