When using foldr
you don't have to test if the input list is empty, foldr
takes care of that for you. And this seems like a job better suited for filter
:
(define (subset_length_n n lst)
(filter (lambda (e) (= (length e) n))
(powerset lst)))
If you must, you can use foldr
for this, but it's a rather contrived solution. You were very close to getting it right! in your code, just change the lambda
's parameters, instead of (x y)
write (y x)
. See how a nice indentation and appropriate parameter names go a long way toward writing correct solutions:
(define (subset_length_n n lst)
(foldr (lambda (e acc)
(if (= (length e) n)
(cons e acc)
acc))
empty
(powerset lst)))
Anyway, it works as expected:
(subset_length_n 4 '(1 2 3 4 5))
=> '((1 2 3 4) (1 2 3 5) (1 2 4 5) (1 3 4 5) (2 3 4 5))