Dr. Racket: Deleting Items from a List Using Abstract List Functions

advertisements

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