有没有一种方法可以在Rust中折叠索引? [英] Is there a way to fold with index in Rust?

查看:81
本文介绍了有没有一种方法可以在Rust中折叠索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,如果我有一个数组 a = [1、2、3、4、5] ,并且我想获得每个元素的总和乘以我可以做的索引

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}    

在Rust中是否有惯用的方式来做同样的事情?到目前为止,我已经

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?

推荐答案

您可以将其与

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
}

这篇关于有没有一种方法可以在Rust中折叠索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆