From 77c6ac48684a384630d882eae51a6327230ed415 Mon Sep 17 00:00:00 2001 From: Rock070 Date: Thu, 11 Jan 2024 01:32:25 +0800 Subject: [PATCH] Refactor factorial function using custom iterator --- exercises/18_iterators/iterators4.rs | 30 +++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/exercises/18_iterators/iterators4.rs b/exercises/18_iterators/iterators4.rs index 79e1692b..7694069a 100644 --- a/exercises/18_iterators/iterators4.rs +++ b/exercises/18_iterators/iterators4.rs @@ -3,7 +3,7 @@ // Execute `rustlings hint iterators4` or use the `hint` watch subcommand for a // hint. -// I AM NOT DONE +// NOTE: 難 pub fn factorial(num: u64) -> u64 { // Complete this function to return the factorial of num @@ -15,6 +15,34 @@ pub fn factorial(num: u64) -> u64 { // For an extra challenge, don't use: // - recursion // Execute `rustlings hint iterators4` for hints. + + struct Num { + current: u64, + end: u64 + } + + impl Iterator for Num { + type Item = u64; + fn next(&mut self) -> Option{ + if self.current > self.end { + return None; + } + + let num = self.current; + self.current += 1; + + Some(num) + } + } + + let num_iter = Num { + current: 1, + end: num + }; + + let total = num_iter.fold(1, |acc, x| acc * x); + + total } #[cfg(test)]