I'm doing some basic work in Haskell and don't understand why this isn't compiling. Here's the error:
shapes.hs:35:11:
No instance for (Floating Int) arising from a use of `sqrt'
In the expression: sqrt (hd * hd + vd * vd)
In an equation for `d': d = sqrt (hd * hd + vd * vd)
In the expression:
let
hd = xc - x
vd = yc - y
d = sqrt (hd * hd + vd * vd)
in if d <= r then True else False
Related code:
type Point = (Int,Int)
data Figure = Rect Point Point | Circ Point Int
inside :: Point -> Figure -> Bool
inside (x,y) (Rect (left,bot) (right,top)) =
if x <= left && x >= right &&
y <= bot && y >= top
then True
else False
inside (x,y) (Circ (xc,yc) r) =
let hd = xc - x
vd = yc - y
d = sqrt (hd*hd + vd*vd) in -- line 35 is here
if d <= r then True else False
The sqrt function's type is Floating a => a -> a -> a
. Doesn't Num auto convert to Floating, or is this not the problem?
Change the Circ
handling code to this and it will typecheck:
inside (x,y) (Circ (xc,yc) r) =
let hd = fromIntegral $ xc - x
vd = fromIntegral $ yc - y
d = sqrt (hd*hd + vd*vd) in
if d <= (fromIntegral r) then True else False
The type of sqrt
is sqrt :: Floating a => a -> a
and you have to do proper type conversion using fromIntegral
to make it typecheck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With