我正在Haskell中做一些基础工作,不明白为什么它不能编译。这是错误:

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

相关代码:
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

sqrt函数的类型为Floating a => a -> a -> a。 Num不会自动转换为Floating,还是这不是问题?

最佳答案

Circ处理代码更改为此,它将进行类型检查:

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
sqrt的类型为sqrt :: Floating a => a -> a,您必须使用fromIntegral进行正确的类型转换以进行类型检查。

关于haskell - 没有因使用 `sqrt`而产生的(Floating Int)实例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31329907/

10-13 03:07