Pofis
Pofis

Reputation: 13

Haskell type declaration problem with isSquareNumber function

I have to write a function that determines if a number is a perfect square, which I was able to do:

isSquareNumber x
    | x < 0 = False
    | otherwise = snd (properFraction (sqrt x)) == 0.0

But I have to use a given type declaration: isSquareNumber :: Int -> Bool

Whitout it, it works fine, but when I add it I get errors.

Upvotes: 1

Views: 84

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

sqrt :: Floating a => a -> a does not work with an Int, but with Floating types, and an Int is not an Floating type.

You can use fromIntegral :: (Integral a, Num b) => a -> b to convert an Integral type to any Num type. You thus can implement this as:

isSquareNumber :: Int -> Bool
isSquareNumber x = x >= 0 && f == 0.0
    where (_, f) = properFraction (sqrt (fromIntegral x))

Upvotes: 4

Related Questions