0

I'm trying to multiply each element from two different arrays. I mean, I have array1 = [i1 , i2] and array2 = [j1, j2] so I need to do (i1 * j1) + (i2 * j2). How can I approach this in Rust? I've been researching in The Book and saw some methods that possibly could help: map and fold. But I'm a bit lost. Thanks in advance!

fn sum_product(a: [f32], b: [f32]) -> [f32] {
    unimplemented!();
}

fn main() {
    let a: [f32; 2] = [2.0, 3.0];
    let b: [f32; 2] = [0.0, 1.0];
}
Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Luisvgs
  • 39
  • 6
  • 2
    Note that French Boiethios' answer uses [slices](https://doc.rust-lang.org/book/ch04-03-slices.html) as the arguments to `sum_product` - you cannot simply specify `[f32]` as a type, as all array types must also carry a size (like the `[f32; 2]` does). Slices, however, are a view into a collection (whether that be an array, a vec, etc), and do not need an explicit size. – Joe Clay Jul 08 '19 at 09:29
  • 1
    Also, unless you absolutely need to, avoid specifying explicit types on variables like `a` and `b`. The compiler can and will work them out for you, which saves a lot of typing :) – Joe Clay Jul 08 '19 at 09:31
  • See also [How can I improve the performance of element-wise multiplication in Rust?](https://stackoverflow.com/q/54603226/155423); [How do I add two Rust arrays element-wise?](https://stackoverflow.com/q/41207666/155423). – Shepmaster Jul 08 '19 at 12:23

1 Answers1

4

With a mix of zip and map:

fn sum_product(a: &[f32], b: &[f32]) -> f32 {
    a.iter()
        .zip(b.iter())
        .map(|(a, b)| a * b)
        .sum()
}

fn main() {
    let a = [2.0, 3.0];
    let b = [0.0, 1.0];

    assert_eq!(3.0, sum_product(&a, &b));
}
Boiethios
  • 38,438
  • 19
  • 134
  • 183