simple problem with setf

Discussion of Common Lisp

simple problem with setf

Postby 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) ?
kanesoban
 
Posts: 2
Joined: Sun Jul 31, 2011 1:39 am

Re: simple problem with setf

Postby 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.
Ramarren
 
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland

Re: simple problem with setf

Postby 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) ?
kanesoban
 
Posts: 2
Joined: Sun Jul 31, 2011 1:39 am

Re: simple problem with setf

Postby 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/HyperSpec/Body/m_defset.htm#defsetf
Konfusius
 
Posts: 62
Joined: Fri Jun 10, 2011 6:38 am


Return to Common Lisp

Who is online

Users browsing this forum: Yahoo [Bot] and 2 guests

cron