So I have this program that has several definitions. Three of interest here are (set-equal? L1 L2), (union S1 S2) and (intersect S1 S2).
For set-equal? it should test if L1 and L2 are equal, where Two sets are equal if they contain exactly the same members, ignoring ordering so if the following is called: (set-equal? '(1 (2 3)) '((3 2) 1)), it should return true. However when I run my program on the above call returns false.
union of two sets is the set of all elements that appear in either set with no repetitions. So when the following is called: (union '((1 2 3)) '((3 2 1))), it should return ((1 2 3)). However when I run my program the on above call returns ((1 2 3) (3 2 1).
intersect of two sets is the set of elements that appear in both sets. So when the following is called: (intersect '((1 2 3)) '((3 2 1))), it should return ((1 2 3)). However when I run my program on the above call it returns ().
Some of my other test cases do work as intended. However, not all, therefore, the program is not quite correct. I am really new to Racket, and find it a bit confusing. I am not sure quite how to resolve the issues mentioned. I am thinking perhaps I need another helper function, but what would it do? And more importantly, how?
My problem seems to be when sets contain other sets, and that is what I am not sure exactly how to deal with.
The code is below.
; Tests if x is in L where L is a set, represented as a list
(define (member? x L)
(if (null? L)
#f
(cond
[(eq? x (car L)) #t]
(else (member? x (cdr L))
))))
; Test whether L1 is a subset of L2
(define (subset? L1 L2)
(if (null? L1)
#t
(and (member? (car L1) L2)
(subset? (cdr L1) L2)
)))
; Test whether L1 and L2 are equal
(define (set-equal? L1 L2)
(and (subset? L1 L2)
(subset? L2 L1)
))
; Join two sets together
(define (union S1 S2)
(if (null? S1)
S2
(cond
[(member? (car S1)S2) (union (cdr S1)S2)]
(else (cons (car S1) (union (cdr S1)S2)))
)))
; Return the intersection of two sets
(define (intersect S1 S2)
(if (null? S1)
'()
(cond
[(member? (car S1)S2)
(cons (car S1) (intersect (cdr S1)S2))]
(else (intersect(cdr S1)S2))
)))
I appreciate all your help. Thank you