Page 1 of 1

Help on setf behavior

Posted: Sat Dec 01, 2012 10:50 am
by megera
HI
I do not understand why this expr :

Code: Select all

(setf lst nil)
(setf (car lst)(1+ (car (push 1 lst))))

2

lst
(1 2)

return 2 it’s ok, but now if we call lst return is : (1 2)-…??
Instead I’ll expect ( 2 1)…
can somebody
illuminate me?? thanks in advance

Re: Help on setf behavior

Posted: Sat Dec 01, 2012 12:19 pm
by Goheeca
Because push expands roughly (see notes on CLHS) to:

Code: Select all

(setf place (cons item place))
so your code looks like this:

Code: Select all

(defvar lst '(nil))
(setf (car lst) (1+ (car (setf lst (cons 1 lst)))))
The place of first setf is evaluated before the value form which has a side effect that the car of lst becomes the cdr of lst, due to consing.
// I've used defvar and a non-empty list, otherwise SBCL would be complaining.

Re: Help on setf behavior

Posted: Sat Dec 01, 2012 12:33 pm
by megera
ooohh PERFECT!!
Thanks Goheeca !!! very much!! :D