3

What is the difference between the following solutions (a setf function and a function)? Is one of them preferable, or are they only two ways to get the same result?

(defparameter *some-array* (make-array 10)) (defun (setf arr-index) (new-value index-string) (setf (aref *some-array* (parse-integer index-string)) new-value)) (defun arr-index-1 (index-string new-value ) (setf (aref *some-array* (parse-integer index-string)) new-value)) CL-USER> *some-array* #(0 0 0 0 0 0 0 0 0 0) CL-USER> (setf (arr-index "2") 7) 7 CL-USER> (arr-index-1 "3" 5) 5 CL-USER> *some-array* #(0 0 7 5 0 0 0 0 0 0) 

Thank you for your answers.

1 Answer 1

6

The setf function works as a place (aka. generalized reference). This means it can be used with modify macros such as INCF or ROTATEF. You do also have to write a corresponding getter function for them to work though.

(defparameter *some-array* (make-array 10)) (defun arr-index (index-string) (aref *some-array* (parse-integer index-string))) (defun (setf arr-index) (new-value index-string) (setf (aref *some-array* (parse-integer index-string)) new-value)) CL-USER> (setf (arr-index "3") 10) 10 CL-USER> (incf (arr-index "3")) 11 CL-USER> (incf (arr-index "3")) 12 CL-USER> (rotatef (arr-index "3") (arr-index "6")) NIL CL-USER> (incf (arr-index "3") 100) 100 CL-USER> *some-array* #(0 0 0 100 0 0 12 0 0 0) 

A setf function is generally preferred unless you are, for some reason, making a stylistic choice not to use setf or modify macros.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.