While there is such a code

(defun Sort (l) ( cond ( (null l) '(Список отсортирован!) ) ( T ( rplaca (car l) (Min l) ) ( Sort( cdr l ) )) ) ) (defun Min (l) ( cond ( (null l) nil) ( (eq (length l) 1) (car l) ) ( T (Min2 (car l) (Min(cdr l) ))) ) ) (defun Min2 (xy) ( cond ( (< xy ) x) ( T y) ) ) 

The function for finding the minimum works correctly, and Sort when called for example (Sort '(3 2 1)) returns nil and writes a bad argument type - 3. Is this why?

1 answer 1

This is not sorting, but something strange.

To begin with, (rplaca (car l) …) , if l simple list - this is nonsense. Suppose we have a list l :

 (setf l '(3 2 1)) 

Visually, this can be represented, say, as (rectangles are cons):

  ┌───┬─────────────────────┐ │ │ ┌───┬─────────────┐ │ │ │ │ │ ┌───┬─────┐ │ │ │ 3 │ │ 2 │ │ 1 │ nil │ │ │ │ │ │ │ └───┴─────┘ │ │ │ │ └───┴─────────────┘ │ └───┴─────────────────────┘ └─┬─┘└─────────┬──────────┘ (car l) (cdr l) 

I did not draw here with a chain (as usual draw, and how to display all this more correctly), but nested. With pseudographics, alas, uncomfortable in a different way.

Or, in the form of statements:

 (car l) => 3 (cdr l) => (2 1) (car (cdr l)) => 2 (cdr (cdr l)) => (1) (car (cdr (cdr l))) => 1 (cdr (cdr (cdr l))) => nil 

By doing (rplaca (car l) …) you are essentially doing (rplaca 3 …) , but 3 is not a cons. That's why it turns out "bad argument type - 3". The first argument type of rplaca invalid.

We end up with the fact that even if it were meant “to replace the first element in l (in fact, (car l) , yes) with the minimum value in l (ie (rplaca l (min l)) ), and then recursively sort tail ", then it will not sort. You replace the first element l , losing the value that was there - it's not a transfer and not a permutation, but a replacement-assignment.

Once again, in detail, re-read everything that is devoted to lists in Lisp. What cons is, and how the (linked) lists are arranged, and how rplaca (in particular, its arguments) works with examples of usage.

And, yes, please format the code more readable.

  • Is there any function that swaps 2 items in the list? then you could write it instead of rplaca .. - AnnaHatiko
  • Clear. Well then a bunch of setf and nth will help. One value in a temporary variable, the second in its place, and from the temporary variable back in place of the second. - drdaeman 3:19
  • I would not answer her until the code is formatted - Vladimir Gordeev
  • The stern answer is a cool lispoid. @ AnnaHotiko that this is XLISP, (Wikipedia says this is an extended Scheme of the old, R3RS version) - alexlz
  • drdaeman, and how do you represent the reversal of 2 elements with nth and setf? - AnnaHatiko