I'm working on old exams to get ready for my own exam and the professor is nice enough to also give us the solutions to them and now I'm wondering why one function does what it's supposed to.
(defun sortulists (L)
(mapcar (lambda (uliste)
(sort uliste (lambda (x1 x2)
(or (symbolp x2)
(and (numberp x1) (numberp x2)
(< x1 x2))))))
L))
It's supposed to take a list L
with unsorted sublists which might contain numbers and atoms and sort first it's numbers and put the symbols at the end.
When called like this (sortulists '((A 9 b h 2) (1 m n 9 8) (5 a 7)))
it returns ((2 9 H B A) (1 8 9 N M) (5 7 A))
.
Any help?
Edit: fixed indentation
The predicate of the sort
function states what test has to be true once the sequence is sorted. How the sorting is done is not defined.
If you struggle with and
and or
as they are used here, I suggest you read the chapter Conditionals of Common Lisp: A Gentle Introduction to Symbolic Computation. It shows how you can interchange cond
, nested if
s and the combination and
and or
, and it provides exercises (and their solutions).
In short, either there has to be a symbol on the right, or, if both are numbers, they must be sorted by size.
(or
; if x2 is a symbol, then x1 is smaller, whatever x1 is
(symbolp x2)
; if both are numbers, then return t if x1 is smaller than x2
(and (numberp x1) (numberp x2)
(< x1 x2)))
So the numbers are sorted and at the front. The symbols are at the end, but unsorted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With