我想计算多边形的面积,但是我实现的代码不起作用。有人能帮助我找到更好的解决方案吗?
这是我的代码:
ar :: (Float,Float,Float)-> Float
ar (v1,v2,v3) = let a=distBetween v1 v2
b=distBetween v2 v3
c=distBetween v3 v1
s=0.5*(a+b+c)
in sqrt (s*(s-a)*(s-b)*(s-c))
distBetween :: (Float,Float)->(Float,Float)->Float
distBetween (x1,y1) (x2,y2) = sqrt ((x1-x2)^2+(y1-y2^2))
这是我的错误:
Type error in application
*** Expression : distBetween v1 v2
*** Term : v2
*** Type : Float
*** Does not match : (Float,Float)
答案 0 :(得分:2)
distBetween
适用于两对Float
,但v1
,v2
和v3
都只是单Float
个。如果你有
-- Just creates an alias for `(Float, Float)`, since otherwise it'd be a lot of typing
type Point = (Float, Float)
然后你可以把它写成
distBetween :: Point -> Point -> Float
distBetween (x1, y1) (x2, y2) = sqrt $ (x1-x2)^2 + (y1-y2)^2
-- You also had a typo in your distance function here ^
ar :: (Point, Point, Point) -> Float
ar (v1, v2, v3) =
let a = distBetween v1 v2
b = distBetween v2 v3
c = distBetween v3 v1
s = 0.5 * (a + b + c)
in sqrt $ s * (s - a) * (s - b) * (s - c)
然后它会编译得很好。既然你已告诉编译器v1
,v2
和v3
都只是Float
,那么它就不能与(Float, Float)
匹配根据{{1}}的参数需要。