hotshot146
hotshot146

Reputation: 45

Scheme union two lists

I am writing a scheme program that takes two lists and displays the union of the lists. This is my code.

(define (union a b)
  (cond ((null? b) a)
        ((element? (car b) a)
         (union a (cdr b)))
        (else (union (cons (car b) a) (cdr b)))))

When I go to call the method using (union '(1 2 3) '(2 4 2))I get an error that reads

Exception: variable element? is not bound. 

What am I doing wrong when I call the method? Thank you.

Upvotes: 1

Views: 4615

Answers (1)

rnso
rnso

Reputation: 24623

It only means that definition of "element?" is not found. Replacing it with "member" (a built-in function in Racket) makes it work:

(define (union a b)
  (cond ((null? b) a)
        ((member (car b) a)
         (union a (cdr b)))
        (else (union (cons (car b) a) (cdr b)))))

(union '(1 2 3) '(2 4 2))

Output:

'(4 1 2 3)

Upvotes: 1

Related Questions