Unusual issue with Haskell

I am running ghci from Terminal.

In the source file I defined

factorial :: Int -> Int factorial n = product [1 .. n] 

When I run this, I get the result

 factorial 13 = 1932053504 product [1 .. 13] = 6227020800 

For any number less than 13, the result is correct. However, for any number greater than or equal to 12, the two results are not consistent.

Also, if I define this function recursively:

 factorial' :: Int -> Int factorial' 0 = 1 factorial' (n + 1) = (n + 1) * factorial' n 

I'm still getting

 factorial' 13 = 1932053504 

If you understand what is happening here, that would be very helpful. Thanks

+4
source share
2 answers

According to the documentation for Int : A fixed-precision integer type with at least the range [-2^29 .. 2^29-1] . Your factorial function is printed to use a Int , which is crowded. Now, if we check the type of the second answer (just using product in GHCi), we see that it is of type Integer :

 Prelude> let a = product [1 .. 13] Prelude> :ta a :: Integer 

Integer unlimited and therefore able to hold such a large amount without overflow.

+24
source

You have the wrong types: Int around somewhere (maybe 2 ^ 31), you need Integer for unlimited integer values:

 factorial :: Integer -> Integer factorial n = product [1 .. n] 
+6
source

All Articles