Haskell的不寻常问题

use*_*033 4 haskell

我正在从终端运行ghci.

在我的源文件中,我定义了

factorial :: Int -> Int
factorial n = product [1 .. n]
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我得到了结果

factorial 13 = 1932053504

product [1 .. 13] = 6227020800
Run Code Online (Sandbox Code Playgroud)

对于任何小于13的数字,结果是正确的.但是,对于大于或等于12的任何数字,两个结果不一致.

另外如果我定义这个函数递归:

factorial' :: Int -> Int
factorial' 0 = 1
factorial' (n + 1) = (n + 1) * factorial' n
Run Code Online (Sandbox Code Playgroud)

我还是得到的

factorial' 13 = 1932053504
Run Code Online (Sandbox Code Playgroud)

如果您了解这里发生的事情,那将非常有帮助.谢谢

kyl*_*ylc 24

根据以下文件Int:A fixed-precision integer type with at least the range [-2^29 .. 2^29-1].factorial键入您的函数以使用Int溢出的a.现在,如果我们检查第二个答案的类型(从简单地product在GHCi中使用),我们看到它是类型Integer:

Prelude> let a = product [1 .. 13]
Prelude> :t a
a :: Integer
Run Code Online (Sandbox Code Playgroud)

Integer 是无限的,所以能够保持如此大的数字而不会溢出.


Lan*_*dei 6

你有错误的类型:Int环绕某处(可能是2 ^ 31),你需要Integer无限的整数值:

factorial :: Integer -> Integer
factorial n = product [1 .. n]
Run Code Online (Sandbox Code Playgroud)