如何从Scheme中的列表中删除非重复元素? [英] How to remove non-duplicate elements from a list in Scheme?

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

问题描述

给定一个列表,

(define ll '(a a a b c c c d e e e e))

我想删除所有非重复元素,只留下重复元素的一个副本,即删除后,结果是

I want to remove all non-duplicate elements and leave only one copy of the duplicate one, i.e. after removing, the result would be

(a c e)

我的算法是:

  • 遍历列表,比较当前元素和下一个元素.

  • Traverse through the list, comparing current element with next element.

  • 如果它们相等,则cons 当前元素与下一个递归调用的列表.例如,

  • If they're equal, then cons the current element with the list of the next recursive call. For example,

(a a a b c)

从左向右移动,遇到aa.

Move from left to right, encounter a and a.

(cons a (remove-nondup (cddr lst)))

  • 否则,跳过当前和下一个元素.

  • Otherwise, skip current and next element.

    (remove-nondup (cddr lst))
    

  • 我遇到的问题是

    (define (remove-nondup lst)
      (if (>= (length lst) 2)
          (if (eq? (car lst) (cadr lst))
              (cons (car lst) (remove-nondup (cdr lst)))
              (remove-nondup (cddr lst)))
          lst))
    

    我遇到的问题是,如果连续元素超过 3 个,我将无法跟踪前一个前一个.所以我想知道我是否应该使用另一个程序来删除所有重复项?或者我可以把它们放在一个程序中?

    The problem that I'm having is if there are more than 3 consecutive elements, I have no way to keep track of the previous-previous one. So I wonder should I use another procedure to remove all duplicates? or I can just put them into one procedure?

    所以我目前的替代解决方案是,

    So my alternative current solution was,

    (define (remove-dup lst)
      (if (>= (length lst) 2)
          (if (eq? (car lst) (cadr lst))
              (cons (car lst) (remove-dup (cddr lst)))
              (cons (car lst) (remove-dup (cdr lst))))
          lst))
    
    (define (remove-nondup-helper lst)
      (if (>= (length lst) 2)
          (if (eq? (car lst) (cadr lst))
              (cons (car lst) (remove-nondup-helper (cdr lst)))
              (remove-nondup (cddr lst)))
          lst))
    
    ; call the helper function and remove-dup
    (define (remove-nondup lst)
      (remove-dup (remove-nondup-helper lst)))
    

    推荐答案

    这是我的解决方案:首先,抓取 bagify(任何版本都可以).然后:

    Here's my solution: first, grab bagify (any version will do). Then:

    (define (remove-singletons lst)
      (define (singleton? ass)
        (< (cdr ass) 2))
      (map car (remove singleton? (bagify lst))))
    

    remove 来自 SRFI 1.如果您使用 Racket,请先运行 (require srfi/1).或者,使用这个简单的定义:

    remove is from SRFI 1. If you're using Racket, run (require srfi/1) first. Or, use this simple definition:

    (define remove #f)   ; Only needed in Racket's REPL
    (define (remove pred lst)
      (cond ((null? lst) lst)
            ((pred (car lst)) (remove pred (cdr lst)))
            (else (cons (car lst) (remove pred (cdr lst))))))
    

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

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