I have been asked to write a recursive function that returns the powerset (a list of all subsets) of a set in the following exact order:
(powerset '(a b)) -> (() (b) (a) (a b))
(powerset '(a b c )) -> (() (c) (b) (b c) (a) (a c) (a b) (a b c))
We have already been asked to write a function consToAll(A L)
which 'conses' A
to every element of the list L
. Here is my consToAll
which works as it should:
(define consToAll
(lambda (A L)
(cond
( (null? L) '() )
( #t (cons (cons A (car L)) (consToAll A (cdr L))) )
)
)
)
This is the closest to a working powerset
function I have gotten:
(define (powerset L)
(cond
( (null? L) '() )
( #t (cons (powerset (cdr L)) (consToAll (car L) (powerset (cdr L)))) )
)
)
which outputs:
(powerset '(a b)) -> ((()) (a))
(powerset '(a b c)) -> (((()) (b)) (a ()) (a b))
EDIT
We are also given the following hint:
"Notice that (powerset '(b) ) is '( () (b) ). Also notice that (powerset '(a b)) is made up of (powerset '(b)) appended onto (powerset '(b) ) with 'a consed onto every element."
EDIT 2
I have found the following solution in Python which appears to do what I am trying to do. I am having trouble translating the last line into Lisp, however:
def powerset(seq):
if not seq:
return [[]]
ps = powerset(seq[1:])
return ps + [[seq[0]] + n for n in ps]