2010-12-15 71 views
2
(define (delete atm lis) 
    (cond 

    ((eq? atm (car lis)) (cdr lis)) 
    (else (cons (car lis) (delete atm (cdr lis)))))) 

(delete 'a '(b c d a)) 
(delete 'the '(the more you practice the better you will be)) 
(delete 'cat '((dog cat) mouse cat (elephant) (cat) cat)) 
(delete 'rainy '(the weather can be (rainy) sunny cloudy and cold)) 

我想输出是Scheme如何从列表中删除元素?

  1. (BCD)
  2. (你练习得越多就越会是)
  3. ((狗猫)鼠标(大象)(CAT))
  4. (气候可能(雨天)晴天阴天和冷)

但有很多错误,请帮助我,谢谢

回答

1

你实际上并没有删除任何东西。您的程序通常被称为remq

以下应工作(未经测试):

(define (delete atm lis) 
    (cond 
    ((null? lis) lis) 
    ((eq? atm (car lis)) (delete atm (cdr lis))) 
    (else (cons (car lis) (delete atm (cdr lis)))))) 
+0

但是如果我想找到的原子不是列表中的第一个元素,它仍然有错误。你能告诉我为什么吗? – Lilo 2010-12-15 15:33:43

+1

@Lilo:你最好告诉我们什么是“错误的”,因为leppie的答案是正确的。 – erjiang 2010-12-16 02:25:28

0

你需要一个基本情况,甚至当你找到你想要的自动取款机,你还愿意继续通过列表递归。

(define (delete atm lis) 
    (cond 
    ((null? lis) '()) 
    ((eq? atm (car lis)) (delete atm (cdr lis))) 
    (else (cons (car lis) (delete atm (cdr lis)))))) 
+0

哎呀抱歉,这跟leppie's一样。我测试了这个,它工作。 – user479988 2010-12-15 16:13:39

1

另外两个答案(顺便说一句)目前只能在列表的顶层工作。如果你也希望它从所有嵌套列表中删除您的原子,你必须得有搜索:

(define (delete atm lis) 
(cond 
    ((null? lis) lis) 
    ((eq? atm (car lis)) (delete atm (cdr lis))) 
    ((list? (car lis)) (cons (delete atm (car lis)) (delete atm (cdr lis)))) 
    (else (cons (car lis) (delete atm (cdr lis)))))) 

如果这不是你想要的,也许你可以指定它到底是什么这是怎么了。你一直在说某件事或许多事情是错误的,但没有具体说明它是什么。例如,你可以指定你期望的四个例子的输出结果。