如何删除列表方案中的所有重复元素? [英] How to erase all duplicate elements in a list Scheme?

查看:41
本文介绍了如何删除列表方案中的所有重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的尝试是,

(define (remove-dup lst)
  (cond ((null? lst) '())
        ((null? (cdr lst)) (car lst))
        ((equal? (car lst) (car (cdr lst))) (remove-dup (cdr lst)))
        (else (cons (car lst) (remove-dup (cdr lst))))
        )

  )

我的列表是 (a b c a a c c c )我想要的是(a b c).任何想法?

My list was (a b c a a c c c ) What I want is (a b c). Any idea?

谢谢,

推荐答案

我会通过循环使用您构建的可见元素的第二个列表来解决这个问题.如果这是家庭作业,我会为你提供这个感到难过 - 了解递归的工作原理比仅仅拥有正确的答案更重要.

I'd approach this by looping with a second list that you build up of seen elements. I'll feel bad for giving this to you if this was homework though - it's more important to understand how recursion works than to just have the right answer.

(define (remove-dup ls)
  (let loop ((ls ls) (seen '()))
     (cond
       ((null? ls) '())
       ((memq (car ls) seen) (loop (cdr ls) seen))
       (else (cons (car ls) (loop (cdr ls) (cons (car ls) seen))))))

更新以适应您的意见 - 这可能不是最干净的解决方案,但应该让您了解它的工作原理.

Updated to accommodate your comments - this probably isn't the cleanest solution but should give you an idea of how it might work.

(define (rdup ls)
  (let loop ((ls ls) (current #f)) ; this is bad coding style, a "magic" variable you don't expect to see in your list
     (cond
       ((null? ls) '())
       ((null? (cdr ls)) (if (eq? (car ls) current) '() ls))
       ((eq? (car ls) (cadr ls)) (loop (cdr ls) (car ls)))
       ((eq? (car ls) current) (loop (cdr ls) current))
       (else (cons (car ls) (loop (cdr ls) (car ls)))))))

这篇关于如何删除列表方案中的所有重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆