[英]Scala: type mismatch error
I am new to scala and I am practicing it with k-means algorithm following the tutorial from k-means 我是新来Scala和我与K-means算法练了从教程以下k均值
I am confused by this part of this tutorial: 我对本教程的这一部分感到困惑:
var newCentroids = pointsGroup.mapValues(ps => average(ps)).collectAsMap()
This causes a type mismatch error because function average
needs a Seq
, while we give it an Iterable
. 这会导致类型不匹配错误,因为函数average
需要一个Seq
,而我们给它一个Iterable
。 How can I fix this? 我怎样才能解决这个问题? What caused this error? 是什么导致此错误?
Well Seq
is a sub-type of Iterable
but not vice-versa, so it is not possible to convert these types in the type systems. Seq
是Iterable
的子类型,但反之亦然,因此不能在类型系统中转换这些类型。
There is an explicit conversion available by writing average(ps.toSeq)
. 通过编写average(ps.toSeq)
可以进行显式转换。 This conversion will iterate the Iterable
and collect the items into a Seq
. 此转换将迭代Iterable
并将项目收集到Seq
。
We could easily replace Seq
with Iterable
in provided solution for average
function: 在提供的average
功能解决方案中,我们可以轻松地用Iterable
替换Seq
:
def average(ps: Iterable[Vector]) : Vector = {
val numVectors = ps.size
var out = new Vector(ps.head.elements)
ps foreach ( out += _)
out / numVectors
}
Or even in constant space: 甚至在恒定的空间中:
def average(ps: Iterable[Vector]): Vector = {
val numVectors = ps.size
val vSize = ps.head.elements.length
def element(index: Int): Double = ps.map(_(index)).sum / numVectors
new Vector(0 until vSize map element toArray)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.