您实际上在做的是为一组大小 x 构建幂集。
幂集是所有可能子集的集合。例如, (list 1 2 3) 的幂集是 (list (list 1 2 3) (list 1 2) (list 1 3) (list 1) (list 2 3) (list 2) (list 3) empty) .
(一个集合是它自己的一个子集,而空集是所有集合的一个子集。)
为什么您正在做的事情描述了幂集是因为一个元素可以在或不在一个子集中。所以 apply (list true true true) to (list 1 2 3) 将返回 (list 1 2 3) 并且 (list false true true) 将返回 (list 2 3)。
这是我解决您问题的代码。
(define baselist (list (list true) (list false)))
;; List1 List2 -> List of Lists
;; Where List1 is any list of lists, and list2 is a list of lists of size 2
;; and all of the lists within list 2 has one element
(define (list-combination list-n list-two)
(cond [(empty? list-n) empty]
[else (cons (append (first list-n) (first list-two))
(cons (append (first list-n) (second list-two))
(list-combination (rest list-n) list-two)))]))
;; tflist Number -> List of Boolean Lists
;; creates baselistn
(define (tflist n)
(cond [(= 1 n) baselist]
[else (list-combination (tlist (sub1 n)) baselist)]))
所以 (tflist 3) 会返回你原来的问题。现在要制作一个powerset,您可以执行以下操作...
;; subset List1 ListofBooleans -> List
;; Determines which elements of a set to create a subset of
;; List1 and LoB are of the same length
(define (subset set t-f-list)
(cond [(empty? t-f-list) empty]
[(first t-f-list) (cons (first set) (subset (rest set) (rest t-f-list)))]
[else (subset (rest set) (rest t-f-list))]))
;;powerset set -> Powerset
;; produces a powerset of a set
(define (powerset set)
(local ((define upperbound (expt 2 (length set)))
(define tflist (tlist (length set)))
(define (powerset set n)
(cond [(= n upperbound) empty]
[else (cons (subset set (list-ref tflist n)) (powerset set (add1 n)))])))
(powerset set 0)))