I'm a coder that has just started to learn code, and I am weeks into my Racket journey. I am implementing a function called my-subset? that has two parameters lst1 and lst2 that returns true just when every element of lst1 is a member of lst2. In this scenario the empty list is considered a subset of all other lists. For this function, I don't want to use the built in subset function.
Here is some code I have written personally, I have been unable to finish the code, and would appreciate some help. The first function is a helper function that is comparing a certain value with every element in a list. the second function is the actual subset function, I am having troubles with the part after cond as I don't know how to write a case where there is no subset and I have to return false. I am comparing a value from lst 1 to every value in lst 2.
(define (member x lst)
(cond [(empty? lst) #f]
[(equal? x (first lst)) #t]
[else (member x (rest lst))]))
(define (my-subset? lst1 lst2)
(cond [(empty? lst1) #t]
[(member (first lst1)(list lst2)) #t]
[else (my-subset? (rest lst1) (list lst2))]))
CodePudding user response:
You are so close to the solution:
(define (member x lst)
(cond
[(empty? lst) #f]
[(equal? x (first lst)) #t]
[else (member x (rest lst))]))
(define (my-subset? lst1 lst2)
(cond
[(empty? lst1) #t]
[(member (first lst1) lst2) (my-subset? (rest lst1) lst2)]
[else #f]))
That is, if the first element of lst1
is a member of lst2
, then
lst1
is a subset of lst2
if the rest of the elements of lst1
also are part of lst2
.