0

我有两种解决方案,但一种无法编译,我认为另一种可能会更好:

object Foo extends App {
     val vectors = List(List(1,2,3), List(2,2,3), List(1,2,2)) //just a stupid example

     //transposing
     println("vectors = " + vectors.transpose.map (_.sum)) //it prints vectors = List(4, 6, 8)

     //folding
     vectors.reduce {
        case (a, b) => (a zip b) map {
           case (x, y) => x + y
        }
     } //compiler says: missing parameter type for exp. function; arg. types must be fully known
} 
4

2 回答 2

5

reduce接受一个Function2参数,但你给了它一个PartialFunction.

vectors reduce { (a, b) => (a zip b) map { case (x, y) => x+y } }

编辑:我的代码有效,但@sschaef 指出我的解释是错误的:由于类型推断的限制,davips 的代码无法编译。请参阅使用 .toSet 进行的 Set 上的类型推断失败?

于 2013-11-08T05:11:12.087 回答
1
val vectors = List(List(1,2,3), List(2,2,3), List(1,2,2))

implicit class VectorizedOps[T : Numeric](vec: List[T]) {
  private val numeric = implicitly[Numeric[T]]
  def +(other: List[T]) = (vec zip other).map { case (x, y) => numeric.plus(x, y) }
}

val sum = vectors.reduce( _ + _ )

也许不是更快但更惯用

于 2013-11-08T05:51:39.327 回答