数值的标量总和列表 [英] scala sum list of numeric values
本文介绍了数值的标量总和列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要一个通用函数来对列表中的值求和.
I want a generic function to sum values in a list.
以下代码无法编译:
def sum[T : Numeric](x: List[T]): T = {
if(x.isEmpty) 0
else x.head + sum(x.tail)
}
编译错误为:
error: type mismatch;
[INFO] found : Int(0)
[INFO] required: T
[INFO] if(x.isEmpty) 0
推荐答案
这个错误告诉你你已经指定了返回类型是 T
,但你总是返回一个 0
表示一个空列表,它是一个 Int
.如果传入的列表包含其他内容,即 T
是 Double
或某些自定义类型怎么办?试试这个:
This error is telling you that you've specified the return type is T
, but you're always returning a 0
for an empty list, which is an Int
. What if the passed-in list contains something else, i.e. T
is Double
or some custom type? Try this:
if(x.isEmpty) implicitly[Numeric[T]].zero
完整的工作方法:
def sum[T : Numeric](x: List[T]): T = {
if (x.isEmpty) implicitly[Numeric[T]].zero
else implicitly[Numeric[T]].plus(x.head, sum(x.tail))
}
或者:
def sum[T](x: List[T])(implicit num: Numeric[T]): T = {
import num._
if (x.isEmpty) zero
else x.head + sum(x.tail)
}
这篇关于数值的标量总和列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文