LISP:删除列表中特定变量的所有出现

时间:2015-09-25 07:33:15

标签: lisp clisp

我必须编写一个函数,我可以从中删除列表中特定变量的所有出现 我在Ubuntu文本编辑器中进行编程 我的Lisp代码看起来像这样:

   #! /usr/bin/clisp


(defun my-remove(lst var1)
  (cond
   ((eq lst nil) nil)
   ((eq (car (cdr lst)) var1)(cons (car lst) (my-remove (cdr(cdr lst)) var1)))
    ( t (my-remove (cdr lst) var1))
  )
)

问题是它没有从列表

中删除任何元素

2 个答案:

答案 0 :(得分:2)

您需要查看列表中的第一个元素。 (car (cdr lst))不是列表中的第一个元素。

如果该元素与您要删除的元素相等,则需要跳过该元素并继续向下移动。如果它们不相等,您希望在继续列表的结果中包含该元素。

在这两种情况下,“继续向下列表”-bit应该是相同的,变化是否包含您正在查看的元素。

此外,您可能希望使用eqlequal而不是eq来比较元素。 eql是传统的默认比较器。

这看起来像是家庭作业,所以我不打算直接给你代码,但希望这可以帮助你朝着正确的方向推动。

答案 1 :(得分:2)

你想做什么:

if you have an empty list, return the empty list and do no more
if the very first element of the list has the value to be purged:
  return the result of calling the "purge this value" on the rest of the list
otherwise:
  create a new list with:
    the head of the list
    the result of purging the value from the rest of the list

你在做什么:

if there's an empty list, return the empty list and do no more
if the second element is the value to purge:
  create a new list consisting of:
    the head of the list
    the result of purging the value from the rest of the rest of the list
otherwise:
  return the result of purging the value from the rest of the list