两点距离,Haskell没有改变函数声明?

时间:2017-03-17 12:01:54

标签: haskell

对于两点之间的距离,在不更改函数声明的情况下,我不断收到此错误"无法将预期类型'b'与实际类型'a'匹配       'a'是绑定的刚性类型变量         类型签名:"

type Point a = (a,a)
distance :: (Real a, Floating b) => Point a -> Point a -> b
distance (x1,y1) (x2,y2) = sqrt ((dx * dx) + (dy * dy))
  where dx = x2 - x1
    dy = y2 - y1

2 个答案:

答案 0 :(得分:2)

sqrt返回与其参数相同的类型:

Prelude> :t sqrt
sqrt :: Floating a => a -> a

由于您将b作为sqrt的参数提供,因此Haskell推断返回类型必须为b而不是a

是否有特定原因导致您无法使用

distance :: Floating b => Point b -> Point b -> b
distance (x1,y1) (x2,y2) = sqrt ((dx * dx) + (dy * dy))
  where dx = x2 - x1
        dy = y2 - y1

答案 1 :(得分:0)

type Point a = (a,a)
distance :: (Real a, Floating b) => Point a -> Point a -> b
distance (x1,y1) (x2,y2) = sqrt ((dx * dx) + (dy * dy))
  where dx = realToFrac $ x2 - x1
        dy = realToFrac $ y2 - y1