【问题标题】:removing a specific element in a list multiple times not case sensitive多次删除列表中的特定元素不区分大小写
【发布时间】:2014-12-04 16:57:05
【问题描述】:

我一直在编写这段代码,并研究如何递归地运行一个函数并让它返回一个删除了单词“the”的列表。

我是 Common Lisp 的新手,我已经了解了 setq, cons, cond, equal, carcdr 等基本功能。

当我运行代码时,我不断得到列表中的最后一个元素,如果后面有一个the,它就会跟随。

谁能告诉我我做错了什么并引导我朝着正确的方向前进?

允许的 Common Lisp 结构是:CONDEQUAL(或 EQUALP)、CONSCARCDR,以及 Common Lisp 的一些基本原始构建块。

我不能使用任何预定义的函数来进行实际的消除。

这应该是它的样子.. 示例运行:

(filter-out-the   '(There are the boy and THE girl and The Rose))

返回:

(THERE ARE BOY AND GIRL AND ROSE)

这是我的代码:

(defun list_member (x L)
  (cond ((null L) nil)                      
        ((equal x (car L))                 
         (list_member x (cdr L)))           
        (T (cons (car l) (list_member x (cdr L))))))  


(defun filter-out-the (L)
  (setq x '(the))
  (cond ((null L) nil)                             
        ((list_member (car x) (cdr L )) (filter-out-the (cdr L))) 
        (T (cons (car L) (filter-out-the (cdr L))))))

【问题讨论】:

  • 该语言称为Common Lisp,而不是CLISP
  • 要在 Lisp 中编程,您需要缩进代码。编辑应该帮助你。请不要发布未缩进的代码。
  • filter-out-the 中的变量 x 未定义。你需要定义它...
  • 你能解释一下list_member应该做什么吗?如果是,请解释一下。你测试了吗?怎么样?
  • 我假设我应该使用(let ((x the))

标签: lisp common-lisp


【解决方案1】:

函数只是你的第一个函数,命名更好:

(defun my-remove (item list)
  (cond ((null list) nil)                      
        ((equal item (first list))                 
         (my-remove item (rest list)))           
        (T (cons (first list)
                 (my-remove item (rest list))))))  

你可以这样称呼它:

CL-USER 36 > (my-remove 'the '(there are the boy and the girl and the rose))
(THERE ARE BOY AND GIRL AND ROSE)

【讨论】:

  • 我发现让my-remove 有两个参数更容易做到这一点。如果只使用一个参数并让函数只删除单词“the”,您将如何做到这一点。
  • @triniplayaz1:你写了一个函数(一个参数),它调用my-remove
  • 好的,我知道了。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
  • 2015-04-08
相关资源
最近更新 更多