Last active
March 7, 2022 11:07
-
-
Save katsaii/6720b3e93d97dbe4f6c74e95e8d40247 to your computer and use it in GitHub Desktop.
A simple factorial function written in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(generic_const_exprs)] | |
#![allow(incomplete_features)] | |
trait Factorialable<const N : usize> { | |
fn value() -> usize; | |
} | |
impl Factorialable<0> for () { | |
fn value() -> usize { 1 } | |
} | |
impl<T, const N : usize> Factorialable<N> for (T,) | |
where | |
T : Factorialable<{ N - 1 }> { | |
fn value() -> usize { N * T::value() } | |
} | |
macro_rules! count { | |
() => (0); | |
($x:tt $($xs:tt)*) => (1 + count!($($xs)*)); | |
} | |
macro_rules! number { | |
() => (()); | |
($x:tt $($xs:tt)*) => ((number!($($xs)*),)); | |
} | |
macro_rules! factorial { | |
($($xs:tt)*) => (<number!($($xs)*) as Factorialable::<{count!($($xs)*)}>>::value()); | |
} | |
fn main() { | |
println!("{}", factorial!()); // 0! | |
println!("{}", factorial!(#)); // 1! | |
println!("{}", factorial!(##)); // 2! | |
println!("{}", factorial!(###)); // 3! | |
println!("{}", factorial!(##########)); // 10! | |
println!("{}", factorial!(########## | |
##########)); // 20! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
playground