Haskell函数返回一个排序的点列表,具体取决于它们与特定点的距离

时间:2017-11-14 17:41:19

标签: haskell

我有以下三个功能。函数“distance”计算两点之间的距离。函数“calculateDistances”取一个点(x1,y1)和一个点[(x2,y2)]列表,并使用“距离”函数计算(x1,y1)和每个(x2,y2)之间的距离。清单[(x2,y2)]。它返回一个排序的点列表,具体取决于它们与(x1,y1)的距离。函数“nearestDistances”返回n个最接近的点(x1,y1),它使用函数“calculateDistances”中的排序列表。

我认为我的算法是正确的,但你可以看到我的“calculateDistances”代码丢失了,因为我不知道如何在Haskell中编写它。我是初学者,我真的很难用Haskell语法。任何帮助将不胜感激。

distance :: (Floating a, Ord a) => (a,a) -> (a,a)-> a
    distance (x1 , y1) (x2 , y2) = sqrt (x'*x' + y'*y')
        where
          x' = x1 - x2
          y' = y1 - y2

    Example outputs:
    *Main> distance (0,0) (1,0)
    1.0
    *Main> distance (0,0) (2,0)
    2.0
    *Main> distance (0,0) (3,0)
    3.0


    calculatesDistances :: (Floating a, Ord a) => (a,a) -> [(a,a)] -> [(a,a)]
    Psesudocode:
    Apply function distance to (x1 , y1) and every (x2 , y2) in [(x2 , y2)] and get a distance for every input
    Return the list [(x2 , y2)] but sorted in ascending order depending on the distance

    Expected output:
    *Main> calculatesDistances (0,0) [(3,0), (2,0),(-3,0), (1,0)]
     [(1,0),(2,0),(3,0),(-3,0)]


    closestDistances :: (Floating a, Ord a) => Int -> (a,a) -> [(a,a)] -> [(a,a)]
    closestDistances n (x1, y1) [(x2, y2)] = take n (calculatesDistances (x1, y1) [(x2, y2)])

    Expected output:

    *Main> closestDistances 3 (0,0) [(1,0),(2,0),(3,0),(-3,0)]
     [(1,0),(2,0),(3,0)]

    *Main> closestDistances 2 (0,0) [(1,0),(2,0),(3,0),(-3,0)]
     [(1,0),(2,0)]

1 个答案:

答案 0 :(得分:2)

您可以使用类型为

sortOn
sortOn :: Ord b => (a -> b) -> [a] -> [a]

并通过比较a函数的输出对a -> b进行排序。例如,

Data.List> sortOn (distance (0,0)) [(3,0), (1,1), (0,1)]
[(0.0,1.0),(1.0,1.0),(3.0,0.0)]

您也可以考虑编写一个squaredDistance函数,该函数省略了sqrt的效率,因为sqrt是单调的,因此不会影响排序顺序。