我编写了一个函数来接受以下类型的值: (1, Array(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))
}
Run Code Online (Sandbox Code Playgroud)
元组的第一个参数是一个数字,然后是它在文件中出现的次数的数组。
它适用于示例案例,但是我正在读取一个文本文件,该文件的数据格式与此功能工作所需的格式相同。我正在使用“地图”操作调用此函数:
parsedfile.map(getCountsAndAverages)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
?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.
Run Code Online (Sandbox Code Playgroud)
我将不胜感激任何帮助或建议
您可以使用以下任何一种语法
def foo[T](x: T)(implicit n: Numeric[T]) = n.toDouble(x)
Run Code Online (Sandbox Code Playgroud)
或者
def foo[T : Numeric](x: T) = implicitly[Numeric[T]].toDouble(x)
Run Code Online (Sandbox Code Playgroud)
在你的情况下
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))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1979 次 |
| 最近记录: |