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

前提是你 提交于 2019-12-01 20:52:34

问题


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). I have written 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)

回答1:


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



回答2:


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
    [ <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


来源:https://stackoverflow.com/questions/33052559/remove-multiple-characters-from-a-list-if-they-are-next-to-each-other-in-scheme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!