使用距离函数确定最接近的点对,Haskell

时间:2017-03-17 23:34:42

标签: haskell

我试图找出如何使用此函数为项目获得最接近的点对。我收到的错误我不太明白。谢谢您的帮助。我已经给出了有效的距离公式,我不确定我是否在nearestPairs函数中正确调用了距离函数。

type Point a = (a,a)

-- Determine the true distance between two points.
distance :: (Real a, Floating b) => Point a -> Point a -> b
distance (x1,y1) (x2,y2) = sqrt (realToFrac ((x1 - x2)^2 + (y1 - y2)^2))

type Pair a = (Point a, Point a)

-- Determine which of two pairs of points is the closer.
closerPair :: Real a => Pair a -> Pair a -> Pair a
closerPair (p1,p2) (q1,q2) | distance (p1, p2) > distance (q1,q2) = (q1,q2)
                           | otherwise = (p1,p2)
mod11PA.hs:30:30: error:
* Could not deduce (Real (Point a))
    arising from a use of `distance'
  from the context: Real a
    bound by the type signature for:
               closerPair :: Real a => Pair a -> Pair a -> Pair a
    at mod11PA.hs:29:1-50
* In the first argument of `(>)', namely `distance (p1, p2)'
  In the expression: distance (p1, p2) > distance (q1, q2)
  In a stmt of a pattern guard for
                 an equation for `closerPair':
    distance (p1, p2) > distance (q1, q2)

mod11PA.hs:30:30: error:
* Could not deduce (Ord (Point (Point a) -> b0))
    arising from a use of `>'
    (maybe you haven't applied a function to enough arguments?)
  from the context: Real a
    bound by the type signature for:
               closerPair :: Real a => Pair a -> Pair a -> Pair a
    at mod11PA.hs:29:1-50
  The type variable `b0' is ambiguous
  Relevant bindings include
    q2 :: Point a (bound at mod11PA.hs:30:24)
    q1 :: Point a (bound at mod11PA.hs:30:21)
    p2 :: Point a (bound at mod11PA.hs:30:16)
    p1 :: Point a (bound at mod11PA.hs:30:13)
    closerPair :: Pair a -> Pair a -> Pair a (bound at mod11PA.hs:30:1)
* In the expression: distance (p1, p2) > distance (q1, q2)
  In a stmt of a pattern guard for
                 an equation for `closerPair':
    distance (p1, p2) > distance (q1, q2)
  In an equation for `closerPair':
      closerPair (p1, p2) (q1, q2)
        | distance (p1, p2) > distance (q1, q2) = (q1, q2)
        | otherwise = (p1, p2)

能够通过更改closePair的方法来解决我的问题,以便在两对中获取分数:

closerPair :: Real a => Pair a -> Pair a -> Pair a
closerPair ((x,y),(x1,y1)) ((x2,y2),(x3,y3)) | distance (x,y) (x1,y1) >   distance (x2,y2) (x3,y3) = ((x2,y2),(x3,y3))
                                             | otherwise = ((x,y),(x1,y1))

1 个答案:

答案 0 :(得分:1)

您已经发布了正确有效的实施方案

closerPair ((x,y),(x1,y1)) ((x2,y2),(x3,y3))
  | distance (x,y) (x1,y1) >   distance (x2,y2) (x3,y3) = ((x2,y2),(x3,y3))
  | otherwise = ((x,y),(x1,y1))

但请注意,这里没有理由与Point - 坐标进行实际模式匹配:您只是放回x1,y1x2,y2 ...无论如何。因此,为什么不把它写成

closerPair (p₀,p₁) (p₂,p₃)
  | distance p₀ p₁ > distance p₂ p₃ = (p₂,p₃)
  | otherwise                       = (p₀,p₁)

顺便提一下,这可以用标准函数来编写:

import Data.List (minimumBy)
import Data.Ord (comparing)

closerPair v w = minimumBy (comparing $ uncurry distance) [v,w]
相关问题