Fate Kyougo
Fate Kyougo

Reputation: 45

opposite of list-ref? (Racket)

Is there anything which acts as the opposite of list-ref, where instead of selecting certain values to add to a list, it'll take values away from a list?

I basically want to do the following

 (list 1 2 3 4 5 6 7) (list 3 6 7) -> (list 1 2 4 5)

Where the values in list two get deleted from list one. (preferred)

Since I will always start with a list that goes from 1 to n, the second list could also represent the location/position where a number on list 1 should be deleted. (less preferred)

I'm trying to create a code which will manipulate other functions to come up with these lists, so please be clear where each list is 'mentioned' in the code, as I sometimes get confused if people use x y and z and so forth with multiple lambda, local definitions, etc.


I have something here which does the opposite of what I want and I've been trying to alter it so instead of outputting the elements of x that are on y, it gives the elements of x which are NOT on y.

(define (selection x y)
  (filter  (lambda (e2)
            (ormap (lambda (e1) (equal? e1 e2))
                   y))
          x))

example:

        (list 1 2 3 4 5 6 7 8 9 10)
         (list 2 4 6 8 10))
    ->  (list 2 4 6 8 10))

Anybody have any ideas on how to change the output to what I need?

Upvotes: 1

Views: 377

Answers (3)

Rhyzomatic
Rhyzomatic

Reputation: 101

Here's a simple recursive function that achieves what you want:

(define remove-list-from-list (lambda (list remlist)
    (cond
        [(null? list) '()]
        [(member (car list) remlist) (remove-list-from-list (cdr list) remlist)]
        [else (cons (car list) (remove-list-from-list (cdr list) remlist))])))

Now you can use it like so:

> (remove-list-from-list (list 1 2 3 4 5 6 7) (list 3 6 7))
'(1 2 4 5)

Upvotes: 0

David Merinos
David Merinos

Reputation: 1295

remove will do the trick I guess.

> (remove* (list 1 2) (list 1 2 3 2 4 5 2))
'(3 4 5)

You can read the doc here.

Upvotes: 2

Greg Hendershott
Greg Hendershott

Reputation: 16260

It sounds like you're using lists as sets. You could instead use Racket sets, and use the set-subtract function:

#lang racket

(set-subtract (set 1 2 3 4 5 6 7)
              (set 3 6 7))
;; => (set 1 2 4 5)

Upvotes: 2

Related Questions