Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to fold with index in Rust?

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?

like image 309
Eli Sadoff Avatar asked Dec 11 '16 22:12

Eli Sadoff


1 Answers

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
}
like image 138
Simon Whitehead Avatar answered Nov 19 '22 15:11

Simon Whitehead