Is there a way to fold with index in Rust?

一曲冷凌霜 提交于 2021-01-26 05:58:52

问题


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?


回答1:


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
}


来源:https://stackoverflow.com/questions/41091641/is-there-a-way-to-fold-with-index-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!