Scala何时使用Currying
示例
Currying是将包含多个参数的函数的评估转换为评估一系列函数的技术,每个函数都有一个参数。
通常在以下情况下有用:
函数的不同自变量在不同时间计算。(示例1)
函数的不同自变量由应用程序的不同层计算。(示例2)
例子1
假设年收入总额是由收入和奖金组成的函数:
val totalYearlyIncome:(Int,Int) => Int = (income, bonus) => income + bonus
上述2-arity函数的最新版本是:
val totalYearlyIncomeCurried: Int => Int => Int = totalYearlyIncome.curried
请注意,在上面的定义中,该类型也可以查看/编写为:
Int => (Int => Int)
让我们假设年收入部分是预先知道的:
val partialTotalYearlyIncome: Int => Int = totalYearlyIncomeCurried(10000)
在下线的某个点,奖金是已知的:
partialTotalYearlyIncome(100)
例子2
假设汽车制造涉及车轮和车身的应用:
val carManufacturing:(String,String) => String = (wheels, body) => wheels + body
这些零件由不同的工厂应用:
class CarWheelsFactory { def applyCarWheels(carManufacturing:(String,String) => String): String => String = carManufacturing.curried("应用轮毂") } class CarBodyFactory { def applyCarBody(partialCarWithWheels: String => String): String = partialCarWithWheels("适用车身") }
请注意,CarWheelsFactory以上内容限制了汽车的制造功能,并且仅应用了车轮。
汽车制造过程将采用以下形式:
val carWheelsFactory = new CarWheelsFactory() val carBodyFactory = new CarBodyFactory() val carManufacturing:(String,String) => String = (wheels, body) => wheels + body val partialCarWheelsApplied: String => String = carWheelsFactory.applyCarWheels(carManufacturing) val carCompleted = carBodyFactory.applyCarBody(partialCarWheelsApplied)