如何计算两个 Rust 数组/切片/向量的点积? [英] How do I compute the dot product of two Rust arrays / slices / vectors?
问题描述
我试图找到两个向量的点积:
I'm trying to find the dot product of two vectors:
fn main() {
let a = vec![1, 2, 3, 4];
let b = a.clone();
let r = a.iter().zip(b.iter()).map(|x, y| Some(x, y) => x * y).sum();
println!("{}", r);
}
这失败了
error: expected one of `)`, `,`, `.`, `?`, or an operator, found `=>`
--> src/main.rs:4:58
|
4 | let r = a.iter().zip(b.iter()).map(|x, y| Some(x, y) => x * y).sum();
| ^^ expected one of `)`, `,`, `.`, `?`, or an operator here
我也试过这些,都失败了:
I've also tried these, all of which failed:
let r = a.iter().zip(b.iter()).map(|x, y| => x * y).sum();
let r = a.iter().zip(b.iter()).map(Some(x, y) => x * y).sum();
这样做的正确方法是什么?
What is the correct way of doing this?
推荐答案
在 map()
中,您不必处理迭代器返回 Option
的事实代码>.这由 map()
处理.您需要提供一个函数,该函数采用两个借用值的元组.您的第二次尝试已接近尾声,但语法错误.这是正确的:
In map()
, you don't have to deal with the fact that the iterator returns an Option
. This is taken care of by map()
. You need to supply a function taking the tuple of both borrowed values. You were close with your second try, but with the wrong syntax. This is the right one:
a.iter().zip(b.iter()).map(|(x, y)| x * y).sum()
您的最终程序需要在 r
上添加注释:
Your final program required an annotation on r
:
fn main() {
let a = vec![1, 2, 3, 4];
let b = a.clone();
let r: i32 = a.iter().zip(b.iter()).map(|(x, y)| x * y).sum();
println!("{}", r);
}
另见:
关于传递给 map
的闭包的更多信息:我写了 ...map(|(x, y)| x * y)
,但是为了更复杂您需要使用 {}
分隔闭包主体的操作:
More info on the closure passed to map
: I have written ...map(|(x, y)| x * y)
, but for more complicated operations you would need to delimit the closure body with {}
:
.map(|(x, y)| {
do_something();
x * y
})
这篇关于如何计算两个 Rust 数组/切片/向量的点积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!