Scala 如何修复此类型不匹配?
假设我这样定义Scala 如何修复此类型不匹配?,scala,collections,iterable,Scala,Collections,Iterable,假设我这样定义zipWith: def zipWith[A](f:(A, A) => A)(xs:Iterable[A], ys:Iterable[A]): Iterable[A] = (xs, ys).zipped map f 现在我想用它来压缩矩阵: type Matrix = Vector[Vector[Int]] val zipMatrix: ((Int, Int) => Int) => Matrix => Matrix => Matrix = f
zipWith
:
def zipWith[A](f:(A, A) => A)(xs:Iterable[A], ys:Iterable[A]): Iterable[A] =
(xs, ys).zipped map f
现在我想用它来压缩矩阵:
type Matrix = Vector[Vector[Int]]
val zipMatrix: ((Int, Int) => Int) => Matrix => Matrix => Matrix = f =>
zipWith(zipWith(f))
但是我犯了一个错误:
<console>:15: error: type mismatch;
found : (Iterable[Iterable[Int]], Iterable[Iterable[Int]]) => Iterable[Iterable[Int]]
required: Matrix => (Matrix => Matrix)
(which expands to) scala.collection.immutable.Vector[Vector[Int]] => (scala.collection.immutable.Vector[Vector[Int]] => scala.collection.immutable.Vector[Vector[Int]])
:15:错误:类型不匹配;
发现:(Iterable[Iterable[Int]],Iterable[Iterable[Int]])=>Iterable[Iterable[Int]]
必需:矩阵=>(矩阵=>矩阵)
(扩展为)scala.collection.immutable.Vector[Vector[Int]]=>(scala.collection.immutable.Vector[Vector[Int]=>scala.collection.immutable.Vector[Vector[Int]])
为什么Vector[Vector[Int]]
不匹配Iterable[Iterable[Int]]
?如何修复此错误?请考虑以下问题:
def zipWith[A] (f:(A => A => A))(xs:Vector[A])(ys:Vector[A]): Vector[A] =
(xs, ys).zipped.map {case (x, y) => f (x)(y)}
val zipMatrix: (Int => Int => Int) => (Matrix => Matrix => Matrix) = f =>
zipWith(zipWith(f))
谢谢,但我想得到一个更通用的解决方案。越通用越好:)好的,那么也许你应该定义更“通用”的矩阵类型?类型矩阵=Iterable[Iterable[Int]]?可能。但是向量[Vector[Int]有什么问题吗?假设我无法更改
矩阵
类型。没有错,它只是比zipWith的所需(Iterable[A])结果类型更一般,向量
比Iterable
更一般?