编写可以采用Int或Double值的scala函数

时间:2016-10-13 13:56:03

标签: scala

我编写了一个接受以下类型值的函数: (1,数组(1.0,2.0,3.0)) 这是一个元组,其中Int是第一个值,接下来是一个双打数组。

我也希望它也接受一个整数数组。我写的函数如下:

def getCountsAndAverages[T](Parameter: Tuple2[Int, Array[T]])(implicit n:Numeric[T]) = {
(Parameter._1, (Parameter._2.size,   Parameter._2.map(n.toDouble).sum/Parameter._2.size)) 
}

元组的第一个参数是一个数字,然后是一个数组,它出现在文件中。

它适用于示例案例,但是我正在读取一个文本文件,其中的数据格式与此函数所需的格式相同。我使用'map'操作调用此函数:

parsedfile.map(getCountsAndAverages)

我收到以下错误:

◾could not find implicit value for parameter n: Numeric[T]
◾not enough arguments for method getCountsAndAverages: (implicit n: Numeric[T])(Int, (Int, Double)). Unspecified value parameter n.

我将不胜感激任何帮助或建议

2 个答案:

答案 0 :(得分:1)

您可以使用以下任何一种语法

def foo[T](x: T)(implicit n: Numeric[T]) = n.toDouble(x)

def foo[T : Numeric](x: T) = implicitly[Numeric[T]].toDouble(x)

在你的情况下

def getCountsAndAverages[T: Numeric](Parameter: Tuple2[Int, Array[T]]) = {
 (Parameter._1, (Parameter._2.size, Parameter._2.map(implicitly[Numeric[T]].toDouble(_)).sum / Parameter._2.size))
}

答案 1 :(得分:1)

  1. Iterable不是Array,因此您的功能无法解决问题。您可以改为定义def getCountsAndAverages[T](Parameter: Tuple2[Int, Iterable[T]])(implicit n:Numeric[T])。但在这种情况下,Parameter._2.map(n.toDouble).sum/Parameter._2.size可能效率低下,具体取决于Parameter._2的实际运行时类型。您可能希望将其写为折叠。

  2. map来电更改为parsedfile.map(getCountsAndAverages(_))

  3. 当您编写parsedfile.map(getCountsAndAverages)时,会使用eta-expansion将其转换为匿名函数。但似乎是在类型参数推断之前发生的,因此对于任意(x: T) => getCountsAndAverages(x),您最终都会使用T,而这不会编译。 parsedfile.map(getCountsAndAverages[Double])也适用。这是一个尚未解决的问题:https://issues.scala-lang.org/browse/SI-7641