GHC type error I don't understand

I teach myself Haskell.

I want to write a function that recursively finds the first number that has an integer square root and less than the 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 the GHC complains:

There is no instance for (RealFrac Int) resulting from using `floor 'at ...

However, if I introduce the following into GHCi, he will happily compile 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?

+4
source share
1 answer

Ok, I figured it out.

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

However, my function declares x as Int , so I need to add fromIntegral to sqrt calls so that they work.

Change the middle guard to the following: trick:

 | fromIntegral(floor(sqrt(fromIntegral(x)))) == (sqrt(fromIntegral(x))) = x 
+9
source

All Articles