rustlings
rustlings copied to clipboard
iterators4: solution exists in the documentation
The hint says:
But you can also use ranges and iterators to solve this in rust.
I went to read the documentation on iterators and saw this:
fn factorial(n: u32) -> u32 {
(1..=n).product()
}
assert_eq!(factorial(0), 1);
assert_eq!(factorial(1), 1);
assert_eq!(factorial(5), 120);
Maybe need a more complex exercise without factorial?
I agree, though possibly the exercise was meant to be solved using fold:
pub fn factorial(n: u64) -> u64 {
(1..=n).fold(1, |a, b| a * b)
}
I think an alternative would be to ask that something else is computed, like the product of the squared roots of numbers from 1 to n - that way one wouldn't be able to use just the built-in functions to solve the exercise.
I want to add that this exercise relying on the knowledge of the mathematical concept of factorial is not optimal. As English is my second language and almost all my mathematical education has been in German I had to research at first what factorials are. Not that I regret this experience, but a simple paragraph in the hints explaining factorials might help reducing this potential barrier.
It'd be great to include the algorithm for factorials as comments in the code. I also had to google it. I haven't done a factorial in 25 years.
Maybe it makes sense to use matrix multiplication or a similar approach. The explanation can be put in the documentation so anyone can follow the mathematics behind it. But it is just an idea. If this sounds interesting, I can create an example.