Scheme如何从列表中删除元素?

时间:2010-12-15 15:18:44

标签: scheme

(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))

我想要的输出是

  1. (b c d)
  2. (越多你练得越好)
  3. ((狗猫)老鼠(大象)(猫))
  4. (天气可以(多雨)晴天多云和寒冷)
  5. 但是有很多错误,请帮帮我,谢谢

3 个答案:

答案 0 :(得分: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))))))

答案 1 :(得分: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))))))

如果这不是您想要的,也许您可​​以指定哪些是错误的。你一直说某些事情或许多事情是错误的,但没有具体说明是什么。例如,您可以指定您希望四个示例的输出结果。

答案 2 :(得分:0)

你需要一个基本案例,即使你找到了你想要的atm,你仍然希望继续通过列表递归。

(define (delete atm lis)
  (cond
   ((null? lis) '())
   ((eq? atm (car lis)) (delete atm (cdr lis)))
   (else (cons (car lis) (delete atm (cdr lis))))))
相关问题