What is happening with this Common Lisp code?

后端 未结 3 2036
野性不改
野性不改 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 10:56

    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.

    0 讨论(0)
  • 2021-02-20 11:14

    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).

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题