我是新来的LISP显然......我正在编写一个函数,它接受一个列表并返回该列表并删除所有重复项,所以(myPurge'(pacepc)) - >(aepc)
这是我的(已编辑)代码:
(defun myPurge (L)
(if (eq L nil) ;if empty return nil
nil
(if(eq (car L)(car(cdr L)) ) ;if I find a match call function on
;rest of list
(myPurge (cdr L))
;else return that term and than call on
(progn ;rest of list
(car L)
(myPurge(cdr L)) ))))
* BUTTTTTTTT,当我调用此函数时,我得到NIL
!
* :
为什么我会NIL
而不是返回car L
?
******谢谢大家,这是我最终使用的完成代码(它使用了另一个函数' myMember'我之前定义过。******
(defun myPurge (L)
(if (eq L nil)
nil
(if(myMember(car L)(cdr L))
(myPurge(cdr L))
(cons (car L)(myPurge(cdr L))))))))
****这里是myMember *****如果X是L
的成员,则返回true
(defun myMember (X L)
(if(eq L nil)
nil
(if(eq X(car L))
t
(myMember X(cdr L)) )) )
答案 0 :(得分:1)
重新格式化代码后如下所示:
(defun myPurge (L)
(if (eq L nil)
nil
(if (eq (car L) (car (cdr L)))
(myPurge (cdr L))
(car L)
(myPurge (cdr L)))))
如您所见,使用4个参数调用最后一个if
。但是if
只需要3个参数(条件,然后是部分,否则是部分)。
答案 1 :(得分:0)
您的代码:
(defun myPurge (L)
(if (eq L nil) ;if empty return nil
nil
(if(eq (car L)(car(cdr L)) ) ;if I find a match call function on rest
;of list
(myPurge (cdr L))
;else return that term and than call on
(progn ;rest of list
(car L)
(myPurge(cdr L)) ))))
正确缩进/格式化/命名:
(defun my-purge (list)
(if (null list)
nil
(if (eql (first list) (second list))
(myPurge (rest list))
(progn
(first list)
(my-purge (rest list))))))
什么看起来很奇怪?请参阅下面的评论。
(defun my-purge (list)
(if (null list)
nil
(if (eql (first list) (second list))
(myPurge (rest list))
(progn
(first list) ; <- what does this do?
(my-purge (rest list))))))
奖励:你可以摆脱嵌套的IF:
(defun my-purge (list)
(cond ((null list)
nil)
((eql (first list) (second list))
(myPurge (rest list)))
(t
(first list)
(my-purge (rest list)))))