Haskell 中的类型混淆:无法将预期类型“Int”与实际类型“Integer”匹配

0 haskell

我尝试使用斐波那契数组来获取黄金比例,这里我定义了一个函数来获取下一个斐波那契对

\n
fibstep :: (Num a) => (a,a) -> (a,a)\nfibstep (u,v) = (v,u + v)  \n
Run Code Online (Sandbox Code Playgroud)\n

然后尝试使用 lambda 函数来获得黄金比例

\n
golden_ratio :: (Fractional a) => Integer -> [a] \ngolden_ratio n = map (\\(x,y) -> x/y) (take n (iterate fibstep (0,1)))\n
Run Code Online (Sandbox Code Playgroud)\n

但它会引发以下错误:

\n
Recursions.hs:68:44: error:\n    \xe2\x80\xa2 Couldn\'t match expected type \xe2\x80\x98Int\xe2\x80\x99 with actual type \xe2\x80\x98Integer\xe2\x80\x99\n    \xe2\x80\xa2 In the first argument of \xe2\x80\x98take\xe2\x80\x99, namely \xe2\x80\x98n\xe2\x80\x99\n      In the second argument of \xe2\x80\x98map\xe2\x80\x99, namely\n        \xe2\x80\x98(take n (iterate fibstep (0, 1)))\xe2\x80\x99\n      In the expression:\n        map (\\ (x, y) -> x / y) (take n (iterate fibstep (0, 1)))\n   |\n68 | golden_ratio n = map (\\(x,y) -> x/y) (take n (iterate fibstep (0,1)))\n   |                                            ^\nFailed, no modules loaded\n
Run Code Online (Sandbox Code Playgroud)\n

当我更改Integer为 时Int,效果很好,有人可以解释一下吗?

\n
golden_ratio :: (Fractional a) => Int -> [a]\ngolden_ratio n = map (\\(x,y) -> x/y) (take n (iterate fibstep (0,1)))\n
Run Code Online (Sandbox Code Playgroud)\n

Nou*_*are 7

该函数take需要 anInt作为其第一个参数,但您给它一个Integer.

请注意,IntInteger是不同的类型。前者,Int,用于有限“机器”整数,在现代机器上通常为 64 位。后者Integer适用于任意精度整数,它可以根据需要占用尽可能多的内存。