indexing - 有没有办法在 Rust 中用索引折叠?

标签 indexing rust fold

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

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

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

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

但这并没有考虑到索引,而且我真的想不出一种方法让它考虑到索引。这可能吗?如果可能,怎么做?

最佳答案

你可以用 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
}

关于indexing - 有没有办法在 Rust 中用索引折叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091641/

相关文章:

mysql - 提高查询整体性能

sql - 如何将索引与数据分开存储在Azure上?

python - 无法正确索引 NUMPY 数组的列表

rust - 如何调用使用自定义实现特征的方法?

为有限列表使用 foldl' 实现 concatMap 的性能提升?

haskell - 这种折叠和迭代的模式是什么?

performance - Postgresql - 使用索引过滤表中超过 1 亿行的行

rust - 如何在 Rust 中将 read_line() 的结果作为字符串获取?

postgresql - 当字段类型在编译时未知时,如何使用tokio-postgres枚举列?

functional-programming - Octave 中的折叠功能