简体   繁体   English

如何在 scala 中编写通用 function?

[英]how to write a generic function in scala?

I want to calculate the mean of every two consecutive elements in array a, and return a new array.我想计算数组 a 中每两个连续元素的平均值,并返回一个新数组。 The parameter type T can be any of the numerical type such as Byte, Short, Int, Float, and Double.参数类型 T 可以是任何数值类型,例如 Byte、Short、Int、Float 和 Double。 I don't know how to make it work.我不知道如何使它工作。 Thanks in advance!提前致谢!

def center[T](a: Array[T]): Array[T] = {
  for (i <- 0 until a.size - 1) yield (a(i) + a(i + 1)) / 2
}

One issue we have to deal with is that integer division produces an integer result: (2+3)/2 == 2我们必须处理的一个问题是 integer 除法产生 integer 结果: (2+3)/2 == 2

If we decide that we always want fractional results (maybe Double ?) then it simplifies the task a bit.如果我们决定总是想要分数结果(也许是Double ?),那么它会稍微简化任务。 What's left is how to deal with input of any number type.剩下的是如何处理任何数字类型的输入。

def center[N](a:Array[N])(implicit ev:Numeric[N]):Array[Double] = {
  import ev._
  if (a.lengthIs < 2) a.map(_.toDouble)
  else a.sliding(2)
        .map{case Array(a,b) => (a+b).toDouble/2.0}.toArray
}

testing:测试:

center(Array(2, 3, 11, 4, 71))
//res0: Array[Double] = Array(2.5, 7.0, 7.5, 37.5)

center(Array(2.3, 1.1, 4.5, 7.1))
//res1: Array[Double] = Array(1.7, 2.8, 5.8)

This code example without dividing because of you should define your own typeclass for diving by integer value.此代码示例无需划分,因为您应该通过 integer 值定义自己的潜水类型类。

def center[T: Numeric](a: Array[T]): Array[T] = {
  a.sliding(2).map { case Array(f, s) => Numeric[T].plus(f, s) }.toArray
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM