在Scala列表中添加所有向量(在数学意义上)的最快惯用方法是什么?

0 scala list

我有两个解决方案,但一个不编译,另一个,我认为,可能更好:

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
} 
Run Code Online (Sandbox Code Playgroud)

Chr*_*tin 5

reduce接受一个Function2论点,但你已经给了它一个PartialFunction.

vectors reduce { (a, b) => (a zip b) map { case (x, y) => x+y } }
Run Code Online (Sandbox Code Playgroud)

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

  • 不是"PartialFunction",他只使用了Pattern Matching. (2认同)