什么是Kotlin在Rust中“减少”操作的替代方案?

问题描述 投票:-2回答:1

我遇到了这个竞争性编程问题:

  1. nums是一个整数向量(长度n
  2. ops是包含+-(长度n-1)的字符串向量

它可以通过Kotlin中的reduce操作来解决,如下所示:

val op_iter = ops.iterator();
nums.reduce {a, b ->
    when (op_iter.next()) {
        "+" -> a+b
        "-" -> a-b
        else -> throw Exception()
    }
}

reduce被描述为:

从第一个元素开始累积值,并从左到右应用操作到当前累加器值和每个元素。

看起来Rust矢量没有reduce方法。你将如何完成这项任务?

collections functional-programming rust reduce
1个回答
4
投票

Kotlin的reduce将迭代器的第一项作为起点,而Rust的foldtry_fold则允许您指定自定义起点。

这是Kotlin代码的等价物:

let mut it = nums.iter().cloned();
let start = it.next().unwrap();
it.zip(ops.iter()).try_fold(start, |a, (b, op)| match op {
    '+' => Ok(a + b),
    '-' => Ok(a - b),
    _ => Err(()),
})

Playground

或者因为我们从矢量开始,可以索引:

nums[1..]
    .iter()
    .zip(ops.iter())
    .try_fold(nums[0], |a, (b, op)| match op {
        '+' => Ok(a + b),
        '-' => Ok(a - b),
        _ => Err(()),
    });

Playground

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.