Home > Net >  How to check if a set1 is a subset of set2 in Scheme?
How to check if a set1 is a subset of set2 in Scheme?

Time:02-12

I tried to write a code to return 'true' if set1 is a subset of set2.

for example: (subset '(a b) '(a c b d)) --> #t (subset '(a b) '(a c d)) --> #f

Here's what I did, can someone enlighten me why isn't it working?

(define (subset lst1 lst2)
  (cond ((null? lst2) #f)
        ((member (car lst1)  lst2)
         (subset  (cdr lst1)  lst2)
         #t)
        (else #f)))

CodePudding user response:

    ((member (car lst1) lst2)
     (subset (cdr lst1) lst2) 
     #t)

true has no reason there. You reduce the problem to a subproblem.

Also, no need to check (null? lst2), as you do not loop over lst2. The final condition must check lst1 instead.

I would write so:

(define (subset lst1 lst2)
  (or (null? lst1)
      (and (member (car lst1) lst2)
           (subset (cdr lst1) lst2)))))
  • Related