ACC
ACC

Reputation: 2560

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

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)

Upvotes: 9

Views: 9041

Answers (1)

mdup
mdup

Reputation: 8529

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:


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

Upvotes: 18

Related Questions