[英]Dr. Racket: Removing elements from a list using abstract list functions
So when given two lists, how do I remove elements in one list from another using only map, filter or foldr? 因此,当给定两个列表时,如何仅使用地图,过滤器或文件夹将一个列表中的元素从另一个列表中删除? I can't use explicit recursion or lambda either.
我也不能使用显式递归或lambda。
The lists consist of only numbers that are sorted in ascending order. 列表仅包含按升序排列的数字。
For example, if given (list 1 2 3) and (list 1 3 5), I want to remove all of the second list's elements from the first list. 例如,如果给定(列表1 2 3)和(列表1 3 5),我想从第一个列表中删除第二个列表的所有元素。 The output I want is (list 2).
我想要的输出是(清单2)。 If given (list 4 5 6) and (list 2 3 5), I would get (list 4 6).
如果给出(清单4 5 6)和(清单2 3 5),我会得到(清单4 6)。
I'm guessing the final code would be something like: 我猜最终的代码是这样的:
(define (fn-name list-one list-two)
(filter ... list-one))
Thanks! 谢谢!
Given that you're using Racket, we can write a simple solution in terms of some of the built-in abstract list functions and without using explicit lambda
s, we only need a little help from SRFI-26
. 鉴于您正在使用Racket,我们可以根据一些内置的抽象列表函数编写一个简单的解决方案,而无需使用显式的
lambda
,我们只需要SRFI-26
的一点帮助SRFI-26
。 Try this: 尝试这个:
(require srfi/26)
(define (difference lst1 lst2)
(filter-not (cut member <> lst2) lst1))
It works as expected: 它按预期工作:
(difference (list 1 2 3) (list 1 3 5))
=> '(2)
(difference (list 4 5 6) (list 2 3 5))
=> '(4 6)
You use filter, but you have to curry and invert member
so you cannot do it without lambda
. 您使用filter,但是必须咖喱和倒置
member
所以如果没有lambda
,您将无法做到。
(define (remove-elements needles haystack)
(filter (lambda (x) (not (member ...)))
haystack))
(define (remove-elements needles haystack)
(define (not-in-needles x)
(not (member ...)))
(filter not-in-needles haystack))
Both of these use lambda
twice! 这两个都使用
lambda
两次! Once for the define
of remove-elements
and once explicit / in not-in-needles
. 一次是为
remove-elements
define
,一次是显式/ not-in-needles
。 In your own example you use lambda
once too since (define (name . args) . body)
is the same as (define name (lambda args . body))
在您自己的示例中,由于
(define (name . args) . body)
与(define name (lambda args . body))
相同,因此您也使用了lambda
(define name (lambda args . body))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.