15

In Ruby, if I had an array a = [1, 2, 3, 4, 5] and I wanted to get the sum of each element times its index I could do

a.each.with_index.inject(0) {|s,(i,j)| s + i*j}    

Is there an idiomatic way to do the same thing in Rust? So far, I have

a.into_iter().fold(0, |x, i| x + i)

But that doesn't account for the index, and I can't really figure out a way to get it to account for the index. Is this possible and if so, how?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61

1 Answers1

36

You can chain it with enumerate:

fn main() {
    let a = [1, 2, 3, 4, 5];
    let b = a.into_iter().enumerate().fold(0, |s, (i, j)| s + i * j);

    println!("{:?}", b); // Prints 40
}
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138