Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 output I am looking for is sort on 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))
like image 629
MRAC Publishing Avatar asked May 14 '11 17:05

MRAC Publishing


1 Answers

Start by defining a function that determines whether one list is less than another. The following example assumes that the lists can only contain numbers:

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

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

(sort (copy-seq list) #'list<)
like image 68
WReach Avatar answered Nov 16 '22 10:11

WReach