Lisp sort list through function

I am trying to use lisp sort to sort a list through a function, but don't know how to do it. I have a starting point in a 2D space with x and y coordinates. Then I have a list of N-other points, and I have a function that calculates the distance between two points. Now I need a list containing all N-points and sorted by distance from the starting point to all other points.

I think I can use the sort function and pass the function as an argument (distance calculation function). But I do not know how to do this, and research on the Internet did not help.

Any ideas?

Yours faithfully

+4
source share
2 answers

Use :key with sort :

 (sort list #'< :key (lambda (p) (dist p start-point))) 

This will sort the list points in ascending order (use > to decrease) based on the distance to the start-point .

+8
source

If you are using generic lisp, I recommend the Common Lisp Hyper Spec . In your case, the documentation for the sort function will be useful. Here you can see that it has a second parameter: a predicate. The predicate takes two arguments and returns whether the second is stronger than the first.

Say you have a dist function that measures the distance between two points. To compare two points at a distance to your start-point , you need the following lambda:

 #'(lambda (p1 p2) (> (dist p1 start-point) (dist p2 start-point))) 

Therefore, you should put it in the place of the predicate (second position) in the sort argument list.

+2
source

Source: https://habr.com/ru/post/1468954/


All Articles