simple problem with setf

Discussion of Common Lisp
Post Reply
kanesoban
Posts: 2
Joined: Sun Jul 31, 2011 1:39 am

simple problem with setf

Post by kanesoban » Sun Jul 31, 2011 1:55 am

Problem:

Code: Select all

(defun proba1 (li) (first (second li)))

(defparameter li (list 1 (list 2) 3))

(setf (first (second li)) 1)

( setf (proba1 li) 1) ; result is an error
The question is, how can the last command cause an error, when the one before it does not, and it does the same thing (but trough a function) ?

ramarren
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland
Contact:

Re: simple problem with setf

Post by ramarren » Sun Jul 31, 2011 3:00 am

SETF is a macro which expands to the correct procedure for setting a place. There must be a valid setf expansion for it to work. Expansions for functions are not automatically generated, since that would not be correct in the majority of cases. You can create your own expander for functions in a number of ways, the simplest of which is DEFUNin a (setf ...) function, like this:

Code: Select all

(defun (setf proba1) (new-value list) (setf (first (second list)) new-value))
Also, you have created a special variable with the same name as a function argument. You should never do that, since that reacts in ways which are often confusing, which is a reason for the convention of naming special variables with symbol names surrounded by stars.

kanesoban
Posts: 2
Joined: Sun Jul 31, 2011 1:39 am

Re: simple problem with setf

Post by kanesoban » Mon Aug 01, 2011 1:38 am

Thank you for the answer. My next question is, what is the general syntax of setf expander function definitions (google doesn't seem to help me with this) ?

Konfusius
Posts: 62
Joined: Fri Jun 10, 2011 6:38 am

Re: simple problem with setf

Post by Konfusius » Mon Aug 01, 2011 5:27 am

There are other ways to define a setf-accessor but defsetf is the simplest and most common one.

http://www.lispworks.com/documentation/ ... tm#defsetf

Post Reply