0 haskell
我尝试使用斐波那契数组来获取黄金比例,这里我定义了一个函数来获取下一个斐波那契对
\nfibstep :: (Num a) => (a,a) -> (a,a)\nfibstep (u,v) = (v,u + v) \nRun Code Online (Sandbox Code Playgroud)\n然后尝试使用 lambda 函数来获得黄金比例
\ngolden_ratio :: (Fractional a) => Integer -> [a] \ngolden_ratio n = map (\\(x,y) -> x/y) (take n (iterate fibstep (0,1)))\nRun Code Online (Sandbox Code Playgroud)\n但它会引发以下错误:
\nRecursions.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\nRun Code Online (Sandbox Code Playgroud)\n当我更改Integer为 时Int,效果很好,有人可以解释一下吗?
golden_ratio :: (Fractional a) => Int -> [a]\ngolden_ratio n = map (\\(x,y) -> x/y) (take n (iterate fibstep (0,1)))\nRun Code Online (Sandbox Code Playgroud)\n
该函数take需要 anInt作为其第一个参数,但您给它一个Integer.
请注意,Int和Integer是不同的类型。前者,Int,用于有限“机器”整数,在现代机器上通常为 64 位。后者Integer适用于任意精度整数,它可以根据需要占用尽可能多的内存。