Sorting 如何使用子列表对列表进行排序(通用Lisp)
如何使用子列表对列表进行排序Sorting 如何使用子列表对列表进行排序(通用Lisp),sorting,lisp,common-lisp,Sorting,Lisp,Common Lisp,如何使用子列表对列表进行排序 (setq list '((0) (1) (2) (0 1 5) (0 1 3) (0 1 5) (0 3 0) (0) (1) (2 7 19) (0 0 3 0))) ; restricting the sort to only the first element: (sort (copy-seq list) #'< :key #'car) --> ((0) (0 1 5) (0 1 3) (0 1 5) (0 3
(setq list '((0) (1) (2) (0 1 5) (0 1 3) (0 1 5) (0 3 0) (0) (1)
(2 7 19) (0 0 3 0)))
; restricting the sort to only the first element:
(sort (copy-seq list) #'< :key #'car)
--> ((0) (0 1 5) (0 1 3) (0 1 5) (0 3 0) (0) (0 0 3 0) (1) (1) (2) (2 7 19))
要对子列表的所有元素进行排序,请对排序谓词或键使用自定义函数。将排序谓词更改为可确定两个子列表顺序的自定义函数。或者,将排序键更改为自定义函数,以将子列表减少为可排序的值 首先定义一个函数,确定一个列表是否小于另一个列表。以下示例假定列表只能包含数字:
(defun list< (a b)
(cond ((null a) (not (null b)))
((null b) nil)
((= (first a) (first b)) (list< (rest a) (rest b)))
(t (< (first a) (first b))) ))
(defun列表<(a b)
(条件((空a)(非(空b)))
((空b)无)
((=(第一个a)(第一个b))(列表<(剩余a)(剩余b)))
(t(<(第一个a)(第一个b)))
使用此功能,您现在可以对列表列表进行排序
(sort (copy-seq list) #'list<)
(排序(复制顺序列表)#'列表感谢大家。这正是我想要的。奇怪的是,Lisp没有一个内置的函数来逐项比较两个列表。它需要做一些假设,但有一个合理的默认值似乎是有意义的,您仍然可以定义自己的函数来覆盖…谢谢,这个帮助让我了解自定义函数的使用。
(sort (copy-seq list) #'list<)