0

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

soegaard
  • 30,661
  • 4
  • 57
  • 106
no_name
  • 31
  • 1
  • 5

2 Answers2

0

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))
soegaard
  • 30,661
  • 4
  • 57
  • 106
0
 (define f
  (lambda (E X)
    (if (list? X)
        (check E X)
        "Your error message")))


(define check
  (lambda (E X)
    (cond ((eq? (cdr X) '()) 'no_occur)          ; what if it's the last symbol?
          ((eq?(car X) E) (cdr X))               ; no need to nest cond's
          (else (cons (car X)                    ; In scheme we use else
                      (check E (cdr X)))))))     ; you search the rest of the 
                                                 ; list. This line cuased your
                     ; error message. You called check with X=k (the car of '(k u l o))

Also not I have removed the cons '() You don't need to cons the empty list every time. Also, note this test

> (f 'a '(k u l o))
 '(k u l . no_occur)

I leave it to you to solve this one. ;-P

Rptx
  • 1,159
  • 1
  • 12
  • 17