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

后端 未结 2 782
傲寒
傲寒 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:14

    This problem will be simpler if you introduce a helper function.

    I recommend something like this (where angle brackets mean you need to fill out the details):

    (define (remove-duplicates x)
      (cond
        [                              '()]  ; no duplicates in empty list
        [                       x]    ; no duplicates in a list with one element
        [  (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
        [                   '()]                 ; e is not the first element of x
        [  (remove-from-front e (cdr x))] ; skip duplicate
        [else                           (remove-duplicates x)]))       ; no more es to remove
    

提交回复
热议问题