Dustin
Dustin

Reputation: 103

What is happening with this Common Lisp code?

I've written the following bit of code to simulate rolling a six-sided die a number of times and counting how many times each side landed up:

(defun dice (num)
  (let ((myList '(0 0 0 0 0 0)))
    (progn (format t "~a" myList)
           (loop for i from 1 to num do
                 (let ((myRand (random 6)))
                   (setf (nth myRand myList) (+ 1 (nth myRand myList)))))
           (format t "~a" myList))))

The function works great the first time I call it, but on subsequent calls the variable myList starts out at the value it had at the end of the last call, instead of being initialized back to all zeros like I thought should happen with the let statement. Why does this happen?

Upvotes: 10

Views: 520

Answers (3)

steve
steve

Reputation: 57

like the post above, the compiler allocates the 0 as constant space. I used to know some tricks for this, one would be make it a macro such:

`',(list 0 0 0 0 0)
=>
 ?? (I forget and don't have the other machine on to check)

or wrapped in an (eval-when (compile)) ... )

also

 (list 0 0 0 0 0) 
=>
  #.(list 0 0 0 0)

I don't know if this still works (or ever worked). The are also some implentation macros or compiler macros that could help keep the alloaction size constant but the data variable. Don't rememeber off the top of my head anymore.

remeber to use fill (like bzero in c).

Upvotes: -1

asm
asm

Reputation: 8898

This is a result of using a constant list in the initializer:

(let ((myList '(0 0 0 0 0 0)))

Change that line to:

(let ((myList (list 0 0 0 0 0 0)))

and it will behave as you expect. The first line only results in an allocation once (since it's a constant list), but by calling list you force the allocation to occur every time the function is entered.

edit: This may be helpful, especially towards the end. Successful Lisp

The answer to this question may also be helpful.

This uses the loop keyword collecting which collects the results of each iteration into a list and returns the list as the value of the loop.

Upvotes: 13

Michael Markert
Michael Markert

Reputation: 4026

SBCL tells you what's wrong:

* (defun dice (num)
  (let ((myList '(0 0 0 0 0 0)))
    (progn (format t "~a" myList)
           (loop for i from 1 to num do
                 (let ((myRand (random 6)))
                   (setf (nth myRand myList) (+ 1 (nth myRand myList)))))
           (format t "~a" myList))))
; in: DEFUN DICE
;     (SETF (NTH MYRAND MYLIST) (+ 1 (NTH MYRAND MYLIST)))
; ==>
;   (SB-KERNEL:%SETNTH MYRAND MYLIST (+ 1 (NTH MYRAND MYLIST)))
; 
; caught WARNING:
;   Destructive function SB-KERNEL:%SETNTH called on constant data.
;   See also:
;     The ANSI Standard, Special Operator QUOTE
;     The ANSI Standard, Section 3.2.2.3
; 
; compilation unit finished
;   caught 1 WARNING condition

DICE

So in essence: Don't call destructive functions (here setf) on constant data.

Upvotes: 8

Related Questions