常见Lisp:delete-if是否与setf + remove-if相同? [英] Common Lisp: is delete-if the same as setf + remove-if?

查看:96
本文介绍了常见Lisp:delete-if是否与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屋!

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