我正在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是否自动转换为浮动,或者这不是问题吗?
答案 0 :(得分:5)
将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
进行正确的类型转换才能进行类型检查。