Reputation: 1058
I want to design a high order function in scala which may looks like flowing:
def process(data: Seq[Double], costFun: **): Double
costFun is a function which can be used to calculate the cost of a method, since I have serval cost functions, which may have different signatures, like:
def costGauss(data: Seq[Double], scalaShift: Boolean): Double
def costKernal(data: Seq[Double], theta: Int): Double
how should I design the process function to enable that cost functions which have different signatures can be passed to it as parameter costFun?
Upvotes: 0
Views: 63
Reputation: 44918
Seems that you need just Seq[Double] => Double
there:
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))
Even better, use multiple argument lists with 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))
And by the way: don't use Float
s, especially not for tiny results that take O(1) memory. Seq[Float] => Double
would make some sense, but not the other way round.
Upvotes: 3