scala - 在scala中使用map和reduce进行矢量积

标签 scala dictionary vector reduce

我正在尝试使用map和reduce函数计算两个向量之间的向量积。

让我们看看 Scala 的 REPL 中发生了什么:

首先我定义了两个长度相同的向量

scala> val v1 = Array(1,4,5,2)
v1: Array[Int] = Array(1, 4, 5, 2)

scala> val v2 = Array (3,5,1,5)
v2: Array[Int] = Array(3, 5, 1, 5)

现在我使用 zip 函数创建一个新数组 vecZip

scala> val vecZip = v1 zip v2
vecZip: Array[(Int, Int)] = Array((1,3), (4,5), (5,1), (2,5))

现在我想应用reduce方法 (计算每个元组的乘积)为此数组的每个元素。 我是这么想的:

val vecToSum = vecZip.map(x=>(List(x).reduce(_*_))) 

我想得到一个列表(vecToSum),其中应用reduce方法来计算总结果。但是我收到此错误:

scala>  val vecToSum = vecZip.map(x=>(List(x).reduce(_*_)))
<console>:10: error: value * is not a member of (Int, Int)
    val vecToSum = vecZip.map(x=>(List(x).reduce(_*_)))
                                                  ^

最佳答案

您只需要调用map并将元组值彼此相乘,如下所示:

val vecToSum = vecZip.map(x => x._1 * x._2) 

vecToSum 是元组列表,因此 x(Int, Int) 的元组。因此,如果您调用 List(x).reduce(...),您将创建一个列表,其唯一值是元组,因此这并不是您真正想要的。

关于scala - 在scala中使用map和reduce进行矢量积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41163713/

相关文章:

java - 无法在 Mongodb 中序列化 LocalDate

c++ - 带 std::vector 的 XTEA 函数

C++/数学GL : Missunderstanding of vector fields

测试 Scala 对象

scala - 使用Scala中的列和索引将数组转换为数据框

eclipse - 为什么 Scala `var` 在 Eclipse 中以红色突出显示

android - 在android中点击一个按钮显示 map

python - 列表理解嵌套在字典中的列表

python - python 中的字典和文件

c++ - c std::vector 一分为二