How to sort a list with sublists (common Lisp)

How to sort a list with sublists?

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

The result I'm looking for is sorted by all elements of the sublist:

 --> ((0) (0) (0 0 3 0) (0 1 3) (0 1 5) (0 1 5) (0 3 0) (1) (1) (2) (2 7 19)) 
+4
source share
2 answers

Start by defining a function that determines if one list is smaller. The following example assumes that lists can contain only numbers:

 (defun list< (ab) (cond ((null a) (not (null b))) ((null b) nil) ((= (first a) (first b)) (list< (rest a) (rest b))) (t (< (first a) (first b))) )) 

Armed with this feature, you can now sort the list of lists.

 (sort (copy-seq list) #'list<) 
+10
source

To sort by all sublist items, use a custom function for the predicate or sort key. Change the sort predicate to a user-defined function that can determine the order of two subscriptions. Alternatively, change the sort key to a user-defined function that reduces the sublist to a sortable value.

0
source

All Articles