此Common Lisp代码会发生什么情况? [英] What is happening with this Common Lisp code?

查看:104
本文介绍了此Common Lisp代码会发生什么情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码来模拟滚动六面模多次并计算每一面降落了多少次:

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

该函数在我第一次调用时效果很好,但是在后续调用中,变量myList从上次调用结束时具有的值开始,而不是像我认为的那样初始化为全零 let 语句.为什么会这样?

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?

推荐答案

这是在初始化程序中使用常量列表的结果:

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

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

将该行更改为:

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

,它将按照您的预期运行.第一行仅产生一次分配(因为它是一个常量列表),但是通过调用list可以强制每次输入该函数时进行分配.

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.

这可能会有所帮助,尤其是到最后. 成功的Lisp

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

问题的答案也可能会有所帮助.

The answer to this question may also be helpful.

这使用loop关键字collecting将每个迭代的结果收集到一个列表中,并将该列表作为loop的值返回.

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.

这篇关于此Common Lisp代码会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆