如何在 Rust 中的列表上链接运算符?寻找与 kotlin 代码等效的代码

Mar*_*her 1 chain rust kotlin

我在 kotlin 中有以下代码,我试图找到 rust 等效项,但不理解 rust 中要转换的链接机制。

val windowSize = 2
val result = listOf(1, 2, 3, 4, 5, 6)
  .windowed(windowSize, 1) ; [[1,2], [2,3], [3,4], [4,5], [5,6]]
  .map { it.sum() }        ; [  3,     5,     7,     9,     11]
  .windowed(2, 1)          ; [[3,5], [5,7], [7,9], [9,11] ]
  .count { it[0] < it[1] } ; 4

;; result = 4, as there are 4 sequences that have first number less than 2nd,
;; when considering a sliding window over the original data of 2 items at a time.
Run Code Online (Sandbox Code Playgroud)

它只需要一个整数列表,将它们分成对(但 windowSize 将是一个函数参数),对这些组求和,再次将总和分成对,并找到每个第二个元素比前一个元素大的位置,因此找到递增的值在移动的窗户上。

我正在将其转换为 Rust 等效项,但很难理解如何将操作链接在一起。

到目前为止我得到的是:

let input = [1, 2, 3, 4, 5, 6];
input.windows(2)
    .map(|es| es.iter().sum())
    // what goes here to do the next windows(2) operation?
    .for_each(|x: u32| println!("{}", x));
Run Code Online (Sandbox Code Playgroud)

我可以在地图上“for_each”在迭代中执行操作,但我无法将其与另一个“windows()”分开,或者不知道使这成为可能的魔力。IntelliJ 向我显示地图的返回类型是impl Iterator<Item=?>

有人可以启发我吗?我是 Rust 的绝对初学者,所以这无疑与我对整个语言的理解有关。

Aid*_*en4 5

Itertools箱提供了一种相当方便的方法来使用该方法执行此tuple_windows操作。

use itertools::Itertools; 

fn main() {
    let input = [1i32, 2, 3, 4, 5, 6];
    let output: usize = input
        .windows(2)
        .map(|es| es.iter().sum::<i32>())
        .tuple_windows()
        .filter(|(a, b)| a < b)
        .count();
    println!("{}", output);
}
Run Code Online (Sandbox Code Playgroud)

操场

标准库没有办法在不首先收集迭代器的情况下执行此操作,这需要两次遍历数据。