I just started learning haskell, and I tried to implement a simple function to check if a number is a square root. I think I’m having some issues understanding the Haskell type system — my only other programming experience is ruby and some Java. This is what I had so far (Sorry if its really stupid):
isPerfectSquare :: (RealFloat t) => t -> Bool
isPerfectSquare n =
(sqrt n) == (truncate (sqrt n))
This is what i would do in ruby … But here it gives me this error:
Could not deduce (Integral t) arising from a use of `truncate'
from the context (RealFloat t)
bound by the type signature for
isPerfectSquare :: RealFloat t => t -> Bool
at more.hs:(73,1)-(74,35)
Possible fix:
add (Integral t) to the context of
the type signature for isPerfectSquare :: RealFloat t => t -> Bool
In the second argument of `(==)', namely `(truncate (sqrt n))'
In the expression: (sqrt n) == (truncate (sqrt n))
In an equation for `isPerfectSquare':
isPerfectSquare n = (sqrt n) == (truncate (sqrt n))
Failed, modules loaded: none.
Could you please explain what the problem is, how to fix it, and preferably any basic concepts I am not understanding? Thanks in advance.
sqrt has type:
truncate has type:
In other words, sqrt returns a floating-point number, while truncate returns an integer. You have to insert an explicit conversion. In this case, you probably want
fromIntegral, which can convert any integral type to any numeric type:You can then make the comparison: