Search code examples
lispclisp

Instance variables in Lisp?


I'm writing a function for a CLOS class that reverses the list element of an object of said class.

I have a method that will return the reverse list, but how do I make it set the object's list to that list? Can I have a instance variable in the function that stores the list then set the element to that? Or is there an easier way?

Here's the method as it is now:

(defun my-reverse (lst)
    (cond ((null lst) ‘())
           (t (append (my-reverse (cdr lst)) (car lst)))))

The object it is passed is (l my-list) and the accessor would then be (my-list-ls l).

Edit: Realized that cons doesn't work on 2 lists.

Edit2: What I assume the right code would be:

(defun my-reverse (l my-list)
        (cond ((null (my-list-ls l) ‘())
               (t (setf (my-list-ls l) (append (my-reverse (cdr (my-list-ls l)))
                                         (car (my-list-ls l)))))))

Solution

  • If you want to modify an object's slot, you need to pass that object itself to your function, not just the value of the slot you want to change.

    EDIT: regarding the edit2 of the question

    I assume my-list is the name of the class, and you don't actually want to pass it to the function, right? In that case, you should substitute the defun with a defmethod. Also, it should be better to change the instance only once, after you reversed the whole list, instead of at each step. You could use an inner function for that:

    (defmethod my-reverse ((l my-list))
      (labels ((inner (list acc)
                 (if (endp list)
                     acc
                     (inner (rest list) (cons (first list) acc)))))
         (setf (my-list-ls l) (inner (my-list-ls l) ()))))
    

    EDIT 2: detailed explanation

    defmethod is the alternative to defun for defining (polymorphic) methods. Though, if you don't need polymorphism, you could just use (defun my-reverse (l) for the first line.

    labels is for inner function definitions. Here, it defines an inner function named inner with the two parameters list and acc. inner is the function that does the actual reversing, and it's a tail-recursive function because reversing goes naturally with tail-recursion. (It can build its result with cons and is therefore of linear complexity, whereas your solution needs append and thereby is of quadratic complexity, because cons itself is constant, but append is linear.)

    first and rest are just alternate names for car and cdr, endp is mostly just an alternate name for null, with the difference that endp will signal an error if its argument isn't actually a list.

    Finally, the last line calls inner with the original and an empty list as arguments, and assigns the result to the slot (aka instance variable).