Clement Decker
Clement Decker

Reputation: 137

Issue With Factorial Function

I have been trying to write a program which prints out a factorial without actually using recursion.

Here is the code

let factorial x = 
   let mutable n = x
       while n > 0 do
             let result = n*(n-1)
             n <- (n-1)
       result

The issue is that when I try to run the code it tells me that the expected result is a unit, whereas the input is clearly an integer, which obviously results in an error. However, I have checked all my variables and the compiler interprets them as integers, so what is the issue

Upvotes: 0

Views: 168

Answers (1)

Luiso
Luiso

Reputation: 4113

There are several issues with your code here, you must keep in mind indentation in f# is very important, for you want to do your code should be:

let factorial x =
   let mutable n = x
   let mutable result = 1
   while n > 0 do
       result <- n * (n-1)
       n <- (n - 1)
   result

You were declaring the result variable inside the while scope and returning it outside it. Your code however is incorrect, I took the liberty of modify it, here what I did:

let factorial x =
    let mutable n = x
    let mutable result = 1
    while n >= 1 do
       result <- result * n
       n <- (n - 1)
    result

Upvotes: 3

Related Questions