简体   繁体   中英

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 xy 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?

It sounds like you're using list s as sets. You could instead use Racket set s, 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)

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 .

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)

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