3

我有这个表格的清单

( (1 3) (2 2) (3 1) (4 5) (5 1)))

我想删除一个项目让我们说(3 1)

所以结果将是

( (1 3) (2 2) (4 5) (5 1)))

我写了这样的东西,但我不知道为什么它不能正常运行。

(define (deleteItem list item)
  (cond
    ((equal? item (car  list)) (cdr list))
    (cons (car  list)(deleteItem(cdr list) item))))
4

3 回答 3

4

There's a built-in function for this, it's called remove:

(define lst
  '((1 3) (2 2) (3 1) (4 5) (5 1)))

(remove '(3 1) lst)
=> '((1 3) (2 2) (4 5) (5 1))

… But I guess you need to implement it from scratch. Some suggestions for your code:

  • You should not use list as a parameter name, that'll clash with a built-in function. Let's call it lst instead
  • You're missing the base case necessary form most list procedures: what happens if the list is empty?
  • You're also missing the else part in the last condition

With all the above fixes in place, the procedure will work:

(define (deleteItem lst item)
  (cond ((null? lst)
         '())
        ((equal? item (car lst))
         (cdr lst))
        (else
         (cons (car lst) 
               (deleteItem (cdr lst) item)))))

(deleteItem lst '(3 1))
=> '((1 3) (2 2) (4 5) (5 1))
于 2013-11-11T18:55:18.860 回答
1

该过程已经存在:

(remove '(3 1) '((1 3) (2 2) (3 1) (4 5) (5 1))))

否则,您的程序应如下所示:

(define (deleteItem item list) 
  (cond 
    ((empty? list) '())
    ((equal? item (car list)) (cdr list))
    (else (cons (car list) (deleteItem item (cdr list))))))

你错过了:

  • 基本情况,(空?列表)
  • 最后从句中的“else”

并且您不应该使用list作为变量名,因为它会影响内置过程list(但它会起作用)。

于 2013-11-11T18:59:12.750 回答
0

1)如果考虑输入列表可能是一个简单的列表,或者您只想删除嵌套列表顶层中的项目,例如:

delete 2 from (1 2 3 4) will return (1 2 3)
delete 2 from (1 2 3 (2 3) 3 2 4) will return (1 3 (2 3) 3 4)

正如我们在上面的第二个示例中看到的,它只是删除了嵌套列表顶层中的项目,在内部列表中,我们没有更改它。

这段代码应该是:

(define (deleteitem list1 item) 
( cond
    ((null? list1) ’())
    ((equal? (car list1) item) (deleteItem (cdr list1) item)) 
    (else (cons (car list1) (deleteitem (cdr list1) item)))
))

2)如果考虑输入列表可能是嵌套列表

例如:

input list: (1 2 3 (3 2 (2 4 (2 5 6) 2 5 6) 2 4) 2 3 (2 3 4))

并删除输入列表中的元素 2

the output list should be: (1 3 (3 (3 (5 6) 5 6) 4) 3 (3 4))

并且代码应该是:

(define (delete2 list1 item) 
    ( cond
    ((null? list1) '())
    ((pair? (car list1)) (con (delete2 (car list1) item) (delete2 (cdr list1) item)))
    ((equal? (car list1) item) (delete2 (cdr list1) item)) 
    (else (cons (car list1) (delete2 (cdr list1) item)))
))
于 2014-11-04T21:06:17.783 回答