2

I am trying to remove a given symbol from a list.

Here is the code i wrote:

(define member?
  (lambda (in-sym in-seq)
    (if (and (symbol? in-sym) (sequence? in-seq))
        (if (null? in-seq)
            '()
            (append 
             (if (equal? in-sym (car in-seq)) '() (list (car in-seq))) 
             (member? in-sym (cdr in-seq)))))))

It turns out that i remove all occurences of the given symbol although i want to remove only the first occurence. Can somebody help me with this?

4

2 回答 2

3

您可以为此使用内置程序,检查您的解释器是否提供remove

(remove 'b '(a b b c b))
=> '(a b c b)

现在,如果您打算自己实现该功能,我建议您将问题分成两部分:一个过程检查该过程是否可以执行(如果inSymbol是一个符号并且inSeq是一个序列),另一个remove-member执行实际删除数据:

(define member?
 (lambda (inSym inSeq)
   (if (and (symbol? inSym) (sequence? inSeq)) ; can remove?
       (remove-member inSym inSeq)             ; then remove!
       'can-not-remove))) ; otherwise, present an error message

(define remove-member
  (lambda (inSym inSeq)
    (cond ((null? inSeq)
           '())
          ((equal? (car inSeq) inSym)
           (cdr inSeq))
          (else
           (cons (car inSeq)
                 (remove-member inSym (cdr inSeq)))))))
于 2013-04-30T20:22:36.983 回答
2

你的问题是你( member? inSym ( cdr inSeq))是否找到了这个符号。你想要做的是:

(define member?
  (lambda (inSym inSeq)
    (if (and (symbol? inSym) (sequence? inSeq))
        (if (null? inSeq) '()
          (if (equal? inSym (car inSeq)) (cdr inSeq)
            (append (list (car inSec)) (member?  inSym (cdr inSeq)))
            )
          )
      )
    )
  )

即,如果您找到该符号,只需返回 (cdr inSeq),因为您已完成。

于 2013-04-30T20:26:59.860 回答