开发者

Scheme How to delete the elements from a list?

(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 y开发者_Python百科ou 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))

the output I want are

  1. (b c d)
  2. (more you practice better you will be)
  3. ( (dog cat) mouse (elephant) (cat))
  4. ( the weather can be (rainy) sunny cloudy and cold)

but there are lots of wrong , please help me, thank you


You are not actually removing anything. Your procedure is normally known as remq.

The following should work (untested):

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


The other two answers (which are identical, by the way) currently only work on the top level of the list. If you also want it to remove your atom from all nested lists, you have to search there too:

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

If this is not what you want, perhaps you can specify what exactly it is that is going wrong. You keep saying that something, or lots of things, are wrong, but not specifying what that is. For instance, you could specify what you expect the output of your four examples to be.


You need a base case and even when you find the atm you want, you still want to continue recursing through the list.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜