9

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)

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ACC
  • 2,488
  • 6
  • 35
  • 61

1 Answers1

15

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
})
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
mdup
  • 7,889
  • 3
  • 32
  • 34