Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compute the dot product of two Rust arrays / slices / vectors?

Tags:

rust

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

This fails with

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?

(Playground)

like image 762
Abhishek Chanda Avatar asked May 24 '15 11:05

Abhishek Chanda


1 Answers

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

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

(Playground)

See also:

  • Why can't Rust infer the resulting type of Iterator::sum?
  • How do I sum a vector using fold?

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
})
like image 121
mdup Avatar answered Nov 10 '22 10:11

mdup