4

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

1
  • Which lisp do you use? Commented Mar 13, 2013 at 12:20

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.