moar doc
cargo devel CI / cargo CI (push) Successful in 6m21s Details

This commit is contained in:
Christoph J. Scherr 2024-09-10 15:39:42 +02:00
parent 88dd0f7d9c
commit 73193b430d
Signed by: cscherrNT
GPG Key ID: 8E2B45BC51A27EA7
1 changed files with 30 additions and 7 deletions

View File

@ -1,15 +1,37 @@
fn main() { //! How to calc the factorial n! with just a single line, no imperative style loops, no vars.
//!
//! See [factorial] for how it's done and [myprod] for how it works under the hood.
/// Just so there is something to be ran :)
pub fn main() {
let x = 7; let x = 7;
println!("{}", factorial(x)); println!("{}", factorial(x));
} }
fn factorial(n: u128) -> u128 { /// Return the factorial of `n` which is defined as `1 * 2 * 3 * … * n`.
/// <https://en.wikipedia.org/wiki/Factorial>
///
/// Task from rustlings
///
/// Do not use:
/// - early returns (using the `return` keyword explicitly)
///
/// Try not to use:
/// - imperative style loops (for/while)
/// - additional variables
///
/// For an extra challenge, don't use:
/// - recursion
pub fn factorial(n: u128) -> u128 {
(1..n + 1).product() (1..n + 1).product()
} }
// does the same as product from the stdlib /// Does the same as [std::iter::Iterator::product] from the stdlib.
///
/// The code for [Iterator::product] can be hard to find because it is implemented with a trait and
/// then a macro. Here is a simple version of it.
#[allow(dead_code)] #[allow(dead_code)]
fn myprod<T>(iter: T) -> u128 pub fn myprod<T>(iter: T) -> u128
where where
T: Iterator<Item = u128>, T: Iterator<Item = u128>,
{ {
@ -17,17 +39,18 @@ where
iter.fold(1, |acc, v| acc * v) iter.fold(1, |acc, v| acc * v)
} }
/// That's just my unit tests to confirm it works
#[cfg(test)] #[cfg(test)]
mod tests { pub mod tests {
use super::*; use super::*;
#[test] #[test]
fn works() { pub fn works() {
assert_eq!(factorial(7), 5040); assert_eq!(factorial(7), 5040);
assert_eq!(factorial(9), 362880); assert_eq!(factorial(9), 362880);
} }
#[test] #[test]
fn myprod_same_as_real() { pub fn myprod_same_as_real() {
assert_eq!((1..5).product::<u128>(), myprod(1..5)); assert_eq!((1..5).product::<u128>(), myprod(1..5));
assert_eq!((1..30).product::<u128>(), myprod(1..30)); assert_eq!((1..30).product::<u128>(), myprod(1..30));
// assert_eq!((1..50).product::<u128>(), myprod(1..50)); // u128 overflows here // assert_eq!((1..50).product::<u128>(), myprod(1..50)); // u128 overflows here