我正在自学 Haskell。
我想编写一个函数,递归地找到第一个具有整数平方根且小于起始数字的数字。
它看起来像这样:
findFirstSquare :: Int -> Int
findFirstSquare x
| x <= 0 = error "This function only works for 1 or above"
| fromInteger(floor(sqrt(x))) == (sqrt x) = x
| otherwise = intSqrt(x - 1)
但 GHC 提示:
No instance for (RealFrac Int) arising from a use of `floor' at ...
但是,如果我在 GHCi 中键入以下内容,它会很高兴地编译它:
fromInteger(floor(sqrt(4))) == (sqrt 4)
我的问题是:为什么我会从在 GHCi 中成功编译的表达式中收到类型错误?
最佳答案
好的,我想通了。
不同之处在于常量“4”被重载,所以交互式 sqrt(4) 得到 的平方根 float 4
但是我的函数将 x 声明为 国际 ,因此我需要在对 sqrt 的调用中添加一个 fromIntegral,以便它们可以工作。
将中间后卫更改为以下内容即可解决问题:
| fromIntegral(floor(sqrt(fromIntegral(x)))) == (sqrt(fromIntegral(x))) = x
关于haskell - 我不明白的 GHC 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1304495/