[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Writing Destructive Functions



> Here is a function that has the requested behaviour:
> 
> (defun replace-first (l new)
>   (setf (cdr l) (cons (car l) (cdr l))
>         (car l) new))
> 
> That is, you add a cons cell after the first one, move the first element to
> the second place, and add the new elemnt in its place.
> This may not work if you share other parts of the list too.
>      Daniel.

Interesting you should bring this up. I thought of this solution years ago 
but never actually implemented it. Thanks Daniel.
The cavat here is that l  CANNOT be NIL or the returned result of
the fn will not be EQ to its first arg. Since Lists of NIL are so common, you 
end up having to maintain the list in a var anyway.
Also consider growable vectors. Unlike lists, there can be > 1 empty
vector in a lisp environment.