Haskell错误:无法将类型“ a”与“ Double”匹配

时间:2019-11-29 15:36:45

标签: haskell

我正在编写一个Haskell代码,根据距离d到点列表x​​s中的点d的度量d,以距离顺序找到最近的k个邻居的列表。我的代码在下面

import Data.List
import Data.Function

type Point a = (a,a)
type Metric a = (Point a) -> (Point a) -> Double

neighbours :: Int -> Metric a -> Point a -> [Point a] -> [Point a]
neighbours k calDistance p [] = []
neighbours k calDistance p ps
 | k < 0     = error "k cannot be negative"
 | otherwise = take k (neighbours' (sortBy (compare `on` snd) [ (poi,dis) | (poi,dis) <- points p ps]))

neighbours' :: [(Point a, Double)] -> [Point a]
neighbours' xs = [ x | (x,y)<-xs]

points :: Point a -> [Point a] -> [(Point a, Double)]
points _ [] = []
points p1 (p2:px) = (p2,(calDistance p1 p2)): points p1 px

calDistance :: Metric Double
calDistance (x1,y1) (x2,y2) = sqrt((x1-x2)**2 + (y1-y2)**2)

错误是

    • Couldn't match type ‘a’ with ‘Double’
      ‘a’ is a rigid type variable bound by
        the type signature for:
          points :: forall a. Point a -> [Point a] -> [(Point a, Double)]
        at A4.hs:27:1-53
      Expected type: Point Double
        Actual type: Point a
    • In the first argument of ‘calDistance’, namely ‘p1’
      In the expression: (calDistance p1 p2)
      In the first argument of ‘(:)’, namely ‘(p2, (calDistance p1 p2))’
    • Relevant bindings include
        px :: [Point a] (bound at A4.hs:29:15)
        p2 :: Point a (bound at A4.hs:29:12)
        p1 :: Point a (bound at A4.hs:29:8)
        points :: Point a -> [Point a] -> [(Point a, Double)]
          (bound at A4.hs:28:1)
   |
29 | points p1 (p2:px) = (p2,(calDistance p1 p2)): points p1 px
   |     

但是,如果我将“ Metric Double”更改为“ Double a”,则还会出现编译错误:无法将期望的类型“ Double”与实际类型“ a”匹配。有人可以告诉我如何解决吗?

1 个答案:

答案 0 :(得分:3)

参见实施

points :: Point a -> [Point a] -> [(Point a, Double)]

您致电

calDistance :: Metric Double

这意味着a必须为Double,如果有人叫points且类型为Point Int的值作为第一个自变量会发生什么? calDistance应该如何处理,因为它只能处理Point Double的值?

该错误告诉您,calDistance的调用类型为Point a,其中a可以是任何类型。而且与calDistance期望Point Double作为其第一个参数不匹配。