则从列表中删除多个字符

则从列表中删除多个字符

本文介绍了如果它们在Scheme中彼此相邻,则从列表中删除多个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须制作一个Dr.Racket程序,如果它们跟自己相同的字母,则从列表中移除字母。例如:(z z f a b b d d)将成为
(z f a b d)。我已经编写了代码,但它所做的只是删除列表中的第一个字母。
任何人都可以帮助?

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)


推荐答案

(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) / code>是(car(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)))]))

这篇关于如果它们在Scheme中彼此相邻,则从列表中删除多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:34