What is happening with this Common Lisp code?

后端 未结 3 2037
野性不改
野性不改 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.

提交回复
热议问题