GHC type error which I do not understand

孤人 提交于 2021-01-27 07:53:02

问题


I am teaching myself Haskell.

I want to write a function that recursively finds the first number that has an integer square root and is smaller than a starting number.

It looks like this:

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)

But GHC complains:

No instance for (RealFrac Int) arising from a use of `floor' at ...

However, if I type the following into GHCi, it happily compiles it:

 fromInteger(floor(sqrt(4))) == (sqrt 4)

My question is: Why am I getting a type error from an expression that compiles successfully in GHCi?


回答1:


Ok, I figured it out.

The difference is that the constant "4" is overloaded, so interactively sqrt(4) is getting the square root of the Float 4

However my function declares x as an Int, therefore I needed to add a fromIntegral to the calls to sqrt, so that they would work.

Changing the middle guard to the following did the trick:

| fromIntegral(floor(sqrt(fromIntegral(x)))) == (sqrt(fromIntegral(x))) = x


来源:https://stackoverflow.com/questions/1304495/ghc-type-error-which-i-do-not-understand

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!