如何使用方案删除列表中的所有重复项(仅允许抽象列表函数) [英] How to remove all the duplicates in a list using scheme (only abstract list functions allowed)
问题描述
我知道如何以递归方式编写此代码.
I know how to write this in an recursive way.
(define (removed2 lst)
(cond
[(empty? lst) empty]
[(not (member? (first lst) (rest lst)))
(cons (first lst) (removed2 (rest lst)))]
[else (removed2 (rest lst))]))
so (removed2 (list 1 1 1 2 2 2 3 3 3 3 3 3)) 给出 (list 1 2 3)
so (removed2 (list 1 1 1 2 2 2 3 3 3 3 3 3)) gives (list 1 2 3)
但是,如何仅使用抽象函数(filter、foldr、map 和 build-list)来重写它?
However, how do you rewrite it only using abstract functions (filter, foldr, map, and build-list)?
我尝试使用过滤器,但它不起作用.
I tried to use filter but it just doesn't work.
推荐答案
可以使用 foldr
来解决这个问题,诀窍是知道在 lambda
中写什么:
It's possible to use foldr
for this, the trick is knowing what to write in the lambda
:
(define (removed lst)
(foldr (lambda (e a)
(if (not (member? e a))
(cons e a)
a))
'()
lst))
还要检查您的解释器是否具有内置功能,例如在 Racket 中您可以使用 remove-duplicates
.
Also check if your interpreter has a built-in function, for instance in Racket you can use remove-duplicates
.
这篇关于如何使用方案删除列表中的所有重复项(仅允许抽象列表函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!