>>>> Josh Huber <huber(a)alum.wpi.edu> writes:
Given this defun:
(defun jmh-test-func ()
(let (tv)
(setq tv '((?a) (?b)))
(push "testme" (cdr (assoc ?a tv)))
tv))
Why does the value returned keep accumulating data from previous
calls?
Because you've just written self-modifying code: that cons is shared
with the _function definition_. Watch this:
(progn
(defun jmh-test-func ()
(let (tv)
(setq tv '((?a) (?b)))
(push "testme" (cdr (assoc ?a tv)))
tv))
(cl-prettyprint (symbol-function 'jmh-test-func))
(cl-prettyprint (jmh-test-func))
(cl-prettyprint (symbol-function 'jmh-test-func))
(cl-prettyprint (jmh-test-func))
(cl-prettyprint (symbol-function 'jmh-test-func))
(terpri)
)
and now this:
(progn
(defun sjt/safe-to-try-at-home ()
(let (tv)
(setq tv (copy-tree '((?a) (?b))))
(push "testme" (cdr (assoc ?a tv)))
tv))
(cl-prettyprint (symbol-function 'sjt/safe-to-try-at-home))
(cl-prettyprint (sjt/safe-to-try-at-home))
(cl-prettyprint (symbol-function 'sjt/safe-to-try-at-home))
(cl-prettyprint (sjt/safe-to-try-at-home))
(cl-prettyprint (symbol-function 'sjt/safe-to-try-at-home))
(terpri)
)
NB: it really does have to be `copy-tree', copy-sequence isn't good
enough.
>>>> "Simon" == Simon Josefsson
<jas(a)extundo.com> writes:
Simon> It would be good if the implementation triggered an error
Simon> for your form though[...].
I don't think so. This is a straightforward, although unintuitive,
consequence of setq's reference semantics.
--
Institute of Policy and Planning Sciences
http://turnbull.sk.tsukuba.ac.jp
University of Tsukuba Tennodai 1-1-1 Tsukuba 305-8573 JAPAN
My nostalgia for Icon makes me forget about any of the bad things. I don't
have much nostalgia for Perl, so its faults I remember. Scott Gilbert c.l.py