Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LISP very simple list question

Tags:

list

lisp

Im learning lisp and im pretty new at this so i was wondering...

if i do this:

(defparameter *list-1* (list 1 2))
(defparameter *list-2* (list 2 3))
(defparameter *list-3* (append *list-1* *list-2*))

And then

(setf (first *list-2*) 1)
*list-3*

I will get (1 2 1 4)

I know this is because the append is going to "save resources" and create a new list for the first chunk, but will actually just point to the second chunk, coz if i do:

(setf (first *list-1*) 0)
*list-3*

I will get (1 2 1 4) instade of the more logical (0 2 1 4)

So my question is, what other cases are like this in lisp, how do you black belt lispers know how to deal with this stuff that is not intuitive or consistent?

like image 247
DFectuoso Avatar asked Oct 15 '25 03:10

DFectuoso


1 Answers

One defensive tactic is to avoid sharing structure.

(defparameter *list-3* (append *list-1* *list-2* '()))

or

(defparameter *list-3* (append *list-1* (copy-list *list-2*)))

Now the structure of the new *list-3* is all new, and modifications to *list-3* won't affect *list-2* and vice versa.

like image 188
Doug Currie Avatar answered Oct 18 '25 09:10

Doug Currie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!