To do a comparison you need at least two elements so checking if x
is NIL
is not enough.
Checking if (cdr x)
is NIL
is a nice way to check that the list length is at least two because NIL
is special and even if it's not a cons cell it's guaranteed that (cdr NIL)
is NIL
.
The error you were getting is because NIL
is not a number thus you cannot compare with <
a number with it and this was happening when executing (< (car x) (cadr x))
when x
was a list with a single element.
About sorting in a single recursive call you could use this definition of sorting:
- an empty list is sorted
- a non-empty list is sorted if the first element is the minimum of the list and the rest of the list is sorted.
This leads to
(defun mysort (x)
(if x
(let ((minimum (reduce #'min x)))
(cons minimum
(mysort (remove minimum x :count 1))))))
That, by the way, is a very inefficient way to do the sorting.