schemenonblank

Removing null elements from the scheme list


(define filter-in
  (lambda (predicate list)
    (let((f
        (lambda (l)
          (filter-in-sexpr predicate l))))
    (map f list))))

(define filter-in-aux
  (lambda (pred lst)
    (if (null? lst) '()
        (cons (filter-in-sexpr pred (car lst))
              (filter-in-aux pred (cdr lst))))))

(define filter-in-sexpr
  (lambda (pred sexpr)
    (if (equal? (pred sexpr) #t)
            sexpr
            '())))

Calling (filter-in number? ’(a 2 (1 3) b 7)) produces ( () 2 () () 7).

How I can skip null elements from the generated list to get final outcome of (2 7) ?


Solution

  • The problem is that you're mapping filter-in-sxpr over the list. You can either run another filter pass to remove the nulls, or use a modified filter-in-aux like this:

    (define filter-in-aux
      (lambda (pred lst)
        (if (null? lst) '()
            (let ((h (filter-in-sexpr pred (car lst)))
                  (t (filter-in-aux pred (cdr lst))))
              (if (null? h) t
                  (cons h t))))))