1. 55
    Rustlings iterators4: Implementing Factorial with Iterators
    2m 12s

Rustlings iterators4: Implementing Factorial with Iterators

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

README for this exercise.

Chris Biscardi: [0:00] In iterators4, rustlings wants us to implement factorial. In case you're unaware of what factorial is, factorial, when passed a number, will multiply that number by all of the numbers preceding it down to one.

[0:12] If we pass in 1, it multiplies by itself. If we pass in 2, it multiplies by 1. If we pass in 4, it's 4 times 3 times 2 times 1, which is 24.

[0:22] Now, there are plenty of explanations how to implement a factorial() function on the Internet in other languages. This particular exercise wants us to not use the return keyword, imperative style loops, additional variables, and also not recursion.

[0:38] Perhaps, obviously, since we're in the iterators exercise, we're going to use an iterator for this. We'll start by using a range to iterate from the number one all the way up because it doesn't matter what order we do this in. It doesn't matter what order our ranges in because multiplication will work the same across all of them anyway.

[0:55] Note that in this range, we're using an equal sign on the end of the two dots, which means that this number is going to be included in our range, whereas normally, it would not. Now we can use a fold on top of this range.

[1:07] We have a range of numbers. We fold over that range. We set our accumulator to one. We get an accumulator and a value in our anonymous function. We multiply the two together, which results in this entire list getting multiplied one by one against each item in the list.

[1:21] Now this works, but it's also not the most rusty way to do this. The most rusty way to do this, including iterators, is to use product. Now, we've used an inclusive range from one to our number, and called product() on it.

[1:36] Product is a trait and it's a trait to represent types that can be created by multiplying elements of an iterator. By creating a range in our iterator, we can then call product() on that range. If we scroll down, there's an implementation of product for us64s. Use64s are the numbers we were given to work with.

[1:55] If we look at the implementation of product in the Rust source code, we can see that product uses fold under the hood with multiplication. This is very similar to what we wrote the first time when we wrote out the fold manually.

[2:06] It's nice to know that these traits exist because they can do various things for us and shorten our code by great amounts.