2

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!

2
  • 2
    Odd requirements. Is it an exercise? If so can you show where it is from (that makes it easier to understand the context).
    – soegaard
    Jul 25, 2015 at 20:19
  • There's also function for that in srfi/1 called lset-difference, for those who don't want to write this function.
    – frayser
    May 27, 2023 at 2:23

2 Answers 2

1

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 lambdas, 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)
0
0

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))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.