Appearance
迭代器4: exercises/iterators/iterators4.rs
题目
rust
// iterators4.rs
//
// Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
pub fn factorial(num: u64) -> u64 {
// Complete this function to return the factorial of num
// Do not use:
// - return
// Try not to use:
// - imperative style loops (for, while)
// - additional variables
// For an extra challenge, don't use:
// - recursion
// Execute `rustlings hint iterators4` for hints.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn factorial_of_0() {
assert_eq!(1, factorial(0));
}
#[test]
fn factorial_of_1() {
assert_eq!(1, factorial(1));
}
#[test]
fn factorial_of_2() {
assert_eq!(2, factorial(2));
}
#[test]
fn factorial_of_4() {
assert_eq!(24, factorial(4));
}
}
我们需要完成factorial
函数的代码,以返回num
的阶乘,要求:
不使用:
- return
尽量不要使用:
- 循环表达式(for, while)
- 附加变量
对于额外的挑战,不要使用:
- 递归
题目解析
在命令式语言中,您可以编写一个for循环来更新可变变量。或者您可以使用递归和match子句来编写代码。但是在Rust中,您可以使用另一种函数方法,使用range和迭代器来优雅的进行阶乘运算。
一共有两种方式:
第一中使用fold
方法,这个方法通过应用操作将每个元素 fold 到一个累加器中,返回最终结果。
rust
pub fn factorial(num: u64) -> u64 {
(1..=num).fold(1, |acc, v| acc * v)
}
第二种方式,使用product
,这个方法的作用是遍历整个迭代器,使所有元素相乘。
rust
pub fn factorial(num: u64) -> u64 {
(1..=num).product()
}