Unexpected lisp setf behaviour

Hi Folks,

In writing some lisp code for uni coursework ("bin-packing" EA problem), I've encountered some weird behaviour. I copy a list, containing an element of type 'item', and attempt to set a value on the copy only. The code below is a modified excerpt but displays what I mean - I expected the 'container' in X to be 0, and its equivalent in M to be something random, but both elements get set to the same random value.

(defstruct item
id
weight
type
container)

(setq X (list (make-item
:id 0
:weight 0
:type 0
:container 0)))

(setq M (copy-list X))
(setf (item-container (nth 0 M)) (random 50))

I'm fairly new to lisp, so I'm not sure if this is correct or not (I suspect that it is, since clisp and emacs lisp behave the same way). Can someone point me in the right direction?

edit: Adding my solution for anyone googling for a similar problem:
(defun copy-item-list (s)
(if s
(cons (copy-item (car s))
(copy-item-list (cdr s))))
)
Good shout, johnwcowan.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Pointing in the right direction

Although there are a number of Schemers and Lispers that hang about, your best bet is comp.lang.scheme or comp.lang.lisp. Language specific questions are usually frowned on in this neck of the woods - homework questions even more so.

Ah, sorry about that!

Ah, sorry about that!

A hint

You might want to consider just what it is that list-copy copies, and what it does not.