我遇到了一个不断困扰我的 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.
}
解决方案的提示告诉我...
In an imperative language you might write a for loop to iterate through multiply the values into a mutable variable. Or you might write code more functionally with recursion and a match clause. But you can also use ranges and iterators to solve this in rust.
我试过这种方法,但我错过了一些东西:
if num > 1 {
(2..=num).map(|n| n * ( n - 1 ) ??? ).???
} else {
1
}
我必须使用类似
.take_while
的东西吗?而不是 if
?
最佳答案
阶乘定义为从起始数到 1 的所有数的乘积。我们使用该定义和 Iterator::product
:
fn factorial(num: u64) -> u64 {
(1..=num).product()
}
如果你看 the implementation的
Product
对于整数,您会看到它使用 Iterator::fold
引擎盖下:impl Product for $a { fn product<I: Iterator<Item=Self>>(iter: I) -> Self { iter.fold($one, Mul::mul) } }
你可以自己硬编码:
fn factorial(num: u64) -> u64 {
(1..=num).fold(1, |acc, v| acc * v)
}
也可以看看:
关于rust - 如何使用迭代器和范围创建阶乘的非递归计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60835646/