2011-05-14 106 views
4

如何使用子列表对列表进行排序?如何使用子列表对列表进行排序(常见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 0) (0) (0 0 3 0) (1) (1) (2) (2 7 19)) 

我要找的输出排序的子表中的所有元素:

--> ((0) (0) (0 0 3 0) (0 1 3) (0 1 5) (0 1 5) (0 3 0) (1) (1) (2) (2 7 19)) 

回答

10

首先定义一个函数来确定一个列表是否小于另一个列表。以下示例假定列表只能包含数字:

(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))))) 

用此功能武装,您现在可以对列表进行排序。

(sort (copy-seq list) #'list<) 
+0

感谢大家。这正是我所期待的。 – 2011-05-15 07:06:02

0

进行排序的子列表中的所有元素,使用自定义功能进行排序谓语排序谓词更改为可以确定两个子列表的顺序的自定义函数。或者,将排序键更改为将子列表减少为可排序值的自定义函数。

+0

谢谢,这有助于我了解自定义函数的使用。 – 2011-05-15 14:35:29