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)))))))
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-listis the name of the class, and you don’t actually want to pass it to the function, right? In that case, you should substitute thedefunwith adefmethod. 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:EDIT 2: detailed explanation
defmethodis the alternative todefunfor defining (polymorphic) methods. Though, if you don’t need polymorphism, you could just use(defun my-reverse (l)for the first line.labelsis for inner function definitions. Here, it defines an inner function namedinnerwith the two parameterslistandacc.inneris 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 withconsand is therefore of linear complexity, whereas your solution needsappendand thereby is of quadratic complexity, becauseconsitself is constant, butappendis linear.)firstandrestare just alternate names forcarandcdr,endpis mostly just an alternate name fornull, with the difference thatendpwill signal an error if its argument isn’t actually a list.Finally, the last line calls
innerwith the original and an empty list as arguments, and assigns the result to the slot (aka instance variable).