2
votes

I have a list that is filled with lists, some of which are null. My function is going through the main list and checking if there are any empty lists. If empty, it eliminates them (or should). I keep getting a car: contract violation error that tells me it is expecting a pair but getting a '(). I am not sure how to change it to not get this error.

       (define (take-out-nulls alist)
        (cond ((null? (car alist)) (take-out-nulls (cdr alist)))
         (#t (cons (car alist)(take-out-nulls (cdr alist))))))
2

2 Answers

3
votes

You have a recursion without a termination test, that is your function continues to ask for the car of alist even at the end of it.

Simply add such test to the function:

(define (take-out-nulls alist)
  (cond ((null? alist) '())
        ((null? (car alist)) (take-out-nulls (cdr alist)))
        (#t (cons (car alist) (take-out-nulls (cdr alist))))))

(take-out-nulls '(a () () b c ()))  ; => (a b c)
0
votes

You could also use

(define (take-out-nulls alist)
  (filter (λ (x) (not (empty? x))) alist))

(take-out-nulls '(a () () b c ())) ;=> (a b c)