1
votes

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
Odd requirements. Is it an exercise? If so can you show where it is from (that makes it easier to understand the context). - soegaard

2 Answers

1
votes

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
votes

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