简体   繁体   中英

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.

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. The output I want is (list 2). If given (list 4 5 6) and (list 2 3 5), I would get (list 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 . 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 .

(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! Once for the define of remove-elements and once explicit / in 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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM