Search⌘ K

Solution Review: The Factorial of a Number (Loops)

Explore how to implement the factorial function in ReasonML by using while loops. Learn to manage iterative multiplication and control loop execution to calculate factorial values effectively.

We'll cover the following...

Solution

Reason
let fact = (n: int) => {
/* Check if n is 0 or 1 */
if (n == 0 || n == 1) {
1;
}
else {
let i = ref(n);
let prod = ref(1); /* Give the product a default value of 1 */
while (i^ > 1) {
prod := prod^ * i^; /* Multiple prod with i in each iteration */
i := i^ - 1; /* Decrement i until it reaches 1 */
};
prod^;
};
};
Js.log(fact(3));

Explanation

Initially, we handle the simplest values for n, 0 ...