LISP功能影响其他功能 [英] LISP function affecting other function

查看:76
本文介绍了LISP功能影响其他功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,当我调用函数fillBoard时,它似乎可以按需填充传递给它的列表,但是它有一个很奇怪的副作用.一旦以某种方式调用fillBoard,clearBoard函数将仅返回fillBoard返回的列表.另外,如果我再次调用fillBoard,它将继续更新clearBoard中返回的值.

I noticed that when I call the function fillBoard, it seems to work as it fills the list passed to it as I want, but it has a very weird side effect. Somehow once fillBoard is called, the clearBoard function will only return the list returned by fillBoard. Additionally if I call fillBoard again it will continue to update the value returned in clearBoard.

据我了解,每次在调用list变量时都应该有一个清晰的新实例,因此我看不到如何修改它或如何存储新值.

As far as I understand, there should be a new instance of the list variable in clear everytime its called, so I don't see how its being modified or how its storing a new value.

我正在传递fillBoard一个像((0 0 0 0)(0 0 0 0)(0 0 0 0)(0 0 0 0))的空列表,它将返回一个像((1 2 3 0)(0 6 0 0)(0 0 0 0)(0 0 0 0)),这就是clearBoard返回的内容.

I am passing fillBoard an empty list like ((0 0 0 0) (0 0 0 0) (0 0 0 0) (0 0 0 0)), and it will return a list like ((1 2 3 0) (0 6 0 0) (0 0 0 0) (0 0 0 0)), which is then what clearBoard returns.

(defun fillBoard (list)

   (let ((numVals (+ 4 (random 3)))
         (rand 0)
     (val1 0)
     (val2 0))

     (dotimes (x numVals)

     (setf val1 (random 3))
     (setf val2 (random 3))
     (setf rand (nth val1 (nth val2 soln)))

     (prin1 rand)
     (write-line " ")


     (if (= (nth val1 (nth val2 list)) 0)
     (setf (nth val1 (nth val2 list)) rand)))
      list))



(defun clearboard ()
   (let (( list '((0 0 0 0) (0 0 0 0) (0 0 0 0) (0 0 0 0))))
    list))

通过将clearBoard传递给列表,然后将其直接设置为空白板(而不是局部变量),然后返回该值,我似乎确实可以缓解此问题.但是,我仍然对最初一期中发生的事情感到好奇

I did seem to alleviate the issue by having clearBoard be passed a list then setting it directly to the blank board as opposed to a local variable, then returning that instead. However, I am still curious as to how what was happening in the original issue

推荐答案

clearboard返回的列表定义为常量结构.在fillBoard中修改它时,您不是在修改副本,而是结构本身.改为使用

The list returned by clearboard is defined as a constant structure. When you modify it in fillBoard, you are not modifying a copy, but the structure itself. Generate the board instead with

(loop repeat 4 collect (make-list 4 :initial-element 0))

这篇关于LISP功能影响其他功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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