lisp sort list via function

大城市里の小女人 提交于 2019-12-05 15:49:31

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.

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