سؤال

I need to create a function that filters out predicates in Scheme. For example (filter-out number? '(a 2 #f b 7)): the output would be (a #f b)

The function that I have returns a list of what was filtered out. How can I change this to get what I need? Thanks

(define (filter pred lst)
  (reverse (filter-help pred lst '())))

(define (filter-help pred lst res)
  (cond ((null? lst) res)
        ((pred (car lst)) 
           (filter-help pred (cdr lst)  (cons (car lst) res)))
        (else 
           (filter-help pred (cdr lst)  res))))
هل كانت مفيدة؟

المحلول

Your functions work if you just negate the predicate on one line of filter-help (and change the name filter to filter-out as intended):

(not (pred (car lst)))

instead of

((pred (car lst))

Though you could write this more briefly by using the built-in filter with a lambda function:

(define (alt-filter-out pred lst)
        (filter (lambda (x) (not (pred x))) lst))

Hope this helps!

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top