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)))
It seems to me the part
(setf a (remove-if #'XXX a))
can be replaced by
(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-IFis mostly a destructive version ofREMOVE-IF.REMOVE-IFreturns a freshly consed sequence, which does not contain the removed elements.DELETE-IFmay return a sequence which is reused.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-IFoperation 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.