简体   繁体   English

预期类型 `a' 带有 `Double' 错误:Haskell

[英]Expected type `a' with `Double' error : Haskell

I'm writing a program that returns a list of the k nearest neighbours, in distance order, according to metric d to point p in the list ps of points.我正在编写一个程序,该程序按照距离顺序返回 k 个最近邻居的列表,根据度量 d 到点列表 ps 中的点 p。 All should be returned as proper neighbours if in the list ps are fewer than k elements.如果列表中的 ps 少于 k 个元素,则所有应作为正确的邻居返回。 Also, two equally close points to p should be returned based on their initial order in the list ps此外,应根据它们在列表 ps 中的初始顺序返回与 p 相同的两个点

import Data.List

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

nearPoints ::  Int -> Metric a -> Point a -> [Point a] -> [Point a]
nearPoints k d p [] = []
nearPoints k d p ps = take k (sortOn (pointsDistCalc p) ps)

pointsDistCalc :: Metric Double
pointsDistCalc (t1,t1) (t2,t2) = sqrt(((t1-t2)^2)+((t1-t2)^2))

This is the error message这是错误信息

    * Couldn't match type `a' with `Double'
      `a' is a rigid type variable bound by
        the type signature for:
          nearPoints :: forall a.
                        Int -> Metric a -> Point a -> [Point a] -> [Point a]
      Expected type: Point Double
        Actual type: Point a
    * In the first argument of `pointsDistCalc', namely `p'
      In the first argument of `sortOn', namely `(pointsDistCalc p)'
      In the second argument of `take', namely
        `(sortOn (pointsDistCalc p) ps)'
    * Relevant bindings include
        ps :: [Point a]
        p :: Point a
        d :: Metric a
        nearPoints :: Int -> Metric a -> Point a -> [Point a] -> [Point a]
11 | nearPoints k d p ps = take k (sortOn (pointsDistCalc p) ps)

Please can someone help me with this请有人可以帮我解决这个问题

You defined pointsDistCalc as a Metric for Point Double s, hence that means that nearPoints which sort by that distance, should be Point Double s as well.您将pointsDistCalc定义为Point DoubleMetric ,因此这意味着按该距离排序的nearPoints也应该是Point Double

That being said, the signature suggests that a metric is given, and thus that one does not per se uses the PointsDistCalc .话虽如此,签名表明给出了一个指标,因此该指标本身并不使用PointsDistCalc You thus can implement this with:因此,您可以通过以下方式实现:

nearPoints ::  Int -> Metric a -> Point a -> [Point a] -> [Point a]
nearPoints _ _ _ [] = []
nearPoints k d p0 ps = take k (sortOn (d p0) ps)

There is no need to split the definition in two cases here: sortOn will return an empty list if it is given an empty list:这里不需要在两种情况下拆分定义:如果给定一个空列表, sortOn将返回一个空列表:

nearPoints ::  Int -> Metric a -> Point a -> [Point a] -> [Point a]
nearPoints k d p0 ps = take k (sortOn (d p0) ps)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM