Search code examples
haskellsqrtfloor

Joint use of floor and sqrt in Haskell


I want my function to read in an integer and return the square root rounded down to the nearest integer. This is what I've tried:

roundSqrt :: Int -> Int
roundSqrt x = floor (sqrt x)  

The error I get is, "Could not deduce (Floating a) arising from a use of -sqrt'", but I don't understand what this means.


Solution

  • The type of sqrt is:

    λ> :t sqrt
    sqrt :: Floating a => a -> a
    

    The type of floor is:

    λ> ::t floor
    floor :: (RealFrac a, Integral b) => a -> b
    

    So, sqrt needs a type which has a Floating constraint. You can use the fromIntegral function to achieve that:

    roundSqrt :: Int -> Int
    roundSqrt x = floor (sqrt (fromIntegral x))