从列表中删除元素

时间:2013-12-19 22:29:40

标签: lisp

我要做的是从列表中删除一些元素,第一,第二,第四,第八,元素位置功率为2.我发现我最简单的解决方法就是构造结果如何列表应该看起来像没有破坏原始列表。这是我的代码,但它还没有工作,我得到一个类型错误。我正在使用contor知道我正在工作的列表中的哪个元素使用counter仅指定要删除元素的位置。我的问题是我做错了什么以及如何解决?

(defun remo(l)
  (defparameter e ())
  (setq contor 0)
  (setq counter 0)
  (dolist (elem l) (
                    (cond
                     (
                      ((or (< (expt 2 contor) counter) (> (expt 2 contor) counter)) 
                       ((push elem e) (setq contor (+ 1 contor))))
                     ))
                    (setq counter (+1 counter))
    )
    )
  (print e)
  )

2 个答案:

答案 0 :(得分:1)

(defun remo (l)
  (do ((power-of-2 1)
       (counter 1 (1+ counter))
       (result ())
       (sublist l (cdr sublist)))
      ((null sublist) (nreverse result))
    (if (= counter power-of-2)
        (setq power-of-2 (* 2 power-of-2))
      (push (car sublist) result))))

(remo '(1 2 3 4 5 6 7 8 9 10))
=> (3 5 6 7 9 10)

答案 1 :(得分:0)

我已经在https://stackoverflow.com/a/20711170/31615改进了你的另一次尝试,但既然你在这里提出了真正的问题,我提出以下解决方案:

(defun remove-if-index-power-of-2 (list)
  (loop :for element :in list
        :for index :upfrom 1        ; correct for language: "1st" is index 0
        :unless (power-of-2-p index)
        :collect element))

(defun power-of-2-p (number)
  "Determines whether number, which is assumed to be a nonnegative
integer, is a power of 2 by counting the bits."
  (declare (type (integer 0 *) number))
  (= 1 (logcount number)))