Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this sorting algorithm do what it is supposed to? [Lisp]

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

like image 411
EviL GaMer Avatar asked Dec 06 '22 20:12

EviL GaMer


2 Answers

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 ifs 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.

like image 144
Pascal Avatar answered May 24 '23 21:05

Pascal


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

like image 21
Rainer Joswig Avatar answered May 24 '23 19:05

Rainer Joswig