What is happening with this Common Lisp code?

后端 未结 3 2038
野性不改
野性不改 2021-02-20 10:30

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)
         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-20 11:20

    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.

提交回复
热议问题