多列表评估错误
我是一名 CommonLisp 菜鸟,有一个问题。我有下面这两个功能。
辅助函数:
(defun make-rests (positions rhythm)
"now make those positions negative numbers for rests"
(let ((resultant-rhythm rhythm))
(dolist (i positions resultant-rhythm)
(setf (nth i resultant-rhythm) (* (nth i resultant-rhythm) -1)))))
和主要函数:
(defun test-return-rhythms (rhythms)
(let ((positions '((0 1) (0)))
(result nil))
(dolist (x positions (reverse result))
(push (make-rests x rhythms) result))))
当我运行 (test-return-rhythms '(1/4 1/8))
时,它的计算结果为: ((1/4 -1 /8) (1/4 -1/8))
但是,我期望: (test-return-rhythms '(1/4 1/8))
评估为: ((-1/4 -1/8) (-1/4 1/8))
。
我做错了什么?
I'm a CommonLisp noob with a question. I have these two functions below.
A helper function:
(defun make-rests (positions rhythm)
"now make those positions negative numbers for rests"
(let ((resultant-rhythm rhythm))
(dolist (i positions resultant-rhythm)
(setf (nth i resultant-rhythm) (* (nth i resultant-rhythm) -1)))))
And a main function:
(defun test-return-rhythms (rhythms)
(let ((positions '((0 1) (0)))
(result nil))
(dolist (x positions (reverse result))
(push (make-rests x rhythms) result))))
When I run (test-return-rhythms '(1/4 1/8))
, it evaluates to: ((1/4 -1/8) (1/4 -1/8))
However, I expected: (test-return-rhythms '(1/4 1/8))
to evaluate to: ((-1/4 -1/8) (-1/4 1/8))
.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
make-rests
实现具有破坏性。因此,如果您运行测试,第二次迭代将看到
(-1/4 -1/8)
和(make-rests '(0) '(-1/4 - 1/8))
返回(1/4 -1/8)
。在make-rests
中使用let
不会复制列表,它只是创建一个引用它的新绑定。在let
中使用copy-list
,或者首先编写一个非破坏性版本:Your implementation of
make-rests
is destructive.So, if you run your test, the second iteration will see
(-1/4 -1/8)
, and(make-rests '(0) '(-1/4 -1/8))
returns(1/4 -1/8)
. Your use oflet
inmake-rests
does not copy the list, it just creates a new binding that references it. Usecopy-list
in yourlet
, or write a non-destructive version in the first place: