如何使用迭代器和范围创建阶乘的非递归计算?

dom*_*mbo 4 iterator non-recursive rust

我遇到了一个不断困扰我的 Rustlings 练习:

pub fn factorial(num: u64) -> u64 {
    // Complete this function to return factorial of num
    // Do not use:
    // - return
    // For extra fun don't use:
    // - imperative style loops (for, while)
    // - additional variables
    // For the most fun don't use:
    // - recursion
    // Execute `rustlings hint iterators4` for hints.
}
Run Code Online (Sandbox Code Playgroud)

解决方案的提示告诉我...

在命令式语言中,您可能会编写一个 for 循环来迭代将值乘以可变变量。或者,您可以使用递归和匹配子句编写更具功能性的代码。但是你也可以使用范围和迭代器来解决这个问题。

我试过这种方法,但我遗漏了一些东西:

if num > 1 {
    (2..=num).map(|n| n * ( n - 1 ) ??? ).???
} else {
    1
}
Run Code Online (Sandbox Code Playgroud)

我必须使用类似的东西.take_while而不是if吗?

She*_*ter 15

阶乘定义为从起始数到 1 的所有数的乘积。我们使用该定义和Iterator::product

fn factorial(num: u64) -> u64 {
    (1..=num).product()
}
Run Code Online (Sandbox Code Playgroud)

如果你看一下实施Product为整数,你会看到它使用Iterator::fold引擎盖下:

impl Product for $a {
    fn product<I: Iterator<Item=Self>>(iter: I) -> Self {
        iter.fold($one, Mul::mul)
    }
}
Run Code Online (Sandbox Code Playgroud)

你可以自己硬编码:

fn factorial(num: u64) -> u64 {
    (1..=num).fold(1, |acc, v| acc * v)
}
Run Code Online (Sandbox Code Playgroud)

也可以看看:

  • 哇!我怎么错过了那个??非常感谢 (2认同)