Help on setf behavior

Discussion of Common Lisp

Help on setf behavior

Postby 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
megera
 
Posts: 30
Joined: Wed Oct 10, 2012 1:34 pm

Re: Help on setf behavior

Postby 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).
User avatar
Goheeca
 
Posts: 198
Joined: Thu May 10, 2012 12:54 pm

Re: Help on setf behavior

Postby megera » Sat Dec 01, 2012 12:33 pm

ooohh PERFECT!!
Thanks Goheeca !!! very much!! :D
megera
 
Posts: 30
Joined: Wed Oct 10, 2012 1:34 pm


Return to Common Lisp

Who is online

Users browsing this forum: No registered users and 1 guest

cron