From 24c91a4a0b987a6889f6803e5390b79c4762418b Mon Sep 17 00:00:00 2001 From: Alexander Launi Date: Sat, 21 Mar 2020 17:20:03 -0400 Subject: [PATCH] Implement factorial using generic mathematics --- 03_recursion/rust/03_factorial/Cargo.toml | 1 + 03_recursion/rust/03_factorial/src/main.rs | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/03_recursion/rust/03_factorial/Cargo.toml b/03_recursion/rust/03_factorial/Cargo.toml index cec2d7e..223a6ec 100644 --- a/03_recursion/rust/03_factorial/Cargo.toml +++ b/03_recursion/rust/03_factorial/Cargo.toml @@ -7,3 +7,4 @@ edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +num-traits = "0.2" diff --git a/03_recursion/rust/03_factorial/src/main.rs b/03_recursion/rust/03_factorial/src/main.rs index b9c7425..5ebd5b2 100644 --- a/03_recursion/rust/03_factorial/src/main.rs +++ b/03_recursion/rust/03_factorial/src/main.rs @@ -1,9 +1,17 @@ -fn fact(x: u32) -> u32 { - if x == 1 { - return 1; +use std::ops::Sub; +use std::fmt::Display; +use num_traits::identities::One; + +fn fact + Copy + Display>(x: T) -> T { + if x < T::one() { + panic!("Invalid number: {}", x); } - return x * fact(x - 1); + if x.is_one() { + return T::one(); + } + + return x * fact(x - T::one()); } fn main() {