hash__x
hash__x

Reputation: 83

How to make a destructive filter! in scheme?

I can get the filter works, but it does not do it destructively. Below are the starting code and test cases:

(define (filter! f s)
;;Your solution

Test cases:

(define (big x) (> x 5))

(define ints (list 1 10 3 8 4 7)) 
(define ints1 (cdr ints))


(define filtered-ints (filter! big ints))  
filtered-ints 
; expect (10 8 7) 

(eq? filtered-ints ints1) ; expect #t

Could anyone help please?

Upvotes: 1

Views: 368

Answers (1)

Óscar López
Óscar López

Reputation: 236140

This should work:

(define (filter! f lst)
  (let loop ((ans lst))
    (cond ((null? ans)
           ans)
          ((not (f (car ans)))
           (loop (cdr ans)))
          (else
           (scan-in f ans (cdr ans))
           ans))))

(define (scan-in f prev lst)
  (if (pair? lst)
    (if (f (car lst))
        (scan-in  f lst  (cdr lst))
        (scan-out f prev (cdr lst)))))

(define (scan-out f prev lst)
  (let loop ((lst lst))
    (if (pair? lst)
        (if (f (car lst))
            (begin (set-cdr! prev lst)
                   (scan-in  f lst (cdr lst)))
            (loop (cdr lst)))
        (set-cdr! prev lst))))

I adapted the above from the filter! procedure in SRFI 1: List Library. Notice that if you're using Racket a thing or two needs to be modified for the above code to work properly. For example, Racket no longer supports set-cdr! and you'll have to use set-mcdr! instead.

Upvotes: 1

Related Questions