【问题标题】:How to fix this type mismatch?如何解决这种类型不匹配?
【发布时间】:2017-01-02 02:09:42
【问题描述】:

假设我这样定义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]])

为什么 Vector[Vector[Int]] 不匹配 Iterable[Iterable[Int]] ?如何解决这个错误?

【问题讨论】:

    标签: scala collections iterable


    【解决方案1】:

    考虑一下:

    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))
    

    【讨论】:

    • 谢谢,但我想获得更通用的解决方案。越通用越好:)
    • 好的,那么也许你应该定义矩阵类型更“通用”? type Matrix = Iterable[Iterable[Int]]?
    • 可能。但是 Vector[Vector[Int]] 有什么问题?假设我无法更改 Matrix 类型。
    • 没有错,它只是比你想要的(Iterable[A])结果类型的 zipWith 更通用,
    • VectorIterable 更通用?
    猜你喜欢
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多