Remove multiple characters from the list if they are next to each other in the pattern

I need to make Dr. Racket, which removes letters from the list if they follow the same letter as itself. For example: (zzfabbdd) becomes (zfabd). I wrote code for this, but all it does is remove the first letter from the list. Can anyone help?

#lang racket 
(define (remove-duplicates x)
(cond ((null? x)
     '())
    ((member (car x) (cons(car(cdr x)) '())))
     (remove-duplicates (cdr x))
    (else
     (cons (car x) (remove-duplicates (cdr x))))))

(define x '( b c c d d a a))
(remove-duplicates x)
+4
source share
2 answers
(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)not suitable for (car (cdr x))if you did not know this.

In addition, pattern matching makes list deconstruction often more readable. In this case, not so much, but it is even 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)))]))
+2
source

, .

- ( , ):

(define (remove-duplicates x)
  (cond
    [ <x is empty>                             '()]  ; no duplicates in empty list
    [ <x has one element>                      x]    ; no duplicates in a list with one element
    [ <first and second element in x is equal> (cons (car x) (remove-from-front (car x) (cdr x)))]
    [else                                      (cons (car x) (remove-duplicates (cdr x)))]))

(define (remove-from-front e x)
  (cond
    [ <x is empty>                  '()]                 ; e is not the first element of x
    [ <e equals first element of x> (remove-from-front e (cdr x))] ; skip duplicate
    [else                           (remove-duplicates x)]))       ; no more es to remove
+1

Source: https://habr.com/ru/post/1611072/


All Articles