lisp sort list via function

送分小仙女□ 提交于 2019-12-07 10:07:27

问题


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:


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.




回答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.



来源:https://stackoverflow.com/questions/15385099/lisp-sort-list-via-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!