Search code examples
recursionracketunions

Creating a Union function in Racket


I'm trying to create a function in Racket that will read two lists and create a union of the elements in the two sets. This is the code I created to try and emulate this function:

(define (union set1 set2)
  (define unilst '())
  (letrec ([build (lambda (build1 build2 lst)
      (define a '())
      (define b '())
      (cond[(equal? build1 '()) 0]
           [(equal? build2 '()) 0]
           [else (set! a (first build1)) (set! b (first build2))
                 (cond
                      [(= a b) (set! lst (cons lst a))]
                      [else (set! lst (cons b lst))
                            (set! lst (cons a lst))])
                            (set! lst (cons (build (rest build1) (rest build2) lst) lst))])
                             lst)])+
    (set! unilst (build set1 set2 '()))
    unilst))

But the output I receive is: ((((3 4 2 3 1 2) 3 4 2 3 1 2) 2 3 1 2) 1 2)

Should I handle my recursion differently? Or is there something I'm missing?

Any help would be appreciated.


Solution

  • This looks like you've tried to write code in a different language but with Scheme syntax.
    There is almost never any point in using set!.

    The union of the sets s1 and s2 is

    • if s1 is empty, then s2
    • if s2 is empty, then s1
    • if (first s1) is a member of s2, then the union of (rest s1) and s2
    • otherwise, add (first s1) to the union of (rest s1) and s2
    (define (union s1 s2)
      (cond [(empty? s1) s2]
            [(empty? s2) s1]
            [(member (first s1) s2) (union (rest s1) s2)]
            [else (cons (first s1) (union (rest s1) s2))]))
    

    Test:

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

    Of course, if the output is supposed to be a set, the inputs must also be sets (i.e. no repeated values).