Haskell错误:无法匹配预期的类型

时间:2019-11-28 20:37:50

标签: haskell

我正在根据距离d到点列表x​​s中点p的度量d,按距离顺序将Haskell代码写入k个最近邻居的列表中。下面是我的代码:

import Data.List

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 d p [] = []
neighbours k d p ps = take k (sortOn distance(p ps))

distance :: Metric Double
distance (x1,y1) (x2,y2) = sqrt(((x1-x2)^2)+((y1-y2)^2))

错误是

    • Couldn't match expected type ‘[Point a] -> [Point Double]’
                  with actual type ‘(a, a)’
    • The function ‘p’ is applied to one argument,
      but its type ‘(a, a)’ has none
      In the second argument of ‘sortOn’, namely ‘(p ps)’
      In the second argument of ‘take’, namely ‘(sortOn distance (p ps))’
    • Relevant bindings include
        ps :: [Point a] (bound at A4.hs:21:18)
        p :: Point a (bound at A4.hs:21:16)
        d :: Metric a (bound at A4.hs:21:14)
        neighbours :: Int -> Metric a -> Point a -> [Point a] -> [Point a]
          (bound at A4.hs:20:1)
   |
23 |                     | otherwise = take k (sortOn distance(p ps))

请有人告诉我如何解决?

1 个答案:

答案 0 :(得分:7)

这部分

(sortOn distance(p ps))

表示:

  • 使用参数p调用函数ps,将结果命名为res;
  • 调用带有两个参数的函数sortOndistance(2参数函数)和res

这不是您想要的。确实,p是一对,而不是一个函数,因为错误指出:

 The function ‘p’ is applied to one argument,
 but its type ‘(a, a)’ has none

您可能想要的是

(sortOn (distance p) ps)

它将根据1参数函数psdistance p中的所有点进行排序,提供与p的距离。