方案:从列表中删除重复的数字 [英] Scheme: Remove duplicated numbers from list

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

问题描述

我写了这段代码从 en 创建一个列表

 (define (创建列表e)
e)

但是我需要它来删除任何重复的数字从这个块本身的列表中。



我已尝试搜索几个小时,找不到解决方案,而不在其他块上放置数十行代码。 p>

例如,我的输入是

 (create-list。2 2 3 5 5)

我需要创建的列表为(2 3 5) (2 2 3 5 5)...



数字的顺序并不重要。

解决方案

基本上,您需要执行以下操作:

 (define(create-list) e)(重复数据删除))

我可以想到一个非常简单但可能无效率的方法:

 (define(dedupe e)
(if(null?e)'()
(cons(car e)(重复数据删除(filter(lambda(x) x(car e)))
(cdr e))))))

如果您不能使用现有的功能,例如 filter ,您可以自己做一个:

 (else(my-filter pred(cdr ls)))))


I wrote this code to create a list from en number of arguments given

(define (create-list . e)
   e)

But I need it to remove any duplicated numbers from the list within this block itself.

I have tried and searched for hours and can't find a solution without placing dozens of lines of code on other blocks.

For example let's say my input is

(create-list . 2 2 3 5 5 )

I need the list created to be '(2 3 5) and not '(2 2 3 5 5 )...

The order of the numbers doesn't matter.

解决方案

Basically, you need to do something like:

(define (create-list . e) (dedupe e))

I can think of a really simple but probably inefficient way to do this:

(define (dedupe e)
  (if (null? e) '()
      (cons (car e) (dedupe (filter (lambda (x) (not (equal? x (car e)))) 
                                    (cdr e))))))

If you can't use existing functions like filter, you can make one yourself:

(define (my-filter pred ls) 
  (cond ((null? ls) '())
        ((pred (car ls)) (cons (car ls) (my-filter pred (cdr ls))))
        (else (my-filter pred (cdr ls)))))

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

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