常见Lisp:delete-if是否与setf + remove-if相同? [英] Common Lisp: is delete-if the same as setf + remove-if?
问题描述
以下代码生成从1到n的质数:
The following code generates prime from 1 to n:
(defun prime-list(n)
(let ((a)(b)(x (floor (sqrt n))))
(loop for i from (floor n 6) downto 1 do
(push (1+ (* 6 i)) a)
(push (1- (* 6 i)) a))
(loop while (<= (car a) x) do
(push (car a) b)
(setf a (remove-if #'(lambda(m)(or (= 0 (mod m (car a))) (> m n))) a)))
(append '(2 3) (reverse b) a)))
在我看来,这部分
(setf a (remove-if #'XXX a))
可以替换为
(delete-if #'XXX a)
我希望这可以使其更快.但是,当我进行更改时,该函数现在进入无限循环,并且永不返回.为什么?
And I hoped this would make it faster. However when I made that change the function now get into an infinite loop and never returns. Why?
推荐答案
如注释中所述,您需要设置变量.
As mentioned in the comments, you need to set the variable.
DELETE-IF
主要是REMOVE-IF
的破坏性版本. REMOVE-IF
返回一个新的精简序列,其中不包含已删除的元素. DELETE-IF
可能返回被重用的序列.
DELETE-IF
is mostly a destructive version of REMOVE-IF
. REMOVE-IF
returns a freshly consed sequence, which does not contain the removed elements. DELETE-IF
may return a sequence which is reused.
如果具有绑定到列表的变量,则仍需要设置结果.上面的函数返回结果,但是它们没有为结果设置变量.对于列表,DELETE-IF
操作的结果可以是空列表,并且没有副作用,因为变量指向非空列表时可以对其进行设置.
If you have a variable, which is bound to a list, you still need to set the result. Above functions return results, but they don't set variables to the result. In case of a list, the result of a DELETE-IF
operation can be the empty list and there is no way the side effect can be, that a variable can be set to it - when it was pointing to a non-empty list.
这篇关于常见Lisp:delete-if是否与setf + remove-if相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!