Re: Use of a counter in a list

[email protected]
Newsgroups gmane.lisp.steel-bank.general
Message-ID <ZkMywCAUS3DQA7UR@anomaly>
On 2024-05-14 at 09:29:59 +0000,
"steph.tougard via Sbcl-help" <[email protected]> wrote:

> Hi,
> 
> I don't understand why this code does not work with SBCL while it works perfectly with ABCL and CLISP
> 
> (let ((a '(0)))
> (defun inc-a () (incf (car a))) (defun a () (car a)))
> 
> On SBCL
> 
> CL-USER> (a)
> 0 (0 bits, #x0, #o0, #b0)
> CL-USER> (inc-a)
> 1 (1 bit, #x1, #o1, #b1)
> CL-USER> (a)
> 0 (0 bits, #x0, #o0, #b0)CL-USER>
> 
> On CLISP or ABCL
> 
> [2]> (a)
> 0
> [3]> (inc-a)
> 1
> [4]> (a)
> 1[5]>
> 
> Even more worrying to me, I get the same result with (sb-ext:atomic-incf), the (a) function always returns 0.
> 
> Please, can you explain to me like I'm 5 years old why it does not work on SBCL and why it works with other LISP compilers ?

You're binding A to a constant, and then modifying that constant.  I'm
no expert, but I'm pretty sure that that puts you into implementation
defined behavior, which means that different implementations might do
different things, and that you can't depend on any one implementation's
specific behavior.

To fix it, copy the list:

  (let ((a (copy-seq '(0))))
    ...)

That way, A is a mutable copy of the constant.

HTH,
Dan
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.