Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No instance for (Floating Int) arising from a use of `sqrt`

Tags:

haskell

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?

like image 221
Czipperz Avatar asked Jul 09 '15 23:07

Czipperz


1 Answers

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.

like image 156
Sibi Avatar answered Nov 12 '22 08:11

Sibi