Reputation: 437
So i know how to sort a list like (1 2 3)
by ascended order for example in Common Lisp.
But i need to sort this list: ( (1 2 3) nil 1)
in descending order of the 3rd element.
Is there a way to do that?
Upvotes: 1
Views: 4446
Reputation: 9656
The sort
function accepts a predicate that will be used to tell when an element precedes another (see the hyperspec).
So, define a function compare-3rd
:
(defun compare-3rd (a b)
(< (nth 2 a) (nth 2 b)))
And use it as the predicate:
(sort '(( (1 2 3) nil 4)
( (1 2 3) nil 2)
( (1 2 3) nil 3))
'compare-3rd)
==> (((1 2 3) NIL 2) ((1 2 3) NIL 3) ((1 2 3) NIL 4))
Of course, if you want descending order you may use >
instead of <
in compare-3rd
.
Upvotes: 3