1

With the following function:
factorial :: Int -> Int
factorial n = product [1..n]

The correct value is returned with parameters less than 21. For example: factorial 20 returns 2432902008176640000, but factorial 21 returns -4249290049419214848 which isn't correct even if the value wasn't negative.

I know that with these size numbers Integer should have been utilized, but where specifically is the error occurring here and why?

Grant
  • 891
  • 1
  • 9
  • 15

1 Answers1

5

Int in Haskell is a fixed-precision representation of the integers with a finite range. As is the case with most fixed-precision integer representations, an arithmetic operation that would create an integer that is too large or small to be represented (which is called an integer overflow, as mentioned by Mephy) will have its result wrapped by truncating it to its least significant bits. For example:

λ> maxBound + 1 :: Int
-9223372036854775808

λ> (maxBound + 1 :: Int) == minBound
True
Rein Henrichs
  • 15,437
  • 1
  • 45
  • 55