Search code examples
schemeracketr5rs

Scheme. Recursive equivalence checking in the list


I have a problem with the function that is to remove the first occurrence of the specified element from the list. And i cannot use equal. What i'm doing wrong?

 (define f
  (lambda (E X)
    (list? X)
    (check E X)))

(define check
  (lambda (E X)
    (cond ((eq?(cdr X) '()) 'no_occur)
          (#t (cond
                ((eq?(car X)E) (cdr X))
                (#t (cons '()
                          (cons (car X)
                                (check E (car X))))))))))

(f 'u '(k u l o))

I get this:
mcdr: contract violation
expected: mpair?
given: k


Solution

  • A solution with minimal changes. Note that the last call to check (check E (cdr X)) uses the cdr and not the car of X. Why?

    #lang racket
    (define f
      (lambda (E X)
        (if (list? X)
            (check E X)
            #f)))
    
    (define check
      (lambda (E X)
        (cond ((eq? X '()) 'no_occur)
              (#t (cond
                    ((eq? (car X) E) (cdr X))
                    (#t (cons (car X)
                              (check E (cdr X)))))))))
    
    (f 'u '(k u l o))