I have the following three functions. The function "distance" calculates the distance between two points. The function "calculatesDistances" takes a point (x1, y1) and a list of points [(x2, y2)] and uses the "distance" function to calculate the distance between (x1, y1) and every (x2, y2) in the list [(x2, y2)]. It returns a sorted list of points depending on their distance to (x1, y1). The function "closestDistances" returns the n closest points to (x1, y1) and it uses the sorted list from the function "calculatesDistances".
I think my algorithm is correct but as you can see my code for "calculatesDistances" is missing because I have no idea how to write this in Haskell. I am a beginner and I'm really struggling with Haskell syntax. Any help will be appreciated.
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)]
sortBy (comparing distance) list