Help on setf behavior

Discussion of Common Lisp
Post Reply
megera
Posts: 30
Joined: Wed Oct 10, 2012 1:34 pm

Help on setf behavior

Post by megera » Sat Dec 01, 2012 10:50 am

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

Goheeca
Posts: 271
Joined: Thu May 10, 2012 12:54 pm
Contact:

Re: Help on setf behavior

Post by Goheeca » Sat Dec 01, 2012 12:19 pm

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.
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version). Temporary mirrors of aferomentioned: CLHS and a dark version.

megera
Posts: 30
Joined: Wed Oct 10, 2012 1:34 pm

Re: Help on setf behavior

Post by megera » Sat Dec 01, 2012 12:33 pm

ooohh PERFECT!!
Thanks Goheeca !!! very much!! :D

Post Reply