Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 393
Matt Robbins Avatar asked Mar 09 '23 00:03

Matt Robbins


1 Answers

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))  
like image 195
Sibi Avatar answered Mar 10 '23 14:03

Sibi