Scala:如何设计高阶函数?

问题描述 投票:0回答:1

我想在scala中设计一个高阶函数,它看起来像是流动的:

def过程(数据:Seq [Double],costFun:**):Double

costFun是一个可用于计算方法成本的函数,因为我有serval成本函数,可能有不同的签名,如:

def costGauss(data:Seq [Double],scalaShift:Boolean):Double

def costKernal(数据:Seq [Double],theta:Int):Double

我应该如何设计过程函数,以便能够将具有不同签名的成本函数作为参数costFun传递给它?

scala currying
1个回答
3
投票

似乎你只需要Seq[Double] => Double那里:

def processData(data: Seq[Double], lossFunc: Seq[Double] => Double): Double = ???

def lossGauss(data: Seq[Double], scalaShift: Boolean): Double = ???
def lossKernel(data: Seq[Double], theta: Int): Double = ???

val data: Seq[Double] = Seq(1.0, 2.0, 3.0)
processData(data, lossGauss(_, true))
processData(data, lossKernel(_, 1234))

更好的是,使用多个参数列表与currying:

def processData(data: Seq[Double], lossFunc: Seq[Double] => Double): Double = ???

def lossGauss(scalaShift: Boolean)(data: Seq[Double]): Double = ???
def lossKernel(theta: Int)(data: Seq[Double]): Double = ???

val data: Seq[Double] = Seq(1.0, 2.0, 3.0)
processData(data, lossGauss(true))
processData(data, lossKernel(1234))

顺便说一句:不要使用Floats,特别是不要使用O(1)内存的微小结果。 Seq[Float] => Double会有所帮助,但不是相反。

© www.soinside.com 2019 - 2024. All rights reserved.