Remove multiple characters from a list if they are next to each other in Scheme

后端 未结 2 784
傲寒
傲寒 2021-01-19 12:13

I have to make a Dr. Racket program that removes letters from a list if they are following the same letter as itself. For example: (z z f a b b d d) would become (z f a b d

2条回答
  •  不思量自难忘°
    2021-01-19 13:12

    (define (remove-dups x)
       (cond
         [(empty? x) '()]
         [(empty? (cdr x))  (list (car x))]
         [(eq? (car x) (cadr x))  (remove-dups (cdr x))]
         [else  (cons (car x) (remove-dups (cdr x)))]))
    

    (cadr x) is short for (car (cdr x)) in case you didn't know.

    Also, pattern matching makes list deconstruction often much more readable. In this case not so much, but it's still better than the other version:

    (define (rmv-dups x)
      (match x
        [(list)  (list)]
        [(list a)  (list a)]
        [(cons a (cons a b))  (rmv-dups (cdr x))]
        [__  (cons (car x) (rmv-dups (cdr x)))]))
    

提交回复
热议问题