1

I am writing a recursive function that takes an element A and a list L and returns a list equal to L, but with every occurrence of A removed. Here is what I've written:

(define (remove A L)
    (cond   ( (eq? A (car L))       (remove A (cdr L)) )
            ( (not(eq? A (car L)))  (cons (car L) (remove A (cdr L))) )
            ( (null? L)             '() )
    )
)

When compiled and ran, I get the following error:

/tmp/compile/5c6515d8-e155-11e5-9605-aa00009baa05/input/main.scheme:2:21: In procedure remove:

/tmp/compile/5c6515d8-e155-11e5-9605-aa00009baa05/input/main.scheme:2:21: In procedure car: Wrong type argument in position 1 (expecting pair): ()
Machavity
  • 30,841
  • 27
  • 92
  • 100
KOB
  • 4,084
  • 9
  • 44
  • 88

1 Answers1

3

I figured it out:

The first check of the function needed to be (null? L) as car and cdr cannot work on any empty list.

(define (remove A L)
    (cond   ( (null? L)             '() )
            ( (equal? A (car L))       (remove A (cdr L)) )
            ( (not(equal? A (car L)))  (cons (car L) (remove A (cdr L))) )
    )
)
KOB
  • 4,084
  • 9
  • 44
  • 88
  • 1
    The last case in `cond` should be just `else`. In fact, some Scheme implementations wouldn't even allow it to be anything else. – mobiuseng Mar 03 '16 at 18:46