I am trying to use lisp's sort to sort a list via a function but dont have a clue how to do this. I have a start-point in 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 2 points. What I want now is a list, that contains all the N-Points and is sorted by distance ascending from the start-point to all other points.
I think I can use the sort-function and pass a function as argument (the calculate-distance function) But i dont know how to do it and researches on the web did not help.
Any ideas?
Regards
Use :key
with sort
:
(sort list #'< :key (lambda (p) (dist p start-point)))
This will sort the list
of points in the increasing order (use >
for decreasing) based on the distance to start-point
.
If you use common lisp, I recommend you the Common Lisp Hyper Spec project. In your case the documentation to the sort
function will be useful. Here you can see, that it has a second parameter: predicate. The predicate takes two arguments and returns whether the second is greather then the first one.
Let's say you have a function dist
, measuring a distance between two points. To compare two points by the distance to your start-point
, you need the following lambda:
#'(lambda (p1 p2) (> (dist p1 start-point) (dist p2 start-point)))
So you have to place it in the place of predicate (the second position) in sort
argument list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With